rails-ai-context 4.6.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +46 -0
  3. data/CLAUDE.md +23 -22
  4. data/CONTRIBUTING.md +2 -2
  5. data/README.md +62 -36
  6. data/SECURITY.md +1 -1
  7. data/docs/GUIDE.md +23 -48
  8. data/exe/rails-ai-context +15 -2
  9. data/lib/generators/rails_ai_context/install/install_generator.rb +13 -3
  10. data/lib/rails_ai_context/configuration.rb +13 -6
  11. data/lib/rails_ai_context/introspector.rb +0 -2
  12. data/lib/rails_ai_context/introspectors/view_template_introspector.rb +2 -652
  13. data/lib/rails_ai_context/legacy_cleanup.rb +60 -0
  14. data/lib/rails_ai_context/serializers/claude_rules_serializer.rb +1 -91
  15. data/lib/rails_ai_context/serializers/claude_serializer.rb +0 -2
  16. data/lib/rails_ai_context/serializers/compact_serializer_helper.rb +3 -27
  17. data/lib/rails_ai_context/serializers/copilot_instructions_serializer.rb +3 -45
  18. data/lib/rails_ai_context/serializers/copilot_serializer.rb +0 -4
  19. data/lib/rails_ai_context/serializers/cursor_rules_serializer.rb +4 -61
  20. data/lib/rails_ai_context/serializers/opencode_rules_serializer.rb +2 -9
  21. data/lib/rails_ai_context/serializers/opencode_serializer.rb +0 -2
  22. data/lib/rails_ai_context/serializers/stack_overview_helper.rb +26 -6
  23. data/lib/rails_ai_context/serializers/tool_guide_helper.rb +92 -108
  24. data/lib/rails_ai_context/server.rb +0 -1
  25. data/lib/rails_ai_context/tasks/rails_ai_context.rake +8 -0
  26. data/lib/rails_ai_context/tools/analyze_feature.rb +0 -20
  27. data/lib/rails_ai_context/tools/base_tool.rb +54 -0
  28. data/lib/rails_ai_context/tools/dependency_graph.rb +1 -2
  29. data/lib/rails_ai_context/tools/generate_test.rb +1 -2
  30. data/lib/rails_ai_context/tools/get_callbacks.rb +3 -35
  31. data/lib/rails_ai_context/tools/get_component_catalog.rb +1 -2
  32. data/lib/rails_ai_context/tools/get_concern.rb +4 -31
  33. data/lib/rails_ai_context/tools/get_context.rb +2 -5
  34. data/lib/rails_ai_context/tools/get_model_details.rb +1 -2
  35. data/lib/rails_ai_context/tools/get_view.rb +2 -2
  36. data/lib/rails_ai_context/version.rb +1 -1
  37. data/lib/rails_ai_context/watcher.rb +7 -0
  38. data/server.json +3 -3
  39. metadata +10 -12
  40. data/lib/rails_ai_context/introspectors/accessibility_introspector.rb +0 -236
  41. data/lib/rails_ai_context/introspectors/design_token_introspector.rb +0 -365
  42. data/lib/rails_ai_context/serializers/design_system_helper.rb +0 -288
  43. data/lib/rails_ai_context/tools/get_design_system.rb +0 -544
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7a6993d2929f87b6f9c29dffd5f16124a1d3ccb15ac3f8ba8f100364bf0feb06
4
- data.tar.gz: '08c5fe8f51d126c1f7cc52ca9cc8ca0dc2edf5d1dba5f569b8ec5afaeecbb0b4'
3
+ metadata.gz: 2fa1c4d8e9c153c1ad06c0be6824b5421638259b441f4fabc6318e2709315d4e
4
+ data.tar.gz: ecf8ae7d7cb2da0a649146940da643da4cc7c0d3b7ee955a22a0ab1964791ccf
5
5
  SHA512:
6
- metadata.gz: 94ec45e9fd089ba075c1b1c2457bfbf6fc9f2fc9c6da31b2ccafc7e51e64ca9579a390e25b56816a0c1bf4023f3ecbf092124082d53681029dcea3a5446065f5
7
- data.tar.gz: fbab834f047ab3ae3392501964b6e0de1c090af063872473df3e3b074a161536c306cf4afd51daf8e44df8f127ddbb94fd885b15f21610f0884e27159ae118e3
6
+ metadata.gz: 606d359a389873a99e361927e24a26c965491a16286ec22183e514dd6f89fcc14e2fdb1fe838b9fdde72b6cd0e6bb602196de45299afc226d5894c3ac7fdc286
7
+ data.tar.gz: 66101ebb71fd0f15229ccf480b0b280e4d01793bedbd70e2e8158ef9869799a2b29214257a1e51a37ec11da8d23f325e1b43436ab900aa0841e9f5c561996d88
data/CHANGELOG.md CHANGED
@@ -5,6 +5,52 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [5.0.0] — 2026-04-05
9
+
10
+ ### Removed (BREAKING)
11
+
12
+ This release removes the Design & Styling surface and the Accessibility rule surface. When AI assistants consumed pre-digested design/styling context (color palettes, Tailwind class strings, canonical HTML/ERB snippets), they produced poor UI/UX output by blindly copying class strings instead of understanding visual hierarchy. The accessibility surface was asymmetric (Claude-only static rule file, no live MCP tool) and provided generic best-practice rules that didn't earn their keep.
13
+
14
+ **Design system:**
15
+ - **Removed `rails_get_design_system` MCP tool** — tool count is now **38** (was 39). Tool class `RailsAiContext::Tools::GetDesignSystem` deleted.
16
+ - **Removed `:design_tokens` introspector** — class `RailsAiContext::Introspectors::DesignTokensIntrospector` deleted.
17
+ - **Removed `ui_patterns`, `canonical_examples`, `shared_partials` keys** from `ViewTemplateIntrospector` output. The introspector now returns only `templates` and `partials`.
18
+ - **Removed `DesignSystemHelper` serializer module** — module `RailsAiContext::Serializers::DesignSystemHelper` deleted. Consumers no longer receive UI Patterns sections in rule files or compact output.
19
+ - **Removed `"design"` option** from the `include:` parameter of `rails_get_context`. Valid options are now: `schema`, `models`, `routes`, `gems`, `conventions`.
20
+
21
+ **Accessibility:**
22
+ - **Removed `:accessibility` introspector** — class `RailsAiContext::Introspectors::AccessibilityIntrospector` deleted. `ctx[:accessibility]` no longer populated.
23
+ - **Removed `discover_accessibility` cross-cut** from `rails_analyze_feature`. The tool no longer emits a `## Accessibility` section with per-feature a11y findings.
24
+ - **Removed Accessibility line** from root-file Stack Overview (no more "Accessibility: Good/OK/Needs work" label).
25
+
26
+ **Preset counts:** `:full` is now **31** (was 33); `:standard` is now **17** (was 19). Both lost `:design_tokens` and `:accessibility`.
27
+
28
+ **Legacy rule files no longer generated:**
29
+ - `.claude/rules/rails-ui-patterns.md`
30
+ - `.cursor/rules/rails-ui-patterns.mdc`
31
+ - `.github/instructions/rails-ui-patterns.instructions.md`
32
+ - `.claude/rules/rails-accessibility.md`
33
+
34
+ ### Migration notes
35
+
36
+ - **Legacy files are NOT auto-deleted.** On first run after upgrade (via `rake ai:context`, `rails-ai-context context`, install generator, or watcher), the gem detects stale `rails-ui-patterns.*` and `rails-accessibility.md` files and prompts interactively in TTY sessions, or warns (non-destructive) in non-TTY sessions. Answer `y` to remove, or delete the files manually.
37
+ - **If you depended on `rails_get_design_system`**, replace with `rails_get_component_catalog` (component-based) or read view files directly with `rails_read_file` / `rails_search_code`.
38
+ - **If you depended on `include: "design"`** in `rails_get_context`, remove that option.
39
+ - **If you depended on `ctx[:accessibility]`** (custom tools / serializers), that key is gone. Use standard a11y linters (axe-core, lighthouse) in your test suite instead.
40
+ - **The "Build or modify a view" workflow** in tool guides now starts with `rails_get_component_catalog` instead of `rails_get_design_system`.
41
+
42
+ ### Why
43
+
44
+ AI assistants that consume pre-digested summaries produce worse output than AI that reads actual source files. For design systems, class-string copying defeats the mental model required for cohesive visual hierarchy. For accessibility, generic rules ("add alt text") are universal knowledge that AI already has — the static counts didn't add actionable context, and the asymmetric distribution (Claude-only rule file, no live tool) was incoherent with the gem's charter. The gem's charter is ground truth for Rails structure (schema, associations, routes, controllers) — design-system and accessibility summaries were adjacent to that charter and actively counterproductive or inert.
45
+
46
+ ## [4.7.0] — 2026-04-05
47
+
48
+ ### Added
49
+ - **Anti-Hallucination Protocol** — 6-rule verification section embedded in every generated context file (CLAUDE.md, AGENTS.md, .claude/rules/, .cursor/rules/, .github/instructions/, copilot-instructions.md). Targets specific AI failure modes: statistical priors overriding observed facts, pattern completion beating verification, inheritance blindness, empty-output-as-permission, stale-context-lies. Rules force AI to verify column/association/route/method/gem names before writing, mark assumptions with `[ASSUMPTION]` prefix, check inheritance chains, and re-query after writes. Enabled by default via new `config.anti_hallucination_rules` option (boolean, default: `true`). Set `false` to skip.
50
+
51
+ ### Changed
52
+ - **Repositioning: ground truth, not token savings** — the gem's mission is now explicit about what it actually does: stop AI from guessing your Rails app. Token savings are a side-effect, not the product. Updated README headline, "What stops being wrong" section (replaces "Measured token savings"), gemspec summary/description, server.json MCP registry description, docs/GUIDE.md intro, and the tools guide embedded in every generated CLAUDE.md/AGENTS.md/.cursor/rules. The core pitch: AI queries your running app for real schema, real associations, real filters — and writes correct code on the first try instead of iterating through corrections.
53
+
8
54
  ## [4.6.0] — 2026-04-04
9
55
 
10
56
  ### Added
data/CLAUDE.md CHANGED
@@ -8,10 +8,11 @@ structure to AI assistants via the Model Context Protocol (MCP).
8
8
  - `lib/rails_ai_context.rb` — Main entry point, public API (Zeitwerk autoloaded)
9
9
  - `lib/rails_ai_context/configuration.rb` — User-facing config with presets (:standard, :full)
10
10
  - `lib/rails_ai_context/introspector.rb` — Orchestrates sub-introspectors
11
- - `lib/rails_ai_context/introspectors/` — 33 introspectors (schema, models, routes, jobs, gems, conventions, stimulus, database_stats, controllers, views, view_templates, design_tokens, turbo, i18n, config, active_storage, action_text, auth, api, tests, rake_tasks, assets, devops, action_mailbox, migrations, seeds, middleware, engines, multi_database, components, accessibility, performance, frontend_frameworks)
12
- - `lib/rails_ai_context/tools/` — 39 MCP tools using the official mcp SDK
11
+ - `lib/rails_ai_context/introspectors/` — 31 introspectors (schema, models, routes, jobs, gems, conventions, stimulus, database_stats, controllers, views, view_templates, turbo, i18n, config, active_storage, action_text, auth, api, tests, rake_tasks, assets, devops, action_mailbox, migrations, seeds, middleware, engines, multi_database, components, performance, frontend_frameworks)
12
+ - `lib/rails_ai_context/tools/` — 38 MCP tools using the official mcp SDK
13
13
  - `lib/rails_ai_context/cli/` — CLI tool runner (`tool_runner.rb`) — executes MCP tools from rake/Thor
14
- - `lib/rails_ai_context/serializers/` — Output formatters (claude, claude_rules, opencode, opencode_rules, cursor_rules, copilot, copilot_instructions, markdown, JSON, context_file_serializer, compact_serializer_helper, test_command_detection, tool_guide_helper, design_system_helper, stack_overview_helper)
14
+ - `lib/rails_ai_context/serializers/` — Output formatters (claude, claude_rules, opencode, opencode_rules, cursor_rules, copilot, copilot_instructions, markdown, JSON, context_file_serializer, compact_serializer_helper, test_command_detection, tool_guide_helper, stack_overview_helper)
15
+ - `lib/rails_ai_context/legacy_cleanup.rb` — prompts cleanup of legacy `rails-ui-patterns.*` files (v5.0.0 migration)
15
16
  - `lib/rails_ai_context/resources.rb` — MCP resources (static data AI clients read directly)
16
17
  - `lib/rails_ai_context/server.rb` — MCP server configuration (stdio + HTTP transports)
17
18
  - `lib/rails_ai_context/middleware.rb` — Rack middleware for auto-mounting MCP HTTP endpoint
@@ -35,39 +36,39 @@ structure to AI assistants via the Model Context Protocol (MCP).
35
36
  7. **Diff-aware** — context regeneration skips unchanged files
36
37
  8. **Per-assistant serializers** — each AI tool gets tailored output format
37
38
  9. **Zeitwerk autoloading** — files loaded on-demand, not all upfront
38
- 10. **Introspector presets** — `:full` (33) default, `:standard` (19) for lightweight usage
39
+ 10. **Introspector presets** — `:full` (31) default, `:standard` (17) for lightweight usage
39
40
  11. **MCP auto-discovery** — `.mcp.json` generated by install generator
40
41
  12. **Compact by default** — context files ≤150 lines, MCP tools use `detail` parameter (summary/standard/full)
41
42
  13. **Per-tool split rules** — `.claude/rules/`, `.cursor/rules/`, `.github/instructions/`
42
43
  14. **Section markers** — root file content wrapped in `<!-- BEGIN/END rails-ai-context -->` to preserve user content
43
44
  15. **generate_root_files toggle** — when false, skip root files (CLAUDE.md, etc.), only generate split rules
44
- 16. **custom_tools API** — `config.custom_tools` array lets users register additional MCP::Tool subclasses alongside the 39 built-in tools
45
- 17. **Design system extraction** — view templates analyzed for canonical examples, color palette, typography, responsive patterns, interactive states, dark mode
45
+ 16. **custom_tools API** — `config.custom_tools` array lets users register additional MCP::Tool subclasses alongside the 38 built-in tools
46
+ 17. **Legacy cleanup prompting** — v5.0.0 removed `rails_get_design_system` tool + `:design_tokens` introspector + UI pattern rule files. `LegacyCleanup.prompt_legacy_files` detects stale `rails-ui-patterns.*` files at entry points (rake, CLI, watcher, install generator) and prompts (TTY) or warns (non-TTY)
46
47
  18. **skip_tools API** — `config.skip_tools` array lets users exclude specific built-in tools (e.g. `%w[rails_security_scan]`)
47
48
  19. **Security scanning** — optional Brakeman integration via `rails_security_scan` tool (graceful degradation if not installed)
48
49
  20. **tool_mode config** — `:mcp` (default, MCP primary + CLI fallback) or `:cli` (CLI only, no MCP server needed). Selected during install.
49
- 21. **CLI tool access** — all 39 MCP tools callable from terminal: `rails ai:tool[schema]`, `rails-ai-context tool schema`. Tool name resolution: `schema` → `get_schema` → `rails_get_schema`.
50
+ 21. **CLI tool access** — all 38 MCP tools callable from terminal: `rails ai:tool[schema]`, `rails-ai-context tool schema`. Tool name resolution: `schema` → `get_schema` → `rails_get_schema`.
50
51
  22. **Shared ToolGuideHelper** — serializers use a shared module for tool reference sections, rendering MCP or CLI syntax based on `tool_mode`
51
52
  23. **Component catalog** — ViewComponent/Phlex introspection: props, slots, previews, sidecar assets, usage examples via `rails_get_component_catalog`
52
- 24. **Accessibility scanning** — ARIA attributes, semantic HTML, screen reader text, alt text, landmark roles, accessibility score via AccessibilityIntrospector
53
- 25. **Performance analysis** — N+1 query risks, missing counter_cache, missing FK indexes, eager load candidates via `rails_performance_check`
54
- 26. **Migration advisor** — migration code generation with duplicate/nonexistent column warnings, reversibility flags, table name normalization via `rails_migration_advisor`
55
- 27. **Frontend framework detection** — auto-detects React/Vue/Svelte/Angular from package.json, Vite/Shakapacker/Webpacker config, TypeScript setup, monorepo layout, package manager via `rails_get_frontend_stack`
56
- 28. **Install generator idempotency** — re-install preserves existing config, only adds new sections, updates ai_tools/tool_mode selections, prompts per-tool file cleanup for removed tools
57
- 29. **Docs search** — bundled topic index with weighted keyword search, on-demand GitHub fetch
58
- 30. **Safe SQL queries** — defense-in-depth: regex pre-filter + SET TRANSACTION READ ONLY + timeout
59
- 31. **Log reading** — reverse file tail with level filtering and sensitive data redaction
60
- 32. **Config validation** — `http_port`, `cache_ttl`, `max_tool_response_chars`, `query_row_limit` validated on assignment with clear error messages
61
- 33. **Sensitive column redaction** — query tool redacts columns by name AND by suffix pattern (password, secret, token, key, digest, hash) to prevent alias bypass
62
- 34. **Standalone mode** — `gem install rails-ai-context && rails-ai-context init` works without Gemfile entry. CLI pre-loads gem before Rails boot, restores `$LOAD_PATH` entries stripped by `Bundler.setup`. Config from `.rails-ai-context.yml`.
63
- 35. **YAML config** — `.rails-ai-context.yml` as alternative to initializer. Supports all config options except `custom_tools` (Ruby classes) and `excluded_concerns` (regex). Precedence: initializer > YAML > defaults.
64
- 36. **Config auto-loading** — `Configuration.auto_load!` checks `configured_via_block?` flag. If initializer ran, YAML is skipped. Corrupted YAML degrades gracefully with a warning.
65
- 37. **Three install paths** — In-Gemfile (`rails generate rails_ai_context:install`), Standalone (`rails-ai-context init`), Zero config (just run `rails-ai-context serve` with defaults). Users can switch between paths freely; `.mcp.json` command is updated on re-init/re-install.
53
+ 24. **Performance analysis** — N+1 query risks, missing counter_cache, missing FK indexes, eager load candidates via `rails_performance_check`
54
+ 25. **Migration advisor** — migration code generation with duplicate/nonexistent column warnings, reversibility flags, table name normalization via `rails_migration_advisor`
55
+ 26. **Frontend framework detection** — auto-detects React/Vue/Svelte/Angular from package.json, Vite/Shakapacker/Webpacker config, TypeScript setup, monorepo layout, package manager via `rails_get_frontend_stack`
56
+ 27. **Install generator idempotency** — re-install preserves existing config, only adds new sections, updates ai_tools/tool_mode selections, prompts per-tool file cleanup for removed tools
57
+ 28. **Docs search** — bundled topic index with weighted keyword search, on-demand GitHub fetch
58
+ 29. **Safe SQL queries** — defense-in-depth: regex pre-filter + SET TRANSACTION READ ONLY + timeout
59
+ 30. **Log reading** — reverse file tail with level filtering and sensitive data redaction
60
+ 31. **Config validation** — `http_port`, `cache_ttl`, `max_tool_response_chars`, `query_row_limit` validated on assignment with clear error messages
61
+ 32. **Sensitive column redaction** — query tool redacts columns by name AND by suffix pattern (password, secret, token, key, digest, hash) to prevent alias bypass
62
+ 33. **Standalone mode** — `gem install rails-ai-context && rails-ai-context init` works without Gemfile entry. CLI pre-loads gem before Rails boot, restores `$LOAD_PATH` entries stripped by `Bundler.setup`. Config from `.rails-ai-context.yml`.
63
+ 34. **YAML config** — `.rails-ai-context.yml` as alternative to initializer. Supports all config options except `custom_tools` (Ruby classes) and `excluded_concerns` (regex). Precedence: initializer > YAML > defaults.
64
+ 35. **Config auto-loading** — `Configuration.auto_load!` checks `configured_via_block?` flag. If initializer ran, YAML is skipped. Corrupted YAML degrades gracefully with a warning.
65
+ 36. **Three install paths** — In-Gemfile (`rails generate rails_ai_context:install`), Standalone (`rails-ai-context init`), Zero config (just run `rails-ai-context serve` with defaults). Users can switch between paths freely; `.mcp.json` command is updated on re-init/re-install.
66
+ 37. **Anti-Hallucination Protocol** — 6-rule verification section embedded in every generated context file (CLAUDE.md, AGENTS.md, .claude/rules/, .cursor/rules/, .github/instructions/). Targets AI failure modes: statistical priors overriding facts, pattern completion beating verification, stale context. Toggleable via `config.anti_hallucination_rules` (default: true). Rendered by `tools_anti_hallucination_section` in `tool_guide_helper.rb`, placed between intro and detail_guidance in both full and compact render methods.
66
67
 
67
68
  ## Testing
68
69
 
69
70
  ```bash
70
- bundle exec rspec # Run specs (1621 examples)
71
+ bundle exec rspec # Run specs (1563 examples)
71
72
  bundle exec rubocop # Lint
72
73
  ```
73
74
 
data/CONTRIBUTING.md CHANGED
@@ -19,8 +19,8 @@ The test suite uses [Combustion](https://github.com/pat/combustion) to boot a mi
19
19
  ```
20
20
  lib/rails_ai_context/
21
21
  ├── cli/ # CLI tool runner (tool_runner.rb) — executes MCP tools from rake/Thor
22
- ├── introspectors/ # 33 introspectors (schema, models, routes, etc.)
23
- ├── tools/ # 39 MCP tools with detail levels and pagination
22
+ ├── introspectors/ # 31 introspectors (schema, models, routes, etc.)
23
+ ├── tools/ # 38 MCP tools with detail levels and pagination
24
24
  ├── serializers/ # Per-assistant formatters + shared ToolGuideHelper
25
25
  ├── server.rb # MCP server setup (stdio + HTTP)
26
26
  ├── live_reload.rb # MCP live reload (file watcher + cache invalidation)
data/README.md CHANGED
@@ -35,12 +35,12 @@ You've seen it. Your AI:
35
35
  - **Uses the wrong association name** — `user.posts` when it's `user.articles`
36
36
  - **Generates tests that don't match your patterns** — factories when you use fixtures, or the reverse
37
37
  - **Adds a gem you already have** — or calls an API from one you don't
38
- - **Reads 2,000 lines of schema.rb** to answer a question about one table
39
38
  - **Misses `before_action` filters from parent controllers** — then wonders why auth fails
39
+ - **Invents a method** that isn't in your codebase — then you spend 10 minutes finding out
40
40
 
41
41
  You catch it. You fix it. You re-prompt. It breaks something else.
42
42
 
43
- **That loop is the actual cost of AI coding — not the tokens, the corrections.**
43
+ **The real cost of AI coding isn't the tokens it's the correction loop.** Every guess is a round-trip: you catch it, you fix it, you re-prompt, and something adjacent breaks. This gem kills the guessing at its source.
44
44
 
45
45
  <br>
46
46
 
@@ -66,7 +66,7 @@ rails-ai-context serve # start MCP server
66
66
 
67
67
  </div>
68
68
 
69
- Now your AI doesn't guess — it **asks your app directly.** 39 tools that query your schema, models, routes, controllers, views, and conventions on demand. It gets the right answer the first time.
69
+ Now your AI doesn't guess — it **asks your app directly.** 38 tools that query your schema, models, routes, controllers, views, and conventions on demand. It gets the right answer the first time.
70
70
 
71
71
  <br>
72
72
 
@@ -82,37 +82,41 @@ One call returns: definition + source code + every caller grouped by type + test
82
82
 
83
83
  <br>
84
84
 
85
- ## Measured token savings
85
+ ## What stops being wrong
86
86
 
87
- Real numbers from a production Rails app:
87
+ Real scenarios where AI goes sideways — and what it does instead with ground truth:
88
88
 
89
- | Task | Without | With | Saved |
90
- |:-----|--------:|-----:|------:|
91
- | Get one table's columns | 1,492 tokens | 335 tokens | **77%** |
92
- | Trace a method across codebase | 10,556 tokens | 256 tokens | **97%** |
93
- | Understand a model | 1,754 tokens | 588 tokens | **66%** |
94
- | Map Stimulus controllers | 9,886 tokens | 620 tokens | **94%** |
95
- | Routes for one controller | 373 tokens | 121 tokens | **68%** |
89
+ | You ask AI to... | Without — AI guesses | With AI verifies first |
90
+ |:-----|:-----|:-----|
91
+ | Add a `subscription_tier` column to users | Writes the migration, duplicates an existing column | Reads live schema, spots `subscription_status` already exists, asks before migrating |
92
+ | Call `user.posts` in a controller | Uses the guess; runtime `NoMethodError` | Resolves the actual association (`user.articles`) from the model |
93
+ | Write tests for a new model | Scaffolds with FactoryBot | Detects your fixture-based suite and matches it |
94
+ | Fix a failing create action | Misses inherited `before_action :authenticate_user!` | Returns parent-controller filters inline with the action source |
95
+ | Build a dashboard page | Invents Tailwind classes from memory | Returns your actual button/card/alert patterns, copy-paste ready |
96
+ | Trace where `can_cook?` is used | Reads 6 files sequentially, still misses callers | Single call: definition + source + every caller + tests |
96
97
 
97
98
  <details>
98
- <summary><strong>How to reproduce these numbers yourself</strong></summary>
99
+ <summary><strong>Verify it on your own app</strong></summary>
99
100
 
100
101
  <br>
101
102
 
103
+ Run these before and after installing to see what changes in *your* codebase:
104
+
102
105
  ```bash
103
- # Schema: full file vs one table
104
- wc -c db/schema.rb
105
- rails 'ai:tool[schema]' table=users | wc -c
106
+ # Schema: does AI know what columns exist?
107
+ rails 'ai:tool[schema]' table=users
106
108
 
107
- # Trace: all files AI reads vs one call
108
- rails 'ai:tool[search_code]' pattern=your_method match_type=trace | wc -c
109
+ # Trace: find every caller of a method across the codebase
110
+ rails 'ai:tool[search_code]' pattern=your_method match_type=trace
109
111
 
110
- # Model: raw file + schema vs structured output
111
- wc -c app/models/user.rb db/schema.rb
112
- rails 'ai:tool[model_details]' model=User | wc -c
112
+ # Model: associations, scopes, callbacks, concerns all resolved
113
+ rails 'ai:tool[model_details]' model=User
114
+
115
+ # Controllers: action source + inherited filters + strong params in one shot
116
+ rails 'ai:tool[controllers]' controller=UsersController action=create
113
117
  ```
114
118
 
115
- Divide bytes by 4 for rough token count. Bigger apps save more tool output stays focused while raw files grow.
119
+ Compare what AI outputs with and without these tools wired in. The difference is measured in *corrections avoided*, not bytes saved.
116
120
 
117
121
  </details>
118
122
 
@@ -143,7 +147,7 @@ rails ai:serve
143
147
 
144
148
  ### CLI
145
149
 
146
- Same 39 tools, no server needed. Works in any terminal, any AI tool.
150
+ Same 38 tools, no server needed. Works in any terminal, any AI tool.
147
151
 
148
152
  ```bash
149
153
  rails 'ai:tool[search_code]' pattern="can_cook?" match_type=trace
@@ -211,14 +215,14 @@ rails 'ai:tool[validate]' files=app/controllers/cooks_controller.rb level=rails
211
215
  <br>
212
216
 
213
217
  ```bash
214
- # Get the design system
215
- rails 'ai:tool[design_system]' detail=standard
216
- # → your actual button classes, card patterns, color palette — copy-paste ready
217
-
218
218
  # Check existing view patterns
219
219
  rails 'ai:tool[view]' controller=dashboard
220
220
  # → templates with ivars, Turbo frames, Stimulus controllers, partial locals
221
221
 
222
+ # See existing components + usage examples
223
+ rails 'ai:tool[component_catalog]' detail=standard
224
+ # → ViewComponent/Phlex props, slots, previews, sidecar assets
225
+
222
226
  # Get Stimulus data-attributes
223
227
  rails 'ai:tool[stimulus]' controller=chart
224
228
  # → correct HTML with dashes (not underscores) + reverse view lookup
@@ -228,9 +232,9 @@ rails 'ai:tool[stimulus]' controller=chart
228
232
 
229
233
  <br>
230
234
 
231
- ## 39 Tools
235
+ ## 38 Tools
232
236
 
233
- Every tool is **read-only** and returns structured, token-efficient context.
237
+ Every tool is **read-only** and returns data verified against your actual app — not guesses, not training data.
234
238
 
235
239
  <details>
236
240
  <summary><strong>Search & Trace</strong></summary>
@@ -282,7 +286,6 @@ Every tool is **read-only** and returns structured, token-efficient context.
282
286
  |:-----|:------------|
283
287
  | `get_view` | Templates with ivars, Turbo wiring, Stimulus refs, partial locals |
284
288
  | `get_stimulus` | HTML data-attributes (dashes!) + targets + values + actions |
285
- | `get_design_system` | Copy-paste HTML/ERB patterns for your actual components |
286
289
  | `get_partial_interface` | What locals to pass + what methods are called on them |
287
290
  | `get_turbo_map` | Broadcast → subscription wiring + mismatch warnings |
288
291
  | `get_frontend_stack` | React/Vue/Svelte/Angular, Hotwire, TypeScript, package manager |
@@ -339,6 +342,28 @@ Every tool is **read-only** and returns structured, token-efficient context.
339
342
 
340
343
  <br>
341
344
 
345
+ ## Anti-Hallucination Protocol
346
+
347
+ Every generated context file ships with **6 rules that force AI verification** before writing code. The protocol targets the exact cognitive failures that produce confident-wrong code: statistical priors overriding observed facts, pattern completion beating verification, stale context lies.
348
+
349
+ <details>
350
+ <summary><strong>The 6 rules (shown to AI in every CLAUDE.md / .cursor/rules / .github/instructions)</strong></summary>
351
+
352
+ <br>
353
+
354
+ 1. **Verify before you write.** Never reference a column, association, route, helper, method, class, partial, or gem not verified in THIS project via a tool call in THIS turn. Never invent names that "sound right."
355
+ 2. **Mark every assumption.** If proceeding without verification, prefix with `[ASSUMPTION]`. Silent assumptions forbidden. "I'd need to check X first" is a preferred answer.
356
+ 3. **Training data describes average Rails. This app isn't average.** When something feels "obviously" standard Rails, query anyway. Check `rails_get_conventions` + `rails_get_gems` BEFORE scaffolding.
357
+ 4. **Check the inheritance chain before every edit.** Inherited `before_action` filters, concerns, includes, STI parents. Inheritance is never flat.
358
+ 5. **Empty tool output is information, not permission.** "0 callers found" signals investigation, not license to proceed on guesses.
359
+ 6. **Stale context lies. Re-query after writes.** Earlier tool output may be wrong after edits.
360
+
361
+ Enabled by default. Disable with `config.anti_hallucination_rules = false` if you prefer your own rules.
362
+
363
+ </details>
364
+
365
+ <br>
366
+
342
367
  ## How it works
343
368
 
344
369
  ```
@@ -346,7 +371,7 @@ Every tool is **read-only** and returns structured, token-efficient context.
346
371
  │ Your Rails App │
347
372
  │ models + schema + routes + controllers + views + jobs │
348
373
  └────────────────────────┬────────────────────────────────┘
349
- │ introspects (33 introspectors)
374
+ │ introspects (31 introspectors)
350
375
 
351
376
  ┌─────────────────────────────────────────────────────────┐
352
377
  │ rails-ai-context │
@@ -356,7 +381,7 @@ Every tool is **read-only** and returns structured, token-efficient context.
356
381
  ▼ ▼ ▼
357
382
  ┌──────────────────┐ ┌────────────┐ ┌────────────────────┐
358
383
  │ Static Files │ │ MCP Server │ │ CLI Tools │
359
- │ CLAUDE.md │ │ 39 tools │ │ Same 39 tools │
384
+ │ CLAUDE.md │ │ 38 tools │ │ Same 38 tools │
360
385
  │ .cursor/rules/ │ │ stdio/HTTP │ │ No server needed │
361
386
  │ .github/instr... │ │ .mcp.json │ │ rails 'ai:tool[X]' │
362
387
  └──────────────────┘ └────────────┘ └────────────────────┘
@@ -390,7 +415,7 @@ Both paths ask which AI tools you use and whether you want MCP or CLI mode. `.mc
390
415
  | In-Gemfile | Standalone | What it does |
391
416
  |:-----------|:-----------|:------------|
392
417
  | `rails ai:context` | `rails-ai-context context` | Generate context files |
393
- | `rails 'ai:tool[NAME]'` | `rails-ai-context tool NAME` | Run any of the 39 tools |
418
+ | `rails 'ai:tool[NAME]'` | `rails-ai-context tool NAME` | Run any of the 38 tools |
394
419
  | `rails ai:tool` | `rails-ai-context tool --list` | List all available tools |
395
420
  | `rails ai:serve` | `rails-ai-context serve` | Start MCP server (stdio) |
396
421
  | `rails ai:doctor` | `rails-ai-context doctor` | Diagnostics + AI readiness score |
@@ -405,7 +430,7 @@ Both paths ask which AI tools you use and whether you want MCP or CLI mode. `.mc
405
430
  RailsAiContext.configure do |config|
406
431
  config.ai_tools = %i[claude cursor] # Which AI tools to generate for
407
432
  config.tool_mode = :mcp # :mcp (default) or :cli
408
- config.preset = :full # :full (33 introspectors) or :standard (19)
433
+ config.preset = :full # :full (31 introspectors) or :standard (17)
409
434
  end
410
435
  ```
411
436
 
@@ -416,9 +441,10 @@ end
416
441
 
417
442
  | Option | Default | Description |
418
443
  |:-------|:--------|:------------|
419
- | `preset` | `:full` | `:full` (33 introspectors) or `:standard` (19) |
444
+ | `preset` | `:full` | `:full` (31 introspectors) or `:standard` (17) |
420
445
  | `context_mode` | `:compact` | `:compact` (150 lines) or `:full` |
421
446
  | `generate_root_files` | `true` | Set `false` for split rules only |
447
+ | `anti_hallucination_rules` | `true` | Embed 6-rule verification protocol in generated context files |
422
448
  | `cache_ttl` | `60` | Cache TTL in seconds |
423
449
  | `max_tool_response_chars` | `200_000` | Safety cap for tool responses |
424
450
  | `live_reload` | `:auto` | `:auto`, `true`, or `false` |
@@ -444,7 +470,7 @@ end
444
470
  ## About
445
471
 
446
472
  Built by a Rails developer with 10+ years of production experience.<br>
447
- 1621 tests. 39 tools. 33 introspectors. Standalone or in-Gemfile.<br>
473
+ 1563 tests. 38 tools. 31 introspectors. Standalone or in-Gemfile.<br>
448
474
  MIT licensed. [Contributions welcome.](CONTRIBUTING.md)
449
475
 
450
476
  <br>
data/SECURITY.md CHANGED
@@ -30,7 +30,7 @@ If you discover a security vulnerability in rails-ai-context, please report it r
30
30
 
31
31
  ## Security Design
32
32
 
33
- - All 39 MCP tools are **read-only** and never modify your application or database.
33
+ - All 38 MCP tools are **read-only** and never modify your application or database.
34
34
  - **Sensitive file blocking** — configurable `sensitive_patterns` blocks access to `.env`, `*.key`, `*.pem`, `credentials.yml.enc` across all search and read tools. Patterns are checked in `rails_search_code`, `rails_get_edit_context`, and all new tools.
35
35
  - **Path traversal protection** — all file-reading tools validate paths with `File.realpath()` against `Rails.root` to prevent directory escape.
36
36
  - **Command injection prevention** — code search uses `Open3.capture2` with array arguments (never shell strings). The `--` flag separator prevents pattern injection.
data/docs/GUIDE.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  > Full documentation for [rails-ai-context](https://github.com/crisnahine/rails-ai-context).
4
4
  > For a quick overview, see the [README](../README.md).
5
+ >
6
+ > **Why this gem exists:** AI coding assistants guess your Rails app. They invent columns,
7
+ > use wrong association names, miss inherited filters, and scaffold tests that don't match
8
+ > your patterns. This gem turns your running app into the source of truth — so agents query
9
+ > real schema, real associations, and real conventions on demand, and write correct code
10
+ > on the first try.
5
11
 
6
12
  ---
7
13
 
@@ -126,7 +132,7 @@ end
126
132
 
127
133
  `rails ai:context` generates **29 files** across all AI assistants:
128
134
 
129
- ### Claude Code (6 files)
135
+ ### Claude Code (5 files)
130
136
 
131
137
  | File | Purpose | Notes |
132
138
  |------|---------|-------|
@@ -134,7 +140,6 @@ end
134
140
  | `.claude/rules/rails-schema.md` | Database table listing | Auto-loaded by Claude Code alongside CLAUDE.md. |
135
141
  | `.claude/rules/rails-models.md` | Model listing with associations | Auto-loaded by Claude Code alongside CLAUDE.md. |
136
142
  | `.claude/rules/rails-context.md` | Project context and conventions | Auto-loaded by Claude Code alongside CLAUDE.md. |
137
- | `.claude/rules/rails-ui-patterns.md` | UI patterns and design tokens | Auto-loaded by Claude Code alongside CLAUDE.md. |
138
143
  | `.claude/rules/rails-mcp-tools.md` | Full MCP tool reference | Parameters, detail levels, pagination, workflow guide. |
139
144
 
140
145
  ### OpenCode (3 files)
@@ -145,17 +150,16 @@ end
145
150
  | `app/models/AGENTS.md` | Model reference | Auto-loaded by OpenCode when reading files in `app/models/`. |
146
151
  | `app/controllers/AGENTS.md` | Controller reference | Auto-loaded by OpenCode when reading files in `app/controllers/`. |
147
152
 
148
- ### Cursor (5 files)
153
+ ### Cursor (4 files)
149
154
 
150
155
  | File | Purpose | Notes |
151
156
  |------|---------|-------|
152
157
  | `.cursor/rules/rails-project.mdc` | Project overview | `alwaysApply: true` — loaded in every conversation. |
153
158
  | `.cursor/rules/rails-models.mdc` | Model reference | `globs: app/models/**/*.rb` — auto-attaches when editing models. |
154
159
  | `.cursor/rules/rails-controllers.mdc` | Controller reference | `globs: app/controllers/**/*.rb` — auto-attaches when editing controllers. |
155
- | `.cursor/rules/rails-ui-patterns.mdc` | UI patterns and design tokens | `globs: app/views/**/*.erb` — loaded when editing views. |
156
160
  | `.cursor/rules/rails-mcp-tools.mdc` | MCP tool reference | `alwaysApply: true` — always available. |
157
161
 
158
- ### GitHub Copilot (6 files)
162
+ ### GitHub Copilot (5 files)
159
163
 
160
164
  | File | Purpose | Notes |
161
165
  |------|---------|-------|
@@ -163,7 +167,6 @@ end
163
167
  | `.github/instructions/rails-models.instructions.md` | Model context | `applyTo: app/models/**/*.rb` — loaded when editing models. |
164
168
  | `.github/instructions/rails-controllers.instructions.md` | Controller context | `applyTo: app/controllers/**/*.rb` — loaded when editing controllers. |
165
169
  | `.github/instructions/rails-context.instructions.md` | Project context and conventions | `applyTo: **/*` — loaded everywhere. |
166
- | `.github/instructions/rails-ui-patterns.instructions.md` | UI patterns and design tokens | `applyTo: app/views/**/*.erb` — loaded when editing views. |
167
170
  | `.github/instructions/rails-mcp-tools.instructions.md` | MCP tool reference | `applyTo: **/*` — loaded everywhere. |
168
171
 
169
172
  ### Generic (1 file)
@@ -255,7 +258,7 @@ rails ai:context:claude # Use this instead (no quoting needed)
255
258
 
256
259
  ## CLI Tools
257
260
 
258
- All 39 MCP tools can be run directly from the terminal — no MCP server or AI client needed.
261
+ All 38 MCP tools can be run directly from the terminal — no MCP server or AI client needed.
259
262
 
260
263
  ### Rake
261
264
 
@@ -319,7 +322,7 @@ The `tool_mode` is selected during `rails generate rails_ai_context:install`.
319
322
 
320
323
  ## MCP Tools — Full Reference
321
324
 
322
- All 39 tools are **read-only** and **idempotent** — they never modify your application or database.
325
+ All 38 tools are **read-only** and **idempotent** — they never modify your application or database.
323
326
 
324
327
  ### rails_get_schema
325
328
 
@@ -701,33 +704,6 @@ rails_analyze_feature(feature: "orders")
701
704
 
702
705
  **Returns:** Markdown with sections for Models (with columns, associations, validations, scopes, enums), Controllers (with actions and filters), Routes, Services (with methods), Jobs (with queue/retry), Views (with partials and Stimulus refs), Stimulus controllers (with targets/values/actions), Tests (with counts), Related models, Concerns, Callbacks, Channels, Mailers, and Environment dependencies. Each section shows match counts.
703
706
 
704
- ### rails_get_design_system
705
-
706
- Returns the app's design system: color palette with semantic roles, component patterns with real HTML examples from actual views, typography scale, layout conventions, responsive breakpoints, and interactive state patterns.
707
-
708
- **Parameters:**
709
-
710
- | Param | Type | Description |
711
- |-------|------|-------------|
712
- | `detail` | string | `summary` (palette + components), `standard` (+ canonical page examples + design rules, default), `full` (+ typography, responsive, dark mode, animations, design tokens) |
713
-
714
- **Examples:**
715
-
716
- ```
717
- rails_get_design_system()
718
- → Color palette (primary, danger, success), component patterns (buttons, cards, inputs),
719
- canonical page examples (form page, list page), design rules
720
-
721
- rails_get_design_system(detail: "summary")
722
- → Compact: color roles + component class strings only
723
-
724
- rails_get_design_system(detail: "full")
725
- → Everything: + typography scale, responsive breakpoints, interactive states,
726
- dark mode patterns, animations, icon system, design tokens, shared partials
727
- ```
728
-
729
- **Returns:** Structured design system reference. Includes real HTML/ERB snippets from the app's actual views as canonical examples, semantic color roles (primary for CTAs, danger for destructive), component variants, typography hierarchy, spacing scale, and explicit design rules for AI to follow.
730
-
731
707
  ### rails_security_scan
732
708
 
733
709
  Runs Brakeman static security analysis on the Rails app. Detects SQL injection, XSS, mass assignment, command injection, and other vulnerabilities. Requires the `brakeman` gem — returns installation instructions if not present.
@@ -1142,7 +1118,7 @@ RailsAiContext.configure do |config|
1142
1118
  end
1143
1119
  ```
1144
1120
 
1145
- Both transports are **read-only** — they expose the same 39 tools and never modify your app.
1121
+ Both transports are **read-only** — they expose the same 38 tools and never modify your app.
1146
1122
 
1147
1123
  ---
1148
1124
 
@@ -1153,7 +1129,7 @@ Both transports are **read-only** — they expose the same 39 tools and never mo
1153
1129
  RailsAiContext.configure do |config|
1154
1130
  # --- Introspectors ---
1155
1131
 
1156
- # Presets: :full (33 introspectors, default) or :standard (19)
1132
+ # Presets: :full (31 introspectors, default) or :standard (17)
1157
1133
  config.preset = :full
1158
1134
 
1159
1135
  # Cherry-pick on top of a preset
@@ -1268,7 +1244,7 @@ end
1268
1244
  | Option | Type | Default | Description |
1269
1245
  |--------|------|---------|-------------|
1270
1246
  | `preset` | Symbol | `:full` | Introspector preset (`:full` or `:standard`) |
1271
- | `introspectors` | Array | 32 (full preset) | Which introspectors to run |
1247
+ | `introspectors` | Array | 31 (full preset) | Which introspectors to run |
1272
1248
  | `context_mode` | Symbol | `:compact` | `:compact` or `:full` |
1273
1249
  | `claude_max_lines` | Integer | `150` | Max lines for CLAUDE.md in compact mode |
1274
1250
  | `max_tool_response_chars` | Integer | `200_000` | Safety cap for MCP tool responses |
@@ -1290,6 +1266,7 @@ end
1290
1266
  | `server_name` | String | `"rails-ai-context"` | MCP server name |
1291
1267
  | `server_version` | String | gem version | MCP server version |
1292
1268
  | `generate_root_files` | Boolean | `true` | Generate root files (CLAUDE.md, etc.) — set `false` for split rules only |
1269
+ | `anti_hallucination_rules` | Boolean | `true` | Embed 6-rule Anti-Hallucination Protocol in generated context files — set `false` to skip |
1293
1270
  | `max_file_size` | Integer | `5_000_000` | Per-file read limit for tools (5MB) |
1294
1271
  | `max_test_file_size` | Integer | `1_000_000` | Test file read limit (1MB) |
1295
1272
  | `max_schema_file_size` | Integer | `10_000_000` | schema.rb / structure.sql parse limit (10MB) |
@@ -1325,7 +1302,7 @@ All split rules include an app overview file, so no context is lost when root fi
1325
1302
 
1326
1303
  ## Introspectors — Full List
1327
1304
 
1328
- ### Standard preset (19 introspectors)
1305
+ ### Standard preset (17 introspectors)
1329
1306
 
1330
1307
  Core Rails structure only. Use `config.preset = :standard` for a lighter footprint.
1331
1308
 
@@ -1342,16 +1319,14 @@ Core Rails structure only. Use `config.preset = :standard` for a lighter footpri
1342
1319
  | `migrations` | Total count, schema version, pending migrations, recent migration history with detected actions (create_table, add_column, etc.), migration statistics. |
1343
1320
  | `config` | Cache store, session store, timezone, queue adapter, mailer settings, middleware stack, initializers, credentials status, CurrentAttributes classes. |
1344
1321
  | `stimulus` | Stimulus controllers with targets, values (with types), actions, outlets, classes. Extracted from JS/TS files. |
1345
- | `view_templates` | View file contents, partial references, Stimulus data attributes, UI pattern extraction, model field usage in partials. |
1346
- | `design_tokens` | Auto-detects CSS framework (Tailwind v3/v4, Bootstrap, Sass, plain CSS) and extracts design tokens from config files and built CSS. |
1322
+ | `view_templates` | View file contents, partial references, Stimulus data attributes, model field usage in partials. |
1347
1323
  | `components` | ViewComponent/Phlex components: props, slots, previews, sidecar assets, usage examples. |
1348
1324
  | `turbo` | Turbo Frames (IDs and files), Turbo Stream templates, model broadcasts (`broadcasts_to`, `broadcasts`). |
1349
1325
  | `auth` | Devise models with modules, Rails 8 built-in auth, has_secure_password, Pundit policies, CanCanCan, CORS config, CSP config. |
1350
- | `accessibility` | ARIA attributes, semantic HTML elements, screen reader text, alt text coverage, landmark roles, accessibility score. |
1351
1326
  | `performance` | N+1 query risks, missing counter_cache, missing FK indexes, Model.all anti-patterns, eager load candidates. |
1352
1327
  | `i18n` | Default locale, available locales, locale files with key counts, backend class, parse errors. |
1353
1328
 
1354
- ### Full preset (33 introspectors) — default
1329
+ ### Full preset (31 introspectors) — default
1355
1330
 
1356
1331
  Includes all standard introspectors plus:
1357
1332
 
@@ -1474,11 +1449,11 @@ OpenCode uses **per-directory lazy-loading**: when the agent reads a file, it wa
1474
1449
 
1475
1450
  | Setup | Coverage | Notes |
1476
1451
  |-------|----------|-------|
1477
- | Rails full-stack (ERB + Hotwire) | 32/32 | All introspectors relevant |
1478
- | Rails + Inertia.js (React/Vue) | ~25/32 | Views/Turbo partially useful, backend fully covered |
1479
- | Rails API + React/Next.js SPA | ~23/32 | Schema, models, routes, API, auth, jobs — all covered |
1480
- | Rails API + mobile app | ~23/32 | Same as SPA — backend introspection is identical |
1481
- | Rails engine (mountable gem) | ~18/32 | Core introspectors (schema, models, routes, gems) work |
1452
+ | Rails full-stack (ERB + Hotwire) | 31/31 | All introspectors relevant |
1453
+ | Rails + Inertia.js (React/Vue) | ~25/31 | Views/Turbo partially useful, backend fully covered |
1454
+ | Rails API + React/Next.js SPA | ~23/31 | Schema, models, routes, API, auth, jobs — all covered |
1455
+ | Rails API + mobile app | ~23/31 | Same as SPA — backend introspection is identical |
1456
+ | Rails engine (mountable gem) | ~18/31 | Core introspectors (schema, models, routes, gems) work |
1482
1457
 
1483
1458
  Frontend introspectors (views, Turbo, Stimulus, assets) degrade gracefully — they report nothing when those features aren't present.
1484
1459