rails-ai-context 5.30.2 → 5.32.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 (222) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +868 -0
  3. data/CONTEXT.md +7 -3
  4. data/README.md +1 -1
  5. data/docs/ARCHITECTURE.md +3 -3
  6. data/docs/CLI.md +1 -1
  7. data/docs/COMPATIBILITY.md +50 -14
  8. data/docs/CONFIGURATION.md +4 -1
  9. data/docs/FAQ.md +1 -1
  10. data/docs/GUIDE.md +14 -8
  11. data/docs/INTROSPECTORS.md +50 -23
  12. data/docs/SECURITY.md +56 -1
  13. data/docs/TOOLS.md +58 -12
  14. data/lib/generators/rails_ai_context/install/install_generator.rb +1 -0
  15. data/lib/rails_ai_context/action_filters.rb +121 -48
  16. data/lib/rails_ai_context/app_commands.rb +2 -2
  17. data/lib/rails_ai_context/app_kind.rb +65 -8
  18. data/lib/rails_ai_context/ast_cache.rb +53 -18
  19. data/lib/rails_ai_context/base_mixins.rb +46 -16
  20. data/lib/rails_ai_context/boot_manager.rb +5 -1
  21. data/lib/rails_ai_context/cli/entry_boot.rb +17 -2
  22. data/lib/rails_ai_context/cli/tool_runner.rb +15 -1
  23. data/lib/rails_ai_context/concern_macros.rb +791 -111
  24. data/lib/rails_ai_context/concern_membership.rb +25 -5
  25. data/lib/rails_ai_context/concern_paths.rb +63 -17
  26. data/lib/rails_ai_context/config_yaml.rb +40 -0
  27. data/lib/rails_ai_context/configuration.rb +3 -3
  28. data/lib/rails_ai_context/data/docs/index.json +324 -0
  29. data/lib/rails_ai_context/database_yml.rb +136 -0
  30. data/lib/rails_ai_context/doctor.rb +30 -37
  31. data/lib/rails_ai_context/erb_source.rb +40 -0
  32. data/lib/rails_ai_context/fingerprinter.rb +48 -22
  33. data/lib/rails_ai_context/fixture_keys.rb +42 -1
  34. data/lib/rails_ai_context/gem_lock.rb +275 -47
  35. data/lib/rails_ai_context/git_ignore.rb +13 -11
  36. data/lib/rails_ai_context/hydrators/hydration_formatter.rb +8 -2
  37. data/lib/rails_ai_context/hydrators/schema_hint_builder.rb +10 -5
  38. data/lib/rails_ai_context/introspector.rb +10 -1
  39. data/lib/rails_ai_context/introspectors/action_mailbox_introspector.rb +27 -19
  40. data/lib/rails_ai_context/introspectors/action_presence.rb +11 -8
  41. data/lib/rails_ai_context/introspectors/action_resolver.rb +38 -26
  42. data/lib/rails_ai_context/introspectors/action_text_introspector.rb +2 -2
  43. data/lib/rails_ai_context/introspectors/active_record_settings.rb +56 -0
  44. data/lib/rails_ai_context/introspectors/active_storage_introspector.rb +1 -1
  45. data/lib/rails_ai_context/introspectors/active_support_introspector.rb +98 -22
  46. data/lib/rails_ai_context/introspectors/admin_resources.rb +101 -0
  47. data/lib/rails_ai_context/introspectors/anyway_configs.rb +64 -0
  48. data/lib/rails_ai_context/introspectors/apartment_config.rb +47 -0
  49. data/lib/rails_ai_context/introspectors/api_introspector.rb +125 -26
  50. data/lib/rails_ai_context/introspectors/asset_pipeline_introspector.rb +24 -19
  51. data/lib/rails_ai_context/introspectors/ast_walk.rb +18 -0
  52. data/lib/rails_ai_context/introspectors/auth_introspector.rb +71 -18
  53. data/lib/rails_ai_context/introspectors/autoload_introspector.rb +62 -15
  54. data/lib/rails_ai_context/introspectors/base.rb +38 -0
  55. data/lib/rails_ai_context/introspectors/call_site_expansion.rb +349 -39
  56. data/lib/rails_ai_context/introspectors/component_introspector.rb +26 -14
  57. data/lib/rails_ai_context/introspectors/config_introspector.rb +22 -9
  58. data/lib/rails_ai_context/introspectors/connection_pool_introspector.rb +1 -4
  59. data/lib/rails_ai_context/introspectors/controller_filters.rb +335 -31
  60. data/lib/rails_ai_context/introspectors/controller_introspector.rb +315 -129
  61. data/lib/rails_ai_context/introspectors/controller_settings.rb +182 -0
  62. data/lib/rails_ai_context/introspectors/convention_introspector.rb +18 -15
  63. data/lib/rails_ai_context/introspectors/database_stats_introspector.rb +1 -1
  64. data/lib/rails_ai_context/introspectors/declared_constant.rb +108 -23
  65. data/lib/rails_ai_context/introspectors/eager_load.rb +12 -7
  66. data/lib/rails_ai_context/introspectors/engine_introspector.rb +13 -5
  67. data/lib/rails_ai_context/introspectors/env_config_introspector.rb +62 -17
  68. data/lib/rails_ai_context/introspectors/env_introspector.rb +8 -6
  69. data/lib/rails_ai_context/introspectors/env_references.rb +21 -4
  70. data/lib/rails_ai_context/introspectors/frontend_framework_introspector.rb +37 -22
  71. data/lib/rails_ai_context/introspectors/gem_introspector.rb +3 -1
  72. data/lib/rails_ai_context/introspectors/gemfile_gems.rb +53 -5
  73. data/lib/rails_ai_context/introspectors/grape_endpoints.rb +109 -0
  74. data/lib/rails_ai_context/introspectors/helper_names.rb +12 -1
  75. data/lib/rails_ai_context/introspectors/i18n_introspector.rb +101 -46
  76. data/lib/rails_ai_context/introspectors/includers.rb +6 -1
  77. data/lib/rails_ai_context/introspectors/initializer_introspector.rb +2 -5
  78. data/lib/rails_ai_context/introspectors/job_introspector.rb +548 -103
  79. data/lib/rails_ai_context/introspectors/listener_registration.rb +11 -1
  80. data/lib/rails_ai_context/introspectors/listeners/associations_listener.rb +51 -4
  81. data/lib/rails_ai_context/introspectors/listeners/autoload_ignore_listener.rb +31 -0
  82. data/lib/rails_ai_context/introspectors/listeners/autoload_paths_listener.rb +4 -47
  83. data/lib/rails_ai_context/introspectors/listeners/base_listener.rb +80 -14
  84. data/lib/rails_ai_context/introspectors/listeners/branch_conditions.rb +156 -0
  85. data/lib/rails_ai_context/introspectors/listeners/callbacks_listener.rb +85 -23
  86. data/lib/rails_ai_context/introspectors/listeners/class_definition_listener.rb +35 -6
  87. data/lib/rails_ai_context/introspectors/listeners/component_structure_listener.rb +30 -2
  88. data/lib/rails_ai_context/introspectors/listeners/conditional_macro_listener.rb +19 -0
  89. data/lib/rails_ai_context/introspectors/listeners/config_assignment_listener.rb +255 -10
  90. data/lib/rails_ai_context/introspectors/listeners/constant_reference_listener.rb +34 -0
  91. data/lib/rails_ai_context/introspectors/listeners/constructor_macro_listener.rb +123 -0
  92. data/lib/rails_ai_context/introspectors/listeners/definition_file_paths_listener.rb +66 -0
  93. data/lib/rails_ai_context/introspectors/listeners/enums_listener.rb +2 -2
  94. data/lib/rails_ai_context/introspectors/listeners/env_access_listener.rb +31 -0
  95. data/lib/rails_ai_context/introspectors/listeners/filter_macro_listener.rb +54 -0
  96. data/lib/rails_ai_context/introspectors/listeners/fixture_paths_listener.rb +62 -0
  97. data/lib/rails_ai_context/introspectors/listeners/gemfile_dsl_listener.rb +42 -1
  98. data/lib/rails_ai_context/introspectors/listeners/generic_macro_listener.rb +28 -2
  99. data/lib/rails_ai_context/introspectors/listeners/grape_api_listener.rb +137 -0
  100. data/lib/rails_ai_context/introspectors/listeners/http_client_call_listener.rb +50 -0
  101. data/lib/rails_ai_context/introspectors/listeners/i18n_load_path_listener.rb +54 -0
  102. data/lib/rails_ai_context/introspectors/listeners/literal_paths.rb +123 -0
  103. data/lib/rails_ai_context/introspectors/listeners/macros_listener.rb +248 -4
  104. data/lib/rails_ai_context/introspectors/listeners/mailbox_routing_listener.rb +2 -1
  105. data/lib/rails_ai_context/introspectors/listeners/method_call_listener.rb +7 -1
  106. data/lib/rails_ai_context/introspectors/listeners/methods_listener.rb +352 -69
  107. data/lib/rails_ai_context/introspectors/listeners/migration_dsl_listener.rb +1 -1
  108. data/lib/rails_ai_context/introspectors/listeners/migration_replay_listener.rb +35 -26
  109. data/lib/rails_ai_context/introspectors/listeners/mixins_listener.rb +62 -29
  110. data/lib/rails_ai_context/introspectors/listeners/mount_listener.rb +8 -0
  111. data/lib/rails_ai_context/introspectors/listeners/namespaced_roots_listener.rb +35 -0
  112. data/lib/rails_ai_context/introspectors/listeners/nested_constants_listener.rb +32 -0
  113. data/lib/rails_ai_context/introspectors/listeners/owner_scope.rb +67 -0
  114. data/lib/rails_ai_context/introspectors/listeners/preview_paths_listener.rb +16 -7
  115. data/lib/rails_ai_context/introspectors/listeners/proc_literal_listener.rb +42 -0
  116. data/lib/rails_ai_context/introspectors/listeners/queue_assignment_listener.rb +54 -0
  117. data/lib/rails_ai_context/introspectors/listeners/rake_task_dsl_listener.rb +21 -8
  118. data/lib/rails_ai_context/introspectors/listeners/route_files_listener.rb +4 -11
  119. data/lib/rails_ai_context/introspectors/listeners/routes_dsl_listener.rb +461 -65
  120. data/lib/rails_ai_context/introspectors/listeners/schema_dsl_listener.rb +76 -14
  121. data/lib/rails_ai_context/introspectors/listeners/scopes_listener.rb +40 -1
  122. data/lib/rails_ai_context/introspectors/listeners/validations_listener.rb +10 -1
  123. data/lib/rails_ai_context/introspectors/listeners/view_paths_listener.rb +37 -0
  124. data/lib/rails_ai_context/introspectors/middleware_introspector.rb +47 -3
  125. data/lib/rails_ai_context/introspectors/migration_introspector.rb +3 -3
  126. data/lib/rails_ai_context/introspectors/migration_replay/helpers.rb +4 -3
  127. data/lib/rails_ai_context/introspectors/migration_replay/statements.rb +72 -12
  128. data/lib/rails_ai_context/introspectors/migration_replay.rb +110 -14
  129. data/lib/rails_ai_context/introspectors/model_introspector.rb +708 -214
  130. data/lib/rails_ai_context/introspectors/module_aliases.rb +11 -3
  131. data/lib/rails_ai_context/introspectors/multi_database_introspector.rb +9 -57
  132. data/lib/rails_ai_context/introspectors/observability_introspector.rb +5 -8
  133. data/lib/rails_ai_context/introspectors/performance_introspector.rb +28 -8
  134. data/lib/rails_ai_context/introspectors/rake_task_introspector.rb +118 -51
  135. data/lib/rails_ai_context/introspectors/recurring_schedules.rb +150 -0
  136. data/lib/rails_ai_context/introspectors/rendered_record.rb +87 -0
  137. data/lib/rails_ai_context/introspectors/retry_policy.rb +8 -5
  138. data/lib/rails_ai_context/introspectors/route_introspector.rb +153 -42
  139. data/lib/rails_ai_context/introspectors/schema_conventions.rb +127 -40
  140. data/lib/rails_ai_context/introspectors/schema_dump_path.rb +80 -0
  141. data/lib/rails_ai_context/introspectors/schema_introspector.rb +346 -112
  142. data/lib/rails_ai_context/introspectors/schema_reader.rb +69 -29
  143. data/lib/rails_ai_context/introspectors/service_classes.rb +21 -15
  144. data/lib/rails_ai_context/introspectors/source_calls.rb +1 -1
  145. data/lib/rails_ai_context/introspectors/source_introspector.rb +17 -2
  146. data/lib/rails_ai_context/introspectors/source_scan.rb +174 -26
  147. data/lib/rails_ai_context/introspectors/sqlite_virtual_tables.rb +28 -0
  148. data/lib/rails_ai_context/introspectors/stimulus_introspector.rb +16 -5
  149. data/lib/rails_ai_context/introspectors/structure_sql_reader.rb +372 -98
  150. data/lib/rails_ai_context/introspectors/superclass_chain.rb +14 -15
  151. data/lib/rails_ai_context/introspectors/table_name.rb +46 -45
  152. data/lib/rails_ai_context/introspectors/test_introspector.rb +289 -78
  153. data/lib/rails_ai_context/introspectors/turbo_introspector.rb +10 -5
  154. data/lib/rails_ai_context/introspectors/view_introspector.rb +5 -40
  155. data/lib/rails_ai_context/introspectors/view_template_introspector.rb +12 -10
  156. data/lib/rails_ai_context/method_name.rb +31 -0
  157. data/lib/rails_ai_context/migration_status.rb +5 -5
  158. data/lib/rails_ai_context/output_guard.rb +6 -4
  159. data/lib/rails_ai_context/package_json.rb +96 -5
  160. data/lib/rails_ai_context/path_resolver.rb +170 -15
  161. data/lib/rails_ai_context/payload.rb +48 -0
  162. data/lib/rails_ai_context/pending_migrations.rb +15 -18
  163. data/lib/rails_ai_context/portable_path.rb +76 -4
  164. data/lib/rails_ai_context/redaction.rb +8 -2
  165. data/lib/rails_ai_context/route_coverage.rb +5 -1
  166. data/lib/rails_ai_context/safe_file.rb +4 -1
  167. data/lib/rails_ai_context/safe_path.rb +61 -10
  168. data/lib/rails_ai_context/schema_hint.rb +8 -2
  169. data/lib/rails_ai_context/schema_version.rb +7 -9
  170. data/lib/rails_ai_context/serializers/claude_rules_serializer.rb +1 -1
  171. data/lib/rails_ai_context/serializers/markdown_serializer.rb +13 -4
  172. data/lib/rails_ai_context/serializers/section_facts.rb +5 -1
  173. data/lib/rails_ai_context/serializers/stack_overview_helper.rb +2 -2
  174. data/lib/rails_ai_context/serializers/tool_guide_helper.rb +7 -4
  175. data/lib/rails_ai_context/server.rb +26 -7
  176. data/lib/rails_ai_context/test_framework.rb +32 -5
  177. data/lib/rails_ai_context/tools/analyze_feature.rb +22 -10
  178. data/lib/rails_ai_context/tools/base_tool.rb +69 -30
  179. data/lib/rails_ai_context/tools/diagnose.rb +1 -1
  180. data/lib/rails_ai_context/tools/generate_test.rb +8 -9
  181. data/lib/rails_ai_context/tools/get_active_support.rb +19 -4
  182. data/lib/rails_ai_context/tools/get_api.rb +17 -11
  183. data/lib/rails_ai_context/tools/get_autoload.rb +10 -5
  184. data/lib/rails_ai_context/tools/get_callbacks.rb +65 -14
  185. data/lib/rails_ai_context/tools/get_component_catalog.rb +7 -4
  186. data/lib/rails_ai_context/tools/get_concern.rb +31 -18
  187. data/lib/rails_ai_context/tools/get_config.rb +52 -18
  188. data/lib/rails_ai_context/tools/get_controllers.rb +57 -13
  189. data/lib/rails_ai_context/tools/get_conventions.rb +44 -22
  190. data/lib/rails_ai_context/tools/get_engines.rb +2 -0
  191. data/lib/rails_ai_context/tools/get_env.rb +209 -52
  192. data/lib/rails_ai_context/tools/get_env_config.rb +38 -7
  193. data/lib/rails_ai_context/tools/get_frontend_stack.rb +56 -7
  194. data/lib/rails_ai_context/tools/get_helper_methods.rb +136 -26
  195. data/lib/rails_ai_context/tools/get_job_pattern.rb +143 -87
  196. data/lib/rails_ai_context/tools/get_mailers.rb +59 -2
  197. data/lib/rails_ai_context/tools/get_model_details.rb +178 -28
  198. data/lib/rails_ai_context/tools/get_partial_interface.rb +101 -62
  199. data/lib/rails_ai_context/tools/get_routes.rb +35 -9
  200. data/lib/rails_ai_context/tools/get_schema.rb +160 -61
  201. data/lib/rails_ai_context/tools/get_service_pattern.rb +121 -25
  202. data/lib/rails_ai_context/tools/get_stimulus.rb +1 -1
  203. data/lib/rails_ai_context/tools/get_test_info.rb +152 -82
  204. data/lib/rails_ai_context/tools/get_view.rb +37 -20
  205. data/lib/rails_ai_context/tools/migration_advisor.rb +64 -24
  206. data/lib/rails_ai_context/tools/onboard.rb +174 -88
  207. data/lib/rails_ai_context/tools/performance_check.rb +5 -13
  208. data/lib/rails_ai_context/tools/query.rb +122 -28
  209. data/lib/rails_ai_context/tools/read_logs.rb +45 -17
  210. data/lib/rails_ai_context/tools/runtime_info.rb +1 -1
  211. data/lib/rails_ai_context/tools/safe_call.rb +20 -15
  212. data/lib/rails_ai_context/tools/search_code.rb +114 -40
  213. data/lib/rails_ai_context/tools/search_docs.rb +22 -11
  214. data/lib/rails_ai_context/tools/security_scan.rb +51 -4
  215. data/lib/rails_ai_context/tools/validate.rb +21 -4
  216. data/lib/rails_ai_context/tools/validate_semantics.rb +18 -6
  217. data/lib/rails_ai_context/version.rb +1 -1
  218. data/lib/rails_ai_context/vfs.rb +2 -2
  219. data/lib/rails_ai_context/view_file.rb +53 -3
  220. data/lib/rails_ai_context.rb +10 -2
  221. data/server.json +1 -1
  222. metadata +34 -3
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "concurrent"
4
+ require "pathname"
5
+
3
6
  module RailsAiContext
4
7
  # Rewrites a path so it means the same thing on another machine. What is
5
8
  # generated here ends up in .ai-context.json, which the app commits: an
@@ -21,6 +24,9 @@ module RailsAiContext
21
24
  return path.delete_prefix(gem_root) if path.start_with?(gem_root)
22
25
  end
23
26
 
27
+ enclosing = enclosing_relative(path, root)
28
+ return enclosing if enclosing
29
+
24
30
  gem_checkouts.each do |dir, name|
25
31
  return File.join(name, path.delete_prefix(dir)) if path.start_with?(dir)
26
32
  end
@@ -68,9 +74,10 @@ module RailsAiContext
68
74
  path = path.to_s
69
75
  root = root.to_s
70
76
  return false if !root.empty? && path.start_with?("#{root}/")
77
+ return true if gem_roots.any? { |gem_root| path.start_with?(gem_root) }
78
+ return false if enclosing_relative(path, root)
71
79
 
72
- gem_roots.any? { |gem_root| path.start_with?(gem_root) } ||
73
- gem_checkouts.any? { |dir, _name| path.start_with?(dir) }
80
+ gem_checkouts.any? { |dir, _name| path.start_with?(dir) }
74
81
  end
75
82
 
76
83
  # The relative form, or nil for a path no portable form names: the
@@ -94,6 +101,44 @@ module RailsAiContext
94
101
  .gsub(%r{(\A|[\s"'`(:\[=,])(?:#{alternation})(?=\z|[\s"'`)\],;:])}, '\1.')
95
102
  end
96
103
 
104
+ # A file of the gem the app sits inside (an engine's test/dummy) is the
105
+ # app's own source: "../../app/models/x.rb". Compared as real paths, since
106
+ # Bundler and the autoloader can spell one directory two ways (/tmp, /private/tmp).
107
+ def enclosing_relative(path, root)
108
+ real_root, gem_dir = enclosing_gem(root)
109
+ return nil unless gem_dir
110
+
111
+ real = real_path(path)
112
+ return nil unless real.start_with?("#{gem_dir}/")
113
+
114
+ Pathname.new(real).relative_path_from(Pathname.new(real_root)).to_s
115
+ end
116
+
117
+ ENCLOSING = Concurrent::Map.new
118
+ private_constant :ENCLOSING
119
+
120
+ # [real root, real dir of the loaded gem holding it, or nil].
121
+ def enclosing_gem(root)
122
+ return nil if root.empty?
123
+
124
+ ENCLOSING.compute_if_absent(root) do
125
+ real_root = real_path(root)
126
+ dir = Gem.loaded_specs.each_value.filter_map { |spec|
127
+ next if spec.default_gem?
128
+
129
+ dir = real_path(spec.full_gem_path.to_s)
130
+ dir if real_root.start_with?("#{dir}/")
131
+ }.max_by(&:length)
132
+ [ real_root, dir ].freeze
133
+ end
134
+ end
135
+
136
+ def real_path(path)
137
+ File.realpath(path)
138
+ rescue SystemCallError
139
+ File.expand_path(path)
140
+ end
141
+
97
142
  def relativize_all(paths, root)
98
143
  Array(paths).map { |path| relativize(path, root) }.uniq
99
144
  end
@@ -105,15 +150,42 @@ module RailsAiContext
105
150
  .map { |dir| File.join(dir, "gems") + File::SEPARATOR }
106
151
  end
107
152
 
153
+ # A file a loaded gem ships. A `path:` gem kept in the repo, or a gem the
154
+ # app sits inside (an engine's dummy app), is the app's own source; a
155
+ # bundle installed under the root (vendor/bundle, .bundle) is still the gems'.
156
+ def gem_file?(path, root)
157
+ path = path.to_s
158
+ root = "#{root.to_s.chomp(File::SEPARATOR)}#{File::SEPARATOR}"
159
+ Gem.loaded_specs.each_value.any? do |spec|
160
+ dir = "#{spec.full_gem_path}#{File::SEPARATOR}"
161
+ path.start_with?(dir) && !app_owned_gem?(spec, dir, root)
162
+ end
163
+ end
164
+
165
+ def app_owned_gem?(spec, dir, root)
166
+ return true if root.start_with?(dir)
167
+ return false unless dir.start_with?(root) && defined?(Bundler::Source::Path)
168
+
169
+ source = spec.respond_to?(:source) ? spec.source : nil
170
+ source.is_a?(Bundler::Source::Path) && !source.is_a?(Bundler::Source::Git)
171
+ end
172
+
108
173
  # A gem the Gemfile takes from path: or git: is never unpacked under a
109
174
  # gem root, so its own checkout is the only prefix that names it. Longest
110
- # first, because one checkout can sit inside another.
175
+ # first, because one checkout can sit inside another. Kept per set of
176
+ # loaded gems: a gem activated later is a checkout too.
111
177
  def gem_checkouts
112
- @gem_checkouts ||= Gem.loaded_specs.each_value.filter_map { |spec|
178
+ specs = Gem.loaded_specs
179
+ key = [ specs.object_id, specs.size ]
180
+ return @gem_checkouts if @gem_checkouts_key == key
181
+
182
+ @gem_checkouts = specs.each_value.filter_map { |spec|
113
183
  dir = spec.full_gem_path.to_s
114
184
  next if dir.empty? || gem_roots.any? { |gem_root| dir.start_with?(gem_root) }
115
185
  [ dir + File::SEPARATOR, spec.full_name ]
116
186
  }.sort_by { |dir, _name| -dir.length }
187
+ @gem_checkouts_key = key
188
+ @gem_checkouts
117
189
  rescue => e
118
190
  RailsAiContext.debug_fail(e, [], label: "PortablePath.gem_checkouts")
119
191
  end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "safe_path"
4
+
3
5
  module RailsAiContext
4
6
  # Every value that leaves the app through this gem - config source slices,
5
7
  # log lines, query rows, environment values - passes through here first.
@@ -12,6 +14,10 @@ module RailsAiContext
12
14
  # apart from a secret, because it says what kind of data was there.
13
15
  EMAIL = "[EMAIL]"
14
16
 
17
+ PLACEHOLDER_NAMES = SafePath::PLACEHOLDER_SUFFIXES.map { |suffix| Regexp.escape(suffix.delete_prefix(".")) }.join("|")
18
+ EXAMPLE_FILE = /\.(?:#{PLACEHOLDER_NAMES})\b/
19
+ YAML_FILE = /\.ya?ml(?:\.(?:erb|#{PLACEHOLDER_NAMES}))*\z/
20
+
15
21
  # Regex by design: these scrub vocabulary out of values already read from
16
22
  # the AST or a log file rather than parsing structure. A credential can
17
23
  # sit in an interpolation, a heredoc or a bare string, and no node type
@@ -173,7 +179,7 @@ module RailsAiContext
173
179
  # Locale files hold translations: only credential formats are filtered.
174
180
  # Example files often hold real values, so only a plain placeholder is kept.
175
181
  locale = path.to_s.match?(%r{(?:\A|/)locales?/})
176
- example = path.to_s.match?(/\.(?:example|sample|template)\b/)
182
+ example = path.to_s.match?(EXAMPLE_FILE)
177
183
  result = line.gsub(URI_USERINFO) { |m| placeholder?(m) ? m : "#{Regexp.last_match(1)}#{FILTERED}@" }
178
184
  unless locale
179
185
  result = result.gsub(KEYED_LITERAL) do |m|
@@ -193,7 +199,7 @@ module RailsAiContext
193
199
  end
194
200
  result = result.gsub(STRING_LITERAL) { |lit| credential?(lit[1..-2]) ? "#{lit[0]}#{FILTERED}#{lit[0]}" : lit }
195
201
  result = CREDENTIAL_TOKENS.reduce(result) { |text, pattern| text.gsub(pattern, FILTERED) }
196
- path.to_s.match?(/\.ya?ml(?:\.(?:erb|example|sample|template))*\z/) && !locale ? yaml_scalar(result, example) : result
202
+ path.to_s.match?(YAML_FILE) && !locale ? yaml_scalar(result, example) : result
197
203
  end
198
204
 
199
205
  # Consecutive lines, so a PEM key across them is filtered whole; the line
@@ -81,13 +81,16 @@ module RailsAiContext
81
81
  merged
82
82
  end
83
83
 
84
+ # What a table read from source leaves out; `routes` words it as a note instead of a clause.
85
+ GEM_DRAWN = "routes Rails' engines and gems draw at boot"
86
+
84
87
  # A suffix rather than a predicate, so no call site needs a conditional of
85
88
  # its own - that shape is what let nine of them forget.
86
89
  #
87
90
  # @param routes [Hash] the :routes section of an introspection context
88
91
  # @return [String] a leading-comma clause naming what the count leaves out,
89
92
  # or "" when the count is the whole table
90
- def suffix(routes)
93
+ def suffix(routes, gem_drawn: true)
91
94
  return "" unless Tools::SectionFetch.usable?(routes)
92
95
 
93
96
  parts = []
@@ -99,6 +102,7 @@ module RailsAiContext
99
102
  parts << "#{CountPhrase.call(unread, 'in-repo engine route file')} not read" if unread.positive?
100
103
  in_engines = Array(routes[:engine_routes]).sum { |group| Array(group[:routes]).size }
101
104
  parts << "#{in_engines} more in engine tables" if in_engines.positive?
105
+ parts << "#{GEM_DRAWN} not read without booting" if gem_drawn && routes[:confidence] == Confidence::STATIC
102
106
  return "" if parts.empty?
103
107
 
104
108
  ", #{parts.join(', ')}"
@@ -16,8 +16,11 @@ module RailsAiContext
16
16
  dir = File.dirname(path)
17
17
  FileUtils.mkdir_p(dir)
18
18
  tmp = File.join(dir, ".#{File.basename(path)}.#{SecureRandom.hex(4)}.tmp")
19
- File.write(tmp, content)
19
+ File.binwrite(tmp, content)
20
20
  File.rename(tmp, path)
21
+ rescue StandardError
22
+ FileUtils.rm_f(tmp) if tmp
23
+ raise
21
24
  end
22
25
 
23
26
  def self.read(path, max_size: nil)
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "pathname"
4
+ require_relative "polyfill/data"
5
+
3
6
  module RailsAiContext
4
7
  # One answer to "may this caller-supplied path be read, and which file is
5
8
  # it". The checks run in an order that matters: a sensitive name is refused
@@ -18,17 +21,23 @@ module RailsAiContext
18
21
 
19
22
  # relative: the caller's path, relative to `under`. root: the directory
20
23
  # the sensitive patterns are matched against (the app root for most tools).
21
- def locate(relative, under:, root: under, max_size: nil)
24
+ # listed: the path came from a listing of `under`, so it is spelled as on disk.
25
+ def locate(relative, under:, root: under, max_size: nil, listed: false)
22
26
  relative = relative.to_s
23
27
  return refuse(:traversal) if traversal?(relative)
24
28
  return refuse(:sensitive) if sensitive?(relative)
25
29
 
26
- real = File.realpath(File.join(under.to_s, relative))
27
- real_under = File.realpath(under.to_s)
30
+ path = File.join(under.to_s, relative)
31
+ real = listed ? real_file(path) : File.realpath(path)
32
+ real_under = real_base(under)
28
33
  return refuse(:outside) unless contained?(real, real_under)
29
34
 
30
- real_root = File.realpath(root.to_s)
31
- root_relative = real == real_root ? "" : real.delete_prefix(real_root + File::SEPARATOR)
35
+ real_root = real_base(root)
36
+ root_relative = if real == real_root then ""
37
+ elsif contained?(real, real_root) then real.delete_prefix(dir_prefix(real_root))
38
+ # A directory the caller trusts outside the root, such as the engine around a test/dummy.
39
+ else Pathname.new(real).relative_path_from(Pathname.new(real_root)).to_s
40
+ end
32
41
  return refuse(:sensitive) if sensitive?(root_relative)
33
42
  return refuse(:missing) unless File.file?(real)
34
43
 
@@ -40,6 +49,20 @@ module RailsAiContext
40
49
  refuse(:missing)
41
50
  end
42
51
 
52
+ # A directory resolves to the same path for every lookup in a run.
53
+ def real_base(dir)
54
+ RunCache.fetch([ :safe_path_base, dir.to_s ]) { File.realpath(dir.to_s) }
55
+ end
56
+
57
+ # A file that is not a link is its directory's real path plus its name, so a
58
+ # scan of hundreds of files in one directory resolves the directory once. A
59
+ # typed path keeps realpath, which also corrects its case on macOS.
60
+ def real_file(path)
61
+ return File.realpath(path) unless File.lstat(path).file?
62
+
63
+ File.join(real_base(File.dirname(path)), File.basename(path))
64
+ end
65
+
43
66
  def read(relative, under:, root: under, max_size: nil)
44
67
  resolution = locate(relative, under: under, root: root, max_size: max_size)
45
68
  return [ nil, resolution ] unless resolution.ok?
@@ -55,17 +78,45 @@ module RailsAiContext
55
78
  relative.include?("..") || relative.start_with?("/") || relative.include?("\0")
56
79
  end
57
80
 
81
+ PLACEHOLDER_SUFFIXES = %w[.example .sample .template .dist].freeze
82
+
83
+ # A placeholder (.env.example) is committed to be read, so a basename glob
84
+ # does not block it; a path pattern (`.ssh/*`) or its exact name does.
58
85
  def sensitive?(relative)
59
- patterns = RailsAiContext.configuration.sensitive_patterns
60
- basename = File.basename(relative.to_s)
86
+ path = relative.to_s
87
+ basename = File.basename(path)
61
88
  flags = File::FNM_DOTMATCH | File::FNM_CASEFOLD
62
- patterns.any? do |pattern|
63
- File.fnmatch(pattern, relative.to_s, flags) || File.fnmatch(pattern, basename, flags)
89
+ matching = RailsAiContext.configuration.sensitive_patterns.select do |pattern|
90
+ File.fnmatch(pattern, path, flags) || File.fnmatch(pattern, basename, flags)
91
+ end
92
+ return false if matching.empty?
93
+ return true unless PLACEHOLDER_SUFFIXES.any? { |suffix| basename.downcase.end_with?(suffix) }
94
+
95
+ # Without FNM_EXTGLOB a brace is literal, so only these make a pattern a glob.
96
+ matching.any? do |pattern|
97
+ pattern.include?("/") || (!pattern.match?(/[*?\[\\]/) && (pattern.casecmp?(path) || pattern.casecmp?(basename)))
64
98
  end
65
99
  end
66
100
 
67
101
  def contained?(real, real_dir)
68
- real == real_dir || real.start_with?(real_dir + File::SEPARATOR)
102
+ real == real_dir || real.start_with?(dir_prefix(real_dir))
103
+ end
104
+
105
+ # The nearest directory at or above `dir` that holds `.git` (a directory, or a
106
+ # file in a worktree or submodule), or nil outside any repository.
107
+ def git_root(dir)
108
+ until File.exist?(File.join(dir, ".git"))
109
+ parent = File.dirname(dir)
110
+ return nil if parent == dir
111
+
112
+ dir = parent
113
+ end
114
+ dir
115
+ end
116
+
117
+ # The filesystem root already ends in the separator, so it is its own prefix.
118
+ def dir_prefix(dir)
119
+ dir.end_with?(File::SEPARATOR) ? dir : dir + File::SEPARATOR
69
120
  end
70
121
 
71
122
  # A too-large file was found, so its resolution keeps the path for the
@@ -11,6 +11,12 @@ module RailsAiContext
11
11
  :associations, # [{name: "comments", type: "has_many", class_name: "Comment"}, ...]
12
12
  :validations, # [{kind: "presence", attributes: ["title"]}, ...]
13
13
  :primary_key, # "id"
14
- :confidence # "[VERIFIED]", "[STATIC]" or "[INFERRED]"
15
- )
14
+ :confidence, # "[VERIFIED]", "[STATIC]" or "[INFERRED]"
15
+ :collection, # true for a Mongoid document: table_name is its collection
16
+ :embedded_in # the parent a Mongoid embedded document is stored inside, nil otherwise
17
+ ) do
18
+ def initialize(collection: false, embedded_in: nil, **members)
19
+ super
20
+ end
21
+ end
16
22
  end
@@ -13,16 +13,14 @@ module RailsAiContext
13
13
  # (mysqldump quotes the table name with backticks, pg_dump with double
14
14
  # quotes; the version literals themselves are always single-quoted).
15
15
  module SchemaVersion
16
+ # From the dump the app configures, then the default files.
16
17
  def self.current(root)
17
- schema_path = File.join(root, "db", "schema.rb")
18
- if File.exist?(schema_path)
19
- version = from_schema_rb(schema_path)
18
+ Introspectors::SchemaDumpPath.candidates(root).each do |format, path|
19
+ next unless File.exist?(path)
20
+
21
+ version = format == :ruby ? from_schema_rb(path) : from_structure_sql(path)
20
22
  return version if version
21
23
  end
22
-
23
- structure_path = File.join(root, "db", "structure.sql")
24
- return from_structure_sql(structure_path) if File.exist?(structure_path)
25
-
26
24
  nil
27
25
  end
28
26
 
@@ -50,8 +48,8 @@ module RailsAiContext
50
48
  # The whole applied set, which only structure.sql records; schema.rb
51
49
  # carries the max version alone, so `current` is the answer there.
52
50
  def self.applied(root)
53
- path = File.join(root.to_s, "db", "structure.sql")
54
- return nil unless File.exist?(path)
51
+ format, path = Introspectors::SchemaDumpPath.present(root)
52
+ return nil unless format == :sql
55
53
 
56
54
  content = RailsAiContext::SafeFile.read(path, max_size: RailsAiContext.configuration.max_schema_file_size)
57
55
  return nil unless content
@@ -94,7 +94,7 @@ module RailsAiContext
94
94
 
95
95
  col_sample = key_cols.map do |c|
96
96
  col_type = c[:array] ? "#{c[:type]}[]" : c[:type].to_s
97
- entry = "#{c[:name]}:#{col_type}"
97
+ entry = c[:type] ? "#{c[:name]}:#{col_type}" : c[:name].to_s
98
98
  if c.key?(:default) && !c[:default].nil?
99
99
  default_display = c[:default] == "" ? '""' : c[:default]
100
100
  entry += "(=#{default_display})"
@@ -62,9 +62,9 @@ module RailsAiContext
62
62
  def schema_section
63
63
  schema = Payload.section(context, :schema)
64
64
 
65
- lines = [ "## Database Schema (#{count_phrase(schema[:total_tables], "table")})" ]
65
+ lines = [ "## Database Schema (#{Introspectors::SchemaConventions.relations_phrase(schema[:tables])})" ]
66
66
  schema[:tables]&.each do |name, data|
67
- cols = (data[:columns] || []).map { |c| "`#{c[:name]}` (#{c[:type]})" }.join(", ")
67
+ cols = (data[:columns] || []).map { |c| c[:type] ? "`#{c[:name]}` (#{c[:type]})" : "`#{c[:name]}`" }.join(", ")
68
68
  lines << "### #{escape_markdown(name)}"
69
69
  lines << cols
70
70
  end
@@ -291,11 +291,17 @@ module RailsAiContext
291
291
  authn[:devise].each { |d| lines << "- `#{d[:model]}`: #{d[:matches].join(', ')}" }
292
292
  end
293
293
  lines << "- Rails 8 built-in auth detected" if authn[:rails_auth]
294
+ lines << "- Rodauth: #{Array(authn.dig(:rodauth, :classes)).join(', ').presence || 'rodauth-rails'}" if authn[:rodauth]
294
295
  lines << "- has_secure_password: #{authn[:has_secure_password].join(', ')}" if authn[:has_secure_password]
296
+ Introspectors::AuthIntrospector.digest_sentences(authn).each { |sentence| lines << "- #{sentence}" }
295
297
  if authz[:pundit]
296
298
  lines << "### Pundit Policies"
297
299
  authz[:pundit].each { |p| lines << "- `#{p}`" }
298
300
  end
301
+ if authz[:action_policy]
302
+ lines << "### Action Policy Policies"
303
+ authz[:action_policy].each { |p| lines << "- `#{p}`" }
304
+ end
299
305
  if authz[:policies]
300
306
  lines << "### Policy Classes (app/policies)"
301
307
  authz[:policies].each { |p| lines << "- `#{p}`" }
@@ -315,6 +321,7 @@ module RailsAiContext
315
321
  end
316
322
  if data[:serializers]&.any?
317
323
  lines << "- Jbuilder templates: #{data[:serializers][:jbuilder]}" if data[:serializers][:jbuilder]
324
+ lines << "- RABL templates: #{data[:serializers][:rabl]}" if data[:serializers][:rabl]
318
325
  if data[:serializers][:serializer_classes]&.any?
319
326
  lines << "- Serializers: #{data[:serializers][:serializer_classes].join(', ')}"
320
327
  end
@@ -331,7 +338,8 @@ module RailsAiContext
331
338
 
332
339
  lines = [ "## Testing" ]
333
340
  lines << "- Framework: #{data[:framework]}"
334
- lines << "- Factories: #{data[:factories][:location]} (#{count_phrase(data[:factories][:count], "file")})" if data[:factories]
341
+ lines << "- Factories: #{TestFramework.factory_location(data[:factories])}" if data[:factories]
342
+ lines << "- Fabricators: #{data[:fabricators][:location]} (#{count_phrase(data[:fabricators][:count], "file")})" if data[:fabricators]
335
343
  lines << "- Fixtures: #{data[:fixtures][:location]} (#{TestFramework.fixture_phrase(data[:fixtures])})" if data[:fixtures]
336
344
  lines << "- System tests: #{data[:system_tests][:location]}" if data[:system_tests]
337
345
  lines << "- CI: #{data[:ci_config].join(', ')}" if data[:ci_config]&.any?
@@ -478,6 +486,7 @@ module RailsAiContext
478
486
  data[:mounted_engines].each do |e|
479
487
  desc = e[:description] ? " - #{e[:description]}" : ""
480
488
  at = e[:path] ? " at `#{e[:path]}`" : ""
489
+ at += " (`#{e[:condition]}`)" if e[:condition]
481
490
  lines << "- `#{e[:engine]}`#{at}#{desc}"
482
491
  end
483
492
  else
@@ -511,7 +520,7 @@ module RailsAiContext
511
520
  if data[:model_connections]&.any?
512
521
  lines << "### Model Connections"
513
522
  data[:model_connections].each do |c|
514
- lines << "- `#{c[:model]}` → #{c[:connects_to] || 'custom connection'}"
523
+ lines << "- `#{c[:model]}` → #{c[:connects_to] || 'custom connection'}#{" (only #{c[:condition]})" if c[:condition]}"
515
524
  end
516
525
  end
517
526
 
@@ -47,7 +47,9 @@ module RailsAiContext
47
47
  parts = []
48
48
  parts << "Devise" if auth.dig(:authentication, :devise)&.any?
49
49
  parts << "Rails 8 auth" if auth.dig(:authentication, :rails_auth)
50
+ parts << "Rodauth" if auth.dig(:authentication, :rodauth)
50
51
  parts << "Pundit" if auth.dig(:authorization, :pundit)&.any?
52
+ parts << "Action Policy" if auth.dig(:authorization, :action_policy)&.any?
51
53
  parts << "CanCanCan" if auth.dig(:authorization, :cancancan)
52
54
  # No gem behind it, so it is named as a directory, not a framework.
53
55
  parts << "policies in app/policies" if auth.dig(:authorization, :policies)&.any?
@@ -159,7 +161,7 @@ module RailsAiContext
159
161
 
160
162
  def chain_filter_parts(ctx, name, root)
161
163
  chain = ActionFilters.for_controller(ctx, name, root: root)
162
- (chain[:inherited] + chain[:own]).map { |f| "#{f[:kind]} #{f[:name]}#{filter_condition_tail(f)}" } +
164
+ chain[:chain].map { |f| "#{f[:kind]} #{f[:name]}#{filter_condition_tail(f)}" } +
163
165
  chain[:skipped].map { |skipped| "~~#{skipped}~~ _(skipped)_" }
164
166
  end
165
167
 
@@ -182,6 +184,7 @@ module RailsAiContext
182
184
  own = +""
183
185
  own << " (if: #{option_text(filter[:if])})" if filter[:if]
184
186
  own << " (unless: #{option_text(filter[:unless])})" if filter[:unless]
187
+ own << " (`#{filter[:condition]}`)" if filter[:condition]
185
188
  own + skip_condition_tail(filter)
186
189
  end
187
190
 
@@ -189,6 +192,7 @@ module RailsAiContext
189
192
  tail = +""
190
193
  tail << " (skipped if: #{option_text(filter[:skipped_if])})" if filter[:skipped_if]
191
194
  tail << " (skipped unless: #{option_text(filter[:skipped_unless])})" if filter[:skipped_unless]
195
+ tail << " (skipped `#{filter[:skipped_condition]}`)" if filter[:skipped_condition]
192
196
  tail << " (skipped on: #{filter[:skipped_on]})" if filter[:skipped_on]
193
197
  tail << " (skipped except: #{filter[:skipped_except]})" if filter[:skipped_except]
194
198
  tail
@@ -275,14 +275,14 @@ module RailsAiContext
275
275
  # reader the chain walk uses, so this line and `rails_get_controllers`
276
276
  # cannot disagree about one file. "Global" is the claim the generated
277
277
  # files make, so a `skip_before_action` and a filter carrying
278
- # only:/except:/if:/unless: are both out.
278
+ # only:/except:/if:/unless: or an if around it are both out.
279
279
  def detect_before_actions(root = project_root)
280
280
  source = ActionFilters.base_controller_source("ApplicationController", root)
281
281
  return [] unless source
282
282
 
283
283
  Introspectors::ControllerFilters.with_concerns(source, root: root.to_s, within: "ApplicationController").first
284
284
  .select { |filter| filter[:kind] == "before" && !filter[:skipped] }
285
- .reject { |filter| filter[:only] || filter[:except] || filter[:if] || filter[:unless] }
285
+ .reject { |filter| filter[:only] || filter[:except] || filter[:if] || filter[:unless] || filter[:condition] }
286
286
  .map { |filter| filter[:name] }
287
287
  rescue => e
288
288
  RailsAiContext.debug_fail(e, [], label: "Before actions scan")
@@ -317,11 +317,14 @@ module RailsAiContext
317
317
  elsif defined?(ActiveRecord::Base) && ActiveRecord::Base.respond_to?(:schema_format)
318
318
  ActiveRecord::Base.schema_format == :sql
319
319
  end
320
- if sql_format.nil?
321
- root = defined?(Rails) && Rails.respond_to?(:root) && Rails.root ? Rails.root.to_s : Dir.pwd
322
- sql_format = !File.exist?(File.join(root, "db/schema.rb")) && File.exist?(File.join(root, "db/structure.sql"))
320
+ root = defined?(Rails) && Rails.respond_to?(:root) && Rails.root ? Rails.root.to_s : Dir.pwd
321
+ candidates = RailsAiContext::Introspectors::SchemaDumpPath.candidates(root)
322
+ _, path = if sql_format.nil?
323
+ candidates.find { |_, candidate| File.exist?(candidate) } || candidates.first
324
+ else
325
+ candidates.find { |format, _| format == (sql_format ? :sql : :ruby) }
323
326
  end
324
- sql_format ? "db/structure.sql" : "db/schema.rb"
327
+ path.delete_prefix("#{root.chomp('/')}/")
325
328
  end
326
329
 
327
330
  # Generate zsh-safe CLI command. In-Gemfile installs go through the rake
@@ -188,14 +188,33 @@ module RailsAiContext
188
188
  "[rails-ai-context] Tools (#{names.size}): #{names.join(', ')}"
189
189
  end
190
190
 
191
+ # Writes to the saved channel, since the session points $stdout and fd 1
192
+ # at stderr so nothing a tool prints reaches the JSON-RPC stream.
193
+ class StdioChannelTransport < MCP::Server::Transports::StdioTransport
194
+ # The SDK sets UTF-8 on $stdout, which is $stderr here; it goes on the channel instead.
195
+ def initialize(server, channel)
196
+ stderr_encoding = [ $stdout.external_encoding, $stdout.internal_encoding ]
197
+ super(server)
198
+ $stdout.set_encoding(*stderr_encoding)
199
+ @channel = channel
200
+ @channel.set_encoding("UTF-8")
201
+ end
202
+
203
+ def send_response(message)
204
+ @channel.puts(message.is_a?(String) ? message : JSON.generate(message))
205
+ @channel.flush
206
+ end
207
+ end
208
+
191
209
  def start_stdio(server)
192
- transport = MCP::Server::Transports::StdioTransport.new(server)
193
- # Log to stderr so we don't pollute the JSON-RPC channel on stdout
194
- $stderr.puts "[rails-ai-context] MCP server started (stdio transport)"
195
- $stderr.puts tool_banner(server)
196
- RailsAiContext.stdio_open = true
197
- maybe_start_live_reload(server)
198
- transport.open
210
+ OutputGuard.quarantine_stdout(across_exec: false) do |channel|
211
+ transport = StdioChannelTransport.new(server, channel)
212
+ $stderr.puts "[rails-ai-context] MCP server started (stdio transport)"
213
+ $stderr.puts tool_banner(server)
214
+ RailsAiContext.stdio_open = true
215
+ maybe_start_live_reload(server)
216
+ transport.open
217
+ end
199
218
  ensure
200
219
  RailsAiContext.stdio_open = false
201
220
  end
@@ -6,6 +6,7 @@ module RailsAiContext
6
6
  module TestFramework
7
7
  BASES = %w[spec test].freeze
8
8
  NO_TESTS = "no tests yet"
9
+ NOT_READ = "not read"
9
10
  RSPEC_MARKERS = %w[spec/spec_helper.rb spec/rails_helper.rb spec/factories].freeze
10
11
  MINITEST_MARKERS = %w[test/test_helper.rb].freeze
11
12
 
@@ -16,15 +17,25 @@ module RailsAiContext
16
17
  #
17
18
  # @return [String] "rspec", "minitest", "rspec, minitest", or
18
19
  # "no tests yet", with "(rspec-rails in the bundle)" or
19
- # "(minitest in the bundle)" when the bundle names one
20
+ # "(minitest in the bundle)" when the bundle names one, or "not read"
21
+ # for a suite left unread (see `unread_gemfile`)
20
22
  def for(root)
21
23
  found = suites(root)
22
24
  return found.join(", ") if found.any?
25
+ return NOT_READ if unread_gemfile(root)
23
26
 
24
27
  bundled = from_lockfile(GemLock.for(root))
25
28
  bundled ? "#{NO_TESTS} (#{bundled == "rspec" ? "rspec-rails" : bundled} in the bundle)" : NO_TESTS
26
29
  end
27
30
 
31
+ # The Gemfile config/boot.rb names outside the git repository, for an app with no
32
+ # suite of its own (an engine's test/dummy): the engine's suite there is not read.
33
+ def unread_gemfile(root)
34
+ return nil if BASES.any? { |dir| Dir.exist?(File.join(root.to_s, dir)) }
35
+
36
+ GemLock.for(root).outside_gemfile
37
+ end
38
+
28
39
  def none?(framework)
29
40
  framework.to_s.start_with?(NO_TESTS)
30
41
  end
@@ -47,6 +58,19 @@ module RailsAiContext
47
58
  "#{CountPhrase.call(count, "YAML fixture set")}, #{CountPhrase.call(others, "other file")}"
48
59
  end
49
60
 
61
+ # The file count of a factories entry, nil when none of its paths was read.
62
+ def factory_files_phrase(factories)
63
+ return nil if factories[:count].nil?
64
+
65
+ phrase = CountPhrase.call(factories[:count], "file")
66
+ factories[:unread] ? "#{phrase} read" : phrase
67
+ end
68
+
69
+ def factory_location(factories)
70
+ files = factory_files_phrase(factories)
71
+ files ? "#{factories[:location]} (#{files})" : factories[:location]
72
+ end
73
+
50
74
  # RSpec wins where both are real: a new test in an app with an RSpec suite goes to RSpec.
51
75
  def command(framework)
52
76
  framework.to_s.include?("rspec") ? "bundle exec rspec" : "rails test"
@@ -158,9 +182,9 @@ module RailsAiContext
158
182
  parent = klass[:superclass] or next
159
183
  return parent if bases.include?(parent)
160
184
 
161
- chain = Introspectors::SuperclassChain.resolve_in_scope(klass[:name], parent) do |candidate|
185
+ chain = Introspectors::SuperclassChain.resolve_in_scope(klass[:name], parent, nesting: klass[:nesting]) do |candidate|
162
186
  source = lookup.call(candidate)
163
- source && Introspectors::SuperclassChain.to(source, bases: bases, lookup: lookup).presence
187
+ source && Introspectors::SuperclassChain.to(source, bases: bases, lookup: lookup, path_name: candidate).presence
164
188
  end
165
189
  return chain.last.superclass if chain
166
190
  end
@@ -170,13 +194,16 @@ module RailsAiContext
170
194
 
171
195
  # A test base class lives beside the tests, outside the autoload roots
172
196
  # SuperclassChain.lookup_for probes, at the path its name underscores to.
197
+ # The glob also matches a namesake one directory down (test/admin/base_test.rb
198
+ # for BaseTest), so the file must declare the name itself.
173
199
  def test_class_lookup(root)
174
200
  sources = {}
175
201
  lambda do |name|
176
202
  sources.fetch(name) do
177
203
  rel = "#{name.underscore}.rb"
178
- path = BASES.flat_map { |base| Dir.glob(File.join(root.to_s, base, "**", rel)) }.min
179
- sources[name] = path && SafeFile.read(path)
204
+ paths = BASES.flat_map { |base| Dir.glob(File.join(root.to_s, base, "**", rel)) }.sort
205
+ sources[name] = paths.lazy.filter_map { |path| SafeFile.read(path) }
206
+ .find { |source| Introspectors::DeclaredConstant.declarations(source, path_name: name).any? { |d| d.name == name } }
180
207
  end
181
208
  end
182
209
  end