From 78d0d4bfb1d7fae2b6a23969bcb2f7055fb4fa23 Mon Sep 17 00:00:00 2001 From: Jaime Wren Date: Fri, 16 Jan 2026 09:37:10 -0800 Subject: [PATCH] Add table detailing AI rule file character limits for various tools (#179817) Co-authored-by: John Ryan --- docs/rules/README.md | 26 +++++- docs/rules/rules_10k.md | 174 ++++++++++++++++++++++++++++++++++++++++ docs/rules/rules_1k.md | 23 ++++++ docs/rules/rules_4k.md | 80 ++++++++++++++++++ 4 files changed, 301 insertions(+), 2 deletions(-) create mode 100644 docs/rules/rules_10k.md create mode 100644 docs/rules/rules_1k.md create mode 100644 docs/rules/rules_4k.md diff --git a/docs/rules/README.md b/docs/rules/README.md index 74550fea475..d36591c0d28 100644 --- a/docs/rules/README.md +++ b/docs/rules/README.md @@ -1,4 +1,26 @@ # AI rules for Flutter -This directory contains `rules.md`, the default set of AI rules for building -Flutter apps, following best-practices. +This directory contains the default set of AI rules for building Flutter apps, following best practices. + +* `rules.md`: The comprehensive master rule set. +* `rules_10k.md`: A condensed version (<10k chars) for tools with stricter context limits. +* `rules_4k.md`: A highly concise version (<4k chars) for limited contexts. +* `rules_1k.md`: An ultra-compact version (<1k chars) for very strict limits. + +## Device & Editor Specific Limits + +Different AI coding assistants and tools have varying limits for their "rules" or "custom instructions" files. *Last updated: 2026-01-05.* + +| Tool / Product | Rules File / Feature | **Soft / Hard Limit** | Notes & Sources | +| Tool / Product | Limit | Source | Notes | +| :--- | :--- | :--- | :--- | +| Aider | No Hard Limit | [Aider Conventions](https://aider.chat/docs/usage/conventions.html) | Limited by model context window. | +| Antigravity (Google) | 12,000 characters (Hard) | Internal Source | Validated via client-side error message. | +| Claude Code | No Hard Limit | [Claude Code Docs](https://support.claude.com/en/articles/11647753-understanding-usage-and-length-limits) | Uses `CLAUDE.md`. Context limited. | +| CodeRabbit | 1,000 characters (Hard) | [CodeRabbit Docs](https://docs.coderabbit.ai/pr-reviews/pre-merge-checks#ui-configuration) | Applied to "Instructions" field. | +| Cursor | No Hard Limit | [Cursor Docs](https://cursor.com/docs/context/rules) | Keep rules under 500 lines | +| Gemini CLI | 1M+ Tokens (Context) | [Vertex AI Docs](https://cloud.google.com/vertex-ai/generative-ai/docs/long-context) | Pactical limit is model context window. | +| GitHub Copilot | ~2 Pages (Soft) / 4k chars | [Copilot Docs](https://docs.github.com/en/copilot/customizing-copilot/adding-custom-instructions-for-github-copilot) | Chat: ~2 pages context. Code Review: 4000 char hard limit. | +| Goose | No Hard Limit | [Goose Docs](https://block.github.io/goose/) | Uses "summarize" or "truncate" context strategies. | +| JetBrains AI | No Hard Limit | [JetBrains AI Docs](https://www.jetbrains.com/help/idea/ai-assistant.html) | Context managed by AI Assistant; no fixed file size limit. | +| OpenAI (ChatGPT) | 1,500 characters | [OpenAI Help](https://help.openai.com/en/articles/8096356-chatgpt-custom-instructions) | Is there a character limit for custom instructions? | diff --git a/docs/rules/rules_10k.md b/docs/rules/rules_10k.md new file mode 100644 index 00000000000..bc744e8605a --- /dev/null +++ b/docs/rules/rules_10k.md @@ -0,0 +1,174 @@ +# AI Rules for Flutter + +You are an expert Flutter and Dart developer. Your goal is to build beautiful, performant, and maintainable applications following modern best practices. + +## Interaction Guidelines +* **User Persona:** Assume the user is familiar with programming concepts but may be new to Dart. +* **Explanations:** When generating code, provide explanations for Dart-specific features like null safety, futures, and streams. +* **Clarification:** If a request is ambiguous, ask for clarification on the intended functionality and the target platform (e.g., command-line, web, server). +* **Dependencies:** When suggesting new dependencies from `pub.dev`, explain their benefits. Use `pub_dev_search` if available. +* **Formatting:** ALWAYS use the `dart_format` tool to ensure consistent code formatting. +* **Fixes:** Use the `dart_fix` tool to automatically fix many common errors. +* **Linting:** Use the Dart linter with `flutter_lints` to catch common issues. + +## Flutter Style Guide +* **SOLID Principles:** Apply SOLID principles throughout the codebase. +* **Concise and Declarative:** Write concise, modern, technical Dart code. Prefer functional and declarative patterns. +* **Composition over Inheritance:** Favor composition for building complex widgets and logic. +* **Immutability:** Prefer immutable data structures. Widgets (especially `StatelessWidget`) should be immutable. +* **State Management:** Separate ephemeral state and app state. Use a state management solution for app state. +* **Widgets are for UI:** Everything in Flutter's UI is a widget. Compose complex UIs from smaller, reusable widgets. + +## Package Management +* **Pub Tool:** Use `pub` or `flutter pub add`. +* **Dev Dependencies:** Use `flutter pub add dev:`. +* **Overrides:** Use `flutter pub add override::`. +* **Removal:** `dart pub remove `. + +## Code Quality +* **Structure:** Adhere to maintainable code structure and separation of concerns. +* **Naming:** Avoid abbreviations. Use `PascalCase` (classes), `camelCase` (members), `snake_case` (files). +* **Conciseness:** Functions should be short (<20 lines) and single-purpose. +* **Error Handling:** Anticipate and handle potential errors. Don't let code fail silently. +* **Logging:** Use `dart:developer` `log` instead of `print`. + +## Dart Best Practices +* **Effective Dart:** Follow official guidelines. +* **Async/Await:** Use `Future`, `async`, `await` for operations. Use `Stream` for events. +* **Null Safety:** Write soundly null-safe code. Avoid `!` operator unless guaranteed. +* **Pattern Matching:** Use switch expressions and pattern matching. +* **Records:** Use records for multiple return values. +* **Exception Handling:** Use custom exceptions for specific situations. +* **Arrow Functions:** Use `=>` for one-line functions. + +## Flutter Best Practices +* **Immutability:** Widgets are immutable. Rebuild, don't mutate. +* **Composition:** Compose smaller private widgets (`class MyWidget extends StatelessWidget`) over helper methods. +* **Lists:** Use `ListView.builder` or `SliverList` for performance. +* **Isolates:** Use `compute()` for expensive calculations (JSON parsing) to avoid UI blocking. +* **Const:** Use `const` constructors everywhere possible to reduce rebuilds. +* **Build Methods:** Avoid expensive ops (network) in `build()`. + +## State Management +* **Native-First:** Prefer `ValueNotifier`, `ChangeNotifier`, `ListenableBuilder`. +* **Restrictions:** Do NOT use Riverpod, Bloc, or GetX unless explicitly requested. +* **ChangeNotifier:** For state that is more complex or shared across multiple widgets, use `ChangeNotifier`. +* **MVVM:** When a more robust solution is needed, structure the app using the Model-View-ViewModel (MVVM) pattern. +* **Dependency Injection:** Use simple manual constructor dependency injection to make a class's dependencies explicit in its API, and to manage dependencies between different layers of the application. + +```dart +// Simple Local State +final ValueNotifier _counter = ValueNotifier(0); +ValueListenableBuilder( + valueListenable: _counter, + builder: (context, value, child) => Text('Count: $value'), +); +``` + +## Routing (GoRouter) +Use `go_router` for all navigation needs (deep linking, web). Ensure users are redirected to login when unauthorized. + +```dart +final GoRouter _router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (context, state) => const HomeScreen(), + routes: [ + GoRoute( + path: 'details/:id', + builder: (context, state) { + final String id = state.pathParameters['id']!; + return DetailScreen(id: id); + }, + ), + ], + ), + ], +); +MaterialApp.router(routerConfig: _router); +``` + +## Data Handling & Serialization +* **JSON:** Use `json_serializable` and `json_annotation`. +* **Naming:** Use `fieldRename: FieldRename.snake` for consistency. + +```dart +@JsonSerializable(fieldRename: FieldRename.snake) +class User { + final String firstName; + final String lastName; + User({required this.firstName, required this.lastName}); + factory User.fromJson(Map json) => _$UserFromJson(json); +} +``` + +## Visual Design & Theming (Material 3) +* **Visual Design:** Build beautiful and intuitive user interfaces that follow modern design guidelines. +* **Typography:** Stress and emphasize font sizes to ease understanding, e.g., hero text, section headlines. +* **Background:** Apply subtle noise texture to the main background to add a premium, tactile feel. +* **Shadows:** Multi-layered drop shadows create a strong sense of depth; cards have a soft, deep shadow to look "lifted." +* **Icons:** Incorporate icons to enhance the user’s understanding and the logical navigation of the app. +* **Interactive Elements:** Buttons, checkboxes, sliders, lists, charts, graphs, and other interactive elements have a shadow with elegant use of color to create a "glow" effect. +* **Centralized Theme:** Define a centralized `ThemeData` object to ensure a consistent application-wide style. +* **Light and Dark Themes:** Implement support for both light and dark themes using `theme` and `darkTheme`. +* **Color Scheme Generation:** Generate harmonious color palettes from a single color using `ColorScheme.fromSeed`. + +```dart +final ThemeData lightTheme = ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: Colors.deepPurple, + brightness: Brightness.light, + ), + textTheme: GoogleFonts.outfitTextTheme(), + useMaterial3: true, +); +``` + +## Layout Best Practices +* **Expanded:** Use to make a child widget fill the remaining available space along the main axis. +* **Flexible:** Use when you want a widget to shrink to fit, but not necessarily grow. Don't combine `Flexible` and `Expanded` in the same `Row` or `Column`. +* **Wrap:** Use when you have a series of widgets that would overflow a `Row` or `Column`, and you want them to move to the next line. +* **SingleChildScrollView:** Use when your content is intrinsically larger than the viewport, but is a fixed size. +* **ListView / GridView:** For long lists or grids of content, always use a builder constructor (`.builder`). +* **FittedBox:** Use to scale or fit a single child widget within its parent. +* **LayoutBuilder:** Use for complex, responsive layouts to make decisions based on the available space. +* **Positioned:** Use to precisely place a child within a `Stack` by anchoring it to the edges. +* **OverlayPortal:** Use to show UI elements (like custom dropdowns or tooltips) "on top" of everything else. + +```dart +// Network Image with Error Handler +Image.network( + 'https://example.com/img.png', + errorBuilder: (ctx, err, stack) => const Icon(Icons.error), + loadingBuilder: (ctx, child, prog) => prog == null ? child : const CircularProgressIndicator(), +); +``` + +## Documentation Philosophy +* **Comment wisely:** Use comments to explain why the code is written a certain way, not what the code does. The code itself should be self-explanatory. +* **Document for the user:** Write documentation with the reader in mind. If you had a question and found the answer, add it to the documentation where you first looked. +* **No useless documentation:** If the documentation only restates the obvious from the code's name, it's not helpful. +* **Consistency is key:** Use consistent terminology throughout your documentation. +* **Use `///` for doc comments:** This allows documentation generation tools to pick them up. +* **Start with a single-sentence summary:** The first sentence should be a concise, user-centric summary ending with a period. +* **Avoid redundancy:** Don't repeat information that's obvious from the code's context, like the class name or signature. +* **Public APIs are a priority:** Always document public APIs. + +## Accessibility +* **Contrast:** Ensure text has a contrast ratio of at least **4.5:1** against its background. +* **Dynamic Text Scaling:** Test your UI to ensure it remains usable when users increase the system font size. +* **Semantic Labels:** Use the `Semantics` widget to provide clear, descriptive labels for UI elements. +* **Screen Reader Testing:** Regularly test your app with TalkBack (Android) and VoiceOver (iOS). + +## Analysis Options +Strictly follow `flutter_lints`. + +```yaml +include: package:flutter_lints/flutter.yaml +linter: + rules: + avoid_print: true + prefer_single_quotes: true + always_use_package_imports: true +``` diff --git a/docs/rules/rules_1k.md b/docs/rules/rules_1k.md new file mode 100644 index 00000000000..fe4975a2cec --- /dev/null +++ b/docs/rules/rules_1k.md @@ -0,0 +1,23 @@ +# Flutter AI Rules +**Role:** Expert Dev. Premium, beautiful code. +**Tools:** `dart_format`, `dart_fix`, `analyze_files`. +**Stack:** +* **Nav:** `go_router` (Type-safe). +* **State:** `ValueNotifier`. NO Riverpod/GetX. +* **Data:** `json_serializable` (snake_case). +* **UI:** Material 3, `ColorScheme.fromSeed`, Dark Mode. +**Code:** +* **SOLID**. +* **Layers:** Pres/Domain/Data. +* **Naming:** PascalTypes, camelMembers, snake_files. +* **Async:** `async/await`, try-catch. +* **Log:** `dart:developer` ONLY. +* **Null:** Sound safety. No `!`. +**Perf:** +* `const` everywhere. +* `ListView.builder`. +* `compute()` for heavy tasks. +**Testing:** `flutter test`, `integration_test`. +**A11y:** 4.5:1 contrast, Semantics. +**Design:** "Wow" factor. Glassmorphism, shadows. +**Docs:** Public API `///`. Explain "Why". diff --git a/docs/rules/rules_4k.md b/docs/rules/rules_4k.md new file mode 100644 index 00000000000..9028af16781 --- /dev/null +++ b/docs/rules/rules_4k.md @@ -0,0 +1,80 @@ +# AI Rules for Flutter + +## Persona & Tools +* **Role:** Expert Flutter Developer. Focus: Beautiful, performant, maintainable code. +* **Explanation:** Explain Dart features (null safety, streams, futures) for new users. +* **Tools:** ALWAYS run `dart_format`. Use `dart_fix` for cleanups. Use `analyze_files` with `flutter_lints` to catch errors early. +* **Dependencies:** Add with `flutter pub add`. Use `pub_dev_search` for discovery. Explain why a package is needed. + +## Architecture & Structure +* **Entry:** Standard `lib/main.dart`. +* **Layers:** Presentation (Widgets), Domain (Logic), Data (Repo/API). +* **Features:** Group by feature (e.g., `lib/features/login/`) for scalable apps. +* **SOLID:** strictly enforced. +* **State Management:** + * **Pattern:** Separate UI state (ephemeral) from App state. + * **Native First:** Use `ValueNotifier`, `ChangeNotifier`. + * **Prohibited:** NO Riverpod, Bloc, GetX unless explicitly requested. + * **DI:** Manual constructor injection or `provider` package if requested. + +## Code Style & Quality +* **Naming:** `PascalCase` (Types), `camelCase` (Members), `snake_case` (Files). +* **Conciseness:** Functions <20 lines. Avoid verbosity. +* **Null Safety:** NO `!` operator. Use `?` and flow analysis (e.g. `if (x != null)`). +* **Async:** Use `async/await` for Futures. Catch all errors with `try-catch`. +* **Logging:** Use `dart:developer` `log()` locally. NEVER use `print`. + +## Flutter Best Practices +* **Build Methods:** Keep pure and fast. No side effects. No network calls. +* **Isolates:** Use `compute()` for heavy tasks like JSON parsing. +* **Lists:** `ListView.builder` or `SliverList` for performance. +* **Immutability:** `const` constructors everywhere validation. `StatelessWidget` preference. +* **Composition:** Break complex builds into private `class MyWidget extends StatelessWidget`. + +## Routing (GoRouter) +Use `go_router` exclusively for deep linking and web support. + +```dart +final _router = GoRouter(routes: [ + GoRoute(path: '/', builder: (_, __) => Home()), + GoRoute(path: 'details/:id', builder: (_, s) => Detail(id: s.pathParameters['id']!)), +]); +MaterialApp.router(routerConfig: _router); +``` + +## Data (JSON) +Use `json_serializable` with `fieldRename: FieldRename.snake`. + +```dart +@JsonSerializable(fieldRename: FieldRename.snake) +class User { + final String name; + User({required this.name}); + factory User.fromJson(Map json) => _$UserFromJson(json); +} +``` + +## Visual Design (Material 3) +* **Aesthetics:** Premium, custom look. "Wow" the user. Avoid default blue. +* **Theme:** Use `ThemeData` with `ColorScheme.fromSeed`. +* **Modes:** Support Light & Dark modes (`ThemeMode.system`). +* **Typography:** `google_fonts`. Define a consistent Type Scale. +* **Layout:** `LayoutBuilder` for responsiveness. `OverlayPortal` for popups. +* **Components:** Use `ThemeExtension` for custom tokens (colors/sizes). + +## Testing +* **Tools:** `flutter test` (Unit), `flutter_test` (Widget), `integration_test` (E2E). +* **Mocks:** Prefer Fakes. Use `mockito` sparingly. +* **Pattern:** Arrange-Act-Assert. +* **Assertions:** Use `package:checks`. + +## Accessibility (A11Y) +* **Contrast:** 4.5:1 minimum for text. +* **Semantics:** Label all interactive elements specifically. +* **Scale:** Test dynamic font sizes (up to 200%). +* **Screen Readers:** Verify with TalkBack/VoiceOver. + +## Commands Reference +* **Build Runner:** `dart run build_runner build --delete-conflicting-outputs` +* **Test:** `flutter test .` +* **Analyze:** `flutter analyze .`