instant_record 0.1.0 → 0.3.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 (198) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -0
  3. data/README.md +267 -61
  4. data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
  5. data/app/controllers/instant_record/events_controller.rb +58 -6
  6. data/app/controllers/instant_record/files_controller.rb +116 -0
  7. data/app/controllers/instant_record/mutations_controller.rb +84 -5
  8. data/app/controllers/instant_record/native_screens_controller.rb +60 -0
  9. data/app/controllers/instant_record/records_controller.rb +86 -8
  10. data/app/controllers/instant_record/shells_controller.rb +64 -0
  11. data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
  12. data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
  13. data/app/jobs/instant_record/shell_build_job.rb +16 -0
  14. data/app/models/instant_record/change.rb +36 -3
  15. data/app/models/instant_record/mutation_applier.rb +633 -50
  16. data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
  17. data/compiled/README.md +272 -0
  18. data/compiled/pipeline/browser_migrations.rb +18 -0
  19. data/compiled/pipeline/build.rb +13 -0
  20. data/compiled/pipeline/build_native.rb +14 -0
  21. data/compiled/pipeline/native/host.c +78 -0
  22. data/compiled/pipeline/native/instant_record_native.h +57 -0
  23. data/compiled/pipeline/native_shim.c +149 -0
  24. data/compiled/pipeline/reactor_shim.c +66 -0
  25. data/compiled/pipeline/sqlite/rh_shim.c +5 -0
  26. data/compiled/pipeline/sqlite_release.rb +43 -0
  27. data/compiled/toolchain.env.example +22 -0
  28. data/compiled/web/index.html +20 -0
  29. data/compiled/web/package-lock.json +884 -0
  30. data/compiled/web/package.json +17 -0
  31. data/compiled/web/src/app-host-core.js +556 -0
  32. data/compiled/web/src/app-host.js +16 -0
  33. data/compiled/web/src/branch-manager.js +140 -0
  34. data/compiled/web/src/branch-preview.js +397 -0
  35. data/compiled/web/src/changes.js +191 -0
  36. data/compiled/web/src/faults.js +172 -0
  37. data/compiled/web/src/flight-recorder.js +347 -0
  38. data/compiled/web/src/history-fill.js +68 -0
  39. data/compiled/web/src/http-headers.js +100 -0
  40. data/compiled/web/src/leader-election.js +705 -0
  41. data/compiled/web/src/main.js +608 -0
  42. data/compiled/web/src/manifest.js +112 -0
  43. data/compiled/web/src/opfs-wasi-core.js +109 -0
  44. data/compiled/web/src/opfs-wasi-file.js +8 -0
  45. data/compiled/web/src/reactor-runtime.js +1692 -0
  46. data/compiled/web/src/redactor.js +518 -0
  47. data/compiled/web/src/release-updates.js +48 -0
  48. data/compiled/web/src/replay.js +338 -0
  49. data/compiled/web/src/schema-recovery.js +204 -0
  50. data/compiled/web/src/server-request.js +68 -0
  51. data/compiled/web/src/sha256.js +98 -0
  52. data/compiled/web/src/shell.js +52 -0
  53. data/compiled/web/src/snapshot-store.js +38 -0
  54. data/compiled/web/src/sqlite-redactor.js +111 -0
  55. data/compiled/web/src/storage-backend.js +159 -0
  56. data/compiled/web/src/stream-leader.js +675 -0
  57. data/compiled/web/src/sync-context.js +91 -0
  58. data/compiled/web/src/sync-drain.js +104 -0
  59. data/compiled/web/src/sync-schedule.js +9 -0
  60. data/compiled/web/src/wasi-minimal.js +275 -0
  61. data/compiled/web/src/worker.js +39 -0
  62. data/compiled/web/vite.config.js +27 -0
  63. data/config/routes.rb +25 -0
  64. data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
  65. data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
  66. data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
  67. data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
  68. data/exe/instant_record_mcp +6 -0
  69. data/frontend/LiveList.js +67 -0
  70. data/frontend/chord.js +79 -0
  71. data/frontend/file.js +65 -0
  72. data/frontend/files.js +738 -0
  73. data/frontend/focus.js +10 -0
  74. data/frontend/held.js +192 -0
  75. data/frontend/http.js +76 -0
  76. data/frontend/index.js +53 -0
  77. data/frontend/keyboard.js +56 -0
  78. data/frontend/live.js +298 -0
  79. data/frontend/notices.js +118 -0
  80. data/frontend/package.json +15 -0
  81. data/frontend/range.js +10 -0
  82. data/frontend/selection.js +47 -0
  83. data/frontend/shortcuts.js +25 -0
  84. data/frontend/sync-notices.js +130 -0
  85. data/frontend/undo.js +48 -0
  86. data/frontend/window.js +181 -0
  87. data/lib/generators/instant_record/install/install_generator.rb +18 -30
  88. data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
  89. data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
  90. data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
  91. data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
  92. data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
  93. data/lib/instant_record/branch/sqlite_store.rb +142 -0
  94. data/lib/instant_record/branch.rb +388 -0
  95. data/lib/instant_record/client/notifier.rb +8 -12
  96. data/lib/instant_record/client/rebaser.rb +565 -0
  97. data/lib/instant_record/client/transport.rb +64 -42
  98. data/lib/instant_record/client.rb +1600 -169
  99. data/lib/instant_record/compiled_site.rb +85 -0
  100. data/lib/instant_record/compiler/app_stage.rb +212 -0
  101. data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
  102. data/lib/instant_record/compiler/browser_migrations.rb +161 -0
  103. data/lib/instant_record/compiler/entry_builder.rb +832 -0
  104. data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
  105. data/lib/instant_record/compiler/gem_vendor.rb +194 -0
  106. data/lib/instant_record/compiler/host_adapters.rb +506 -0
  107. data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
  108. data/lib/instant_record/compiler/manifest.rb +178 -0
  109. data/lib/instant_record/compiler/native_build.rb +586 -0
  110. data/lib/instant_record/compiler/native_contracts.rb +338 -0
  111. data/lib/instant_record/compiler/path_scrubber.rb +31 -0
  112. data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
  113. data/lib/instant_record/compiler/route_analyzer.rb +623 -0
  114. data/lib/instant_record/compiler/runner.rb +42 -0
  115. data/lib/instant_record/compiler/schema_lock.rb +606 -0
  116. data/lib/instant_record/compiler/source_pages.rb +77 -0
  117. data/lib/instant_record/compiler/static_linter.rb +770 -0
  118. data/lib/instant_record/compiler/swift_codegen.rb +341 -0
  119. data/lib/instant_record/compiler/toolchain.rb +219 -0
  120. data/lib/instant_record/compiler/wasm_build.rb +704 -0
  121. data/lib/instant_record/compiler/wasm_tree.rb +518 -0
  122. data/lib/instant_record/compiler.rb +277 -0
  123. data/lib/instant_record/configuration.rb +104 -0
  124. data/lib/instant_record/engine.rb +68 -18
  125. data/lib/instant_record/file_store.rb +162 -0
  126. data/lib/instant_record/files.rb +92 -0
  127. data/lib/instant_record/hlc.rb +387 -0
  128. data/lib/instant_record/host.rb +66 -0
  129. data/lib/instant_record/inertia/renderer.rb +52 -0
  130. data/lib/instant_record/inertia.rb +222 -0
  131. data/lib/instant_record/mcp/cli.rb +319 -0
  132. data/lib/instant_record/mcp/host_process.rb +229 -0
  133. data/lib/instant_record/mcp/http_exchange.rb +233 -0
  134. data/lib/instant_record/mcp/replica.rb +556 -0
  135. data/lib/instant_record/mcp/runtime.rb +406 -0
  136. data/lib/instant_record/mcp/server.rb +429 -0
  137. data/lib/instant_record/mcp.rb +47 -0
  138. data/lib/instant_record/native/contract.rb +367 -0
  139. data/lib/instant_record/native/node.rb +125 -0
  140. data/lib/instant_record/native/screen.rb +366 -0
  141. data/lib/instant_record/native/xcode_project.rb +344 -0
  142. data/lib/instant_record/native.rb +41 -0
  143. data/lib/instant_record/outbox_mutation.rb +81 -9
  144. data/lib/instant_record/outbox_upcaster.rb +161 -0
  145. data/lib/instant_record/read_tracker.rb +610 -0
  146. data/lib/instant_record/routing.rb +33 -0
  147. data/lib/instant_record/runtime_scoped.rb +4 -0
  148. data/lib/instant_record/shell.rb +486 -0
  149. data/lib/instant_record/sync_actions.rb +800 -0
  150. data/lib/instant_record/sync_metadata.rb +17 -2
  151. data/lib/instant_record/sync_notice.rb +234 -0
  152. data/lib/instant_record/sync_partition.rb +63 -0
  153. data/lib/instant_record/sync_scope.rb +300 -0
  154. data/lib/instant_record/sync_shape.rb +102 -0
  155. data/lib/instant_record/sync_window.rb +92 -15
  156. data/lib/instant_record/syncable.rb +313 -17
  157. data/lib/instant_record/testing/authoritative_server.rb +547 -0
  158. data/lib/instant_record/testing/chaos_simulator.rb +429 -0
  159. data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
  160. data/lib/instant_record/testing/fault_network.rb +140 -0
  161. data/lib/instant_record/testing/parity_suite.rb +435 -0
  162. data/lib/instant_record/testing/runtimes/base.rb +184 -0
  163. data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
  164. data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
  165. data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
  166. data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
  167. data/lib/instant_record/testing.rb +333 -0
  168. data/lib/instant_record/trace/redactor.rb +278 -0
  169. data/lib/instant_record/trace/replayer.rb +126 -0
  170. data/lib/instant_record/trace/schema_extractor.rb +37 -0
  171. data/lib/instant_record/trace.rb +22 -0
  172. data/lib/instant_record/version.rb +1 -1
  173. data/lib/instant_record.rb +107 -37
  174. data/lib/tasks/instant_record.rake +299 -47
  175. data/native/ios/InstantRecordNative/Package.swift +12 -0
  176. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
  177. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
  178. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
  179. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
  180. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
  181. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
  182. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
  183. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
  184. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
  185. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
  186. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
  187. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
  188. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
  189. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
  190. data/native/ios/README.md +341 -0
  191. data/sig/instant_record/inertia.rbs +47 -0
  192. data/sig/instant_record/native.rbs +38 -0
  193. metadata +194 -18
  194. data/lib/generators/instant_record/install/templates/database.js +0 -32
  195. data/lib/generators/instant_record/install/templates/index.html +0 -69
  196. data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
  197. data/lib/instant_record/local_schema.rb +0 -75
  198. data/lib/instant_record/pglite_compat.rb +0 -40
@@ -0,0 +1,1188 @@
1
+ require "active_support/inflector"
2
+ require "action_view"
3
+ require "prism"
4
+ require "set"
5
+ require_relative "manifest"
6
+ require_relative "runner"
7
+
8
+ module InstantRecord
9
+ class Compiler
10
+ # Prism + ActionView::Erubi transitive reachability tracer for Local-First Islands.
11
+ # Starting from local_first routes (plus explicit include overrides and, for
12
+ # native builds, app/screens), stages only reachable controllers, models,
13
+ # views, helpers, and migrations — skipping `server_only` blocks while
14
+ # traversing `browser_only`/`client_only` blocks — and emits crisp
15
+ # missing-symbol diagnostics and dynamic-pattern hints.
16
+ class ReachabilityTracer
17
+ FRAMEWORK_TABLES = %w[
18
+ instant_record_outbox
19
+ instant_record_sync_metadata
20
+ instant_record_changes
21
+ instant_record_applied_mutations
22
+ ].freeze
23
+
24
+ ASSOCIATION_MACROS = %i[belongs_to has_many has_one has_and_belongs_to_many].freeze
25
+ NON_TEMPLATE_RENDER_KEYS = %i[json plain html inline body xml js file head nothing].freeze
26
+ DDL_TABLE_CALLS = %i[
27
+ create_table change_table drop_table rename_table
28
+ add_column remove_column change_column change_column_null change_column_default rename_column
29
+ add_index remove_index
30
+ add_reference remove_reference add_belongs_to remove_belongs_to
31
+ add_timestamps remove_timestamps
32
+ add_foreign_key remove_foreign_key
33
+ ].freeze
34
+
35
+ Result = Struct.new(
36
+ :controllers,
37
+ :models,
38
+ :views,
39
+ :helpers,
40
+ :screens,
41
+ :migrations,
42
+ :manifest_migrations,
43
+ :extra_files,
44
+ :model_metadata,
45
+ :diagnostics,
46
+ keyword_init: true
47
+ )
48
+
49
+ # Extracts constant references, associations, renders, sync macros, and
50
+ # dynamic patterns from a single Ruby AST while ignoring `server_only`.
51
+ class FileVisitor < Prism::Visitor
52
+ DYNAMIC = Object.new.freeze
53
+
54
+ attr_reader :constants, :associations, :renders, :layouts, :helper_decls,
55
+ :bare_calls, :includes, :superclass, :table_name, :abstract_class,
56
+ :syncable, :sync_window, :sync_scope_column, :sync_scope_policy,
57
+ :sync_file, :dynamic_warnings
58
+
59
+ def initialize(rel_path:, is_view: false, is_helper: false)
60
+ super()
61
+ @rel_path = rel_path
62
+ @is_view = is_view
63
+ @is_helper = is_helper
64
+ @namespace = []
65
+ @constants = []
66
+ @associations = []
67
+ @renders = []
68
+ @layouts = []
69
+ @helper_decls = []
70
+ @bare_calls = Set.new
71
+ @includes = []
72
+ @superclass = nil
73
+ @table_name = nil
74
+ @abstract_class = false
75
+ @syncable = false
76
+ @sync_window = nil
77
+ @sync_scope_column = nil
78
+ @sync_scope_policy = false
79
+ @sync_file = false
80
+ @dynamic_warnings = []
81
+ end
82
+
83
+ def visit_module_node(node)
84
+ name = constant_node_segments(node.constant_path)
85
+ @namespace.concat(name) if name
86
+ super
87
+ ensure
88
+ @namespace.pop(name.length) if name
89
+ end
90
+
91
+ def visit_class_node(node)
92
+ name = constant_node_segments(node.constant_path)
93
+ if node.superclass
94
+ sup = constant_node_segments(node.superclass)
95
+ if sup
96
+ @superclass ||= sup.join("::")
97
+ @constants << {
98
+ segments: sup,
99
+ top_level: top_level_const?(node.superclass),
100
+ namespace: @namespace.dup,
101
+ line: node.superclass.location.start_line
102
+ }
103
+ end
104
+ end
105
+ @namespace.concat(name) if name
106
+ visit(node.body) if node.body
107
+ ensure
108
+ @namespace.pop(name.length) if name
109
+ end
110
+
111
+ def visit_constant_path_node(node)
112
+ segments = constant_node_segments(node)
113
+ if segments
114
+ @constants << {
115
+ segments: segments,
116
+ top_level: top_level_const?(node),
117
+ namespace: @namespace.dup,
118
+ line: node.location.start_line
119
+ }
120
+ else
121
+ super
122
+ end
123
+ end
124
+
125
+ def visit_constant_read_node(node)
126
+ @constants << {
127
+ segments: [node.name.to_s],
128
+ top_level: false,
129
+ namespace: @namespace.dup,
130
+ line: node.location.start_line
131
+ }
132
+ end
133
+
134
+ def visit_call_node(node)
135
+ # Strictly skip server_only blocks (only note syncable_to / writable_by policy presence).
136
+ if node.receiver.nil? && node.name == :server_only && node.block
137
+ @sync_scope_policy = true if block_calls_policy?(node.block)
138
+ return
139
+ end
140
+
141
+ # Detect self.table_name = "..." and self.abstract_class = true
142
+ if node.receiver.nil? || node.receiver.is_a?(Prism::SelfNode)
143
+ if node.name == :table_name=
144
+ arg = Array(node.arguments&.arguments).first
145
+ @table_name = arg.unescaped if arg.is_a?(Prism::StringNode)
146
+ elsif node.name == :abstract_class=
147
+ arg = Array(node.arguments&.arguments).first
148
+ @abstract_class = true if arg.is_a?(Prism::TrueNode)
149
+ end
150
+ end
151
+
152
+ if node.receiver.nil?
153
+ @bare_calls << node.name.to_s
154
+ inspect_bare_call(node)
155
+ else
156
+ inspect_receiver_call(node)
157
+ end
158
+
159
+ super
160
+ end
161
+
162
+ private
163
+
164
+ def block_calls_policy?(block_node)
165
+ queue = [block_node]
166
+ while (current = queue.shift)
167
+ if current.is_a?(Prism::CallNode) && current.receiver.nil? &&
168
+ %i[syncable_to writable_by].include?(current.name)
169
+ return true
170
+ end
171
+ queue.concat(current.compact_child_nodes)
172
+ end
173
+ false
174
+ end
175
+
176
+ def inspect_bare_call(node)
177
+ case node.name
178
+ when :include, :extend, :prepend
179
+ Array(node.arguments&.arguments).each do |arg|
180
+ segs = constant_node_segments(arg)
181
+ next unless segs
182
+
183
+ full = segs.join("::")
184
+ @includes << full
185
+ @syncable = true if full == "InstantRecord::Syncable" || full == "Syncable"
186
+ end
187
+ when :sync_window
188
+ extract_sync_window(node)
189
+ when :sync_scope
190
+ arg = Array(node.arguments&.arguments).first
191
+ if arg.is_a?(Prism::SymbolNode) || arg.is_a?(Prism::StringNode)
192
+ @sync_scope_column = arg.unescaped
193
+ end
194
+ when :syncable_to, :writable_by
195
+ @sync_scope_policy = true
196
+ when :sync_file
197
+ @sync_file = true
198
+ when *ASSOCIATION_MACROS
199
+ extract_association(node)
200
+ when :render
201
+ extract_render(node)
202
+ when :layout
203
+ extract_layout(node)
204
+ when :helper
205
+ extract_helper(node)
206
+ when :const_get
207
+ record_dynamic_warning("const_get", node.location.start_line,
208
+ "Dynamic constant lookup via const_get; declare referenced classes in include: { models: [...] } if needed.")
209
+ end
210
+ end
211
+
212
+ def inspect_receiver_call(node)
213
+ if %i[constantize safe_constantize const_get].include?(node.name)
214
+ record_dynamic_warning(node.name.to_s, node.location.start_line,
215
+ "Dynamic constant lookup via #{node.name}; declare referenced classes in include: { models: [...] } if needed.")
216
+ end
217
+ end
218
+
219
+ def extract_sync_window(node)
220
+ opts = extract_keyword_hash(node)
221
+ limit = opts[:limit]
222
+ return unless limit.is_a?(Integer) && limit.positive?
223
+
224
+ partition_by = opts[:partition_by]&.to_s
225
+ @sync_window = {
226
+ "limit" => limit,
227
+ "partition_by" => partition_by && !partition_by.empty? ? partition_by : nil
228
+ }
229
+ end
230
+
231
+ def extract_association(node)
232
+ args = Array(node.arguments&.arguments)
233
+ first = args.first
234
+ return unless first.is_a?(Prism::SymbolNode) || first.is_a?(Prism::StringNode)
235
+
236
+ opts = extract_keyword_hash(node)
237
+ return if opts[:polymorphic] == true
238
+
239
+ assoc_name = first.unescaped
240
+ through = opts.key?(:through)
241
+ source_opt = opts[:source]
242
+ target =
243
+ if opts[:class_name].is_a?(String) && !opts[:class_name].empty?
244
+ opts[:class_name]
245
+ elsif through && (source_opt.is_a?(String) || source_opt.is_a?(Symbol))
246
+ ActiveSupport::Inflector.classify(source_opt.to_s)
247
+ else
248
+ ActiveSupport::Inflector.classify(assoc_name)
249
+ end
250
+
251
+ @associations << {
252
+ name: assoc_name,
253
+ class_name: target.delete_prefix("::"),
254
+ namespace: @namespace.dup,
255
+ through: through,
256
+ line: node.location.start_line
257
+ }
258
+ end
259
+
260
+ def extract_render(node)
261
+ args = Array(node.arguments&.arguments)
262
+ return if args.empty?
263
+
264
+ opts = extract_keyword_hash(node)
265
+ return if (opts.keys & NON_TEMPLATE_RENDER_KEYS).any?
266
+
267
+ if opts.key?(:partial)
268
+ val = opts[:partial]
269
+ if val.is_a?(String) || val.is_a?(Symbol)
270
+ @renders << { kind: :partial, target: val.to_s, line: node.location.start_line }
271
+ else
272
+ record_dynamic_warning("render", node.location.start_line,
273
+ "Dynamic partial render; declare targets in include: { partials: [...] }.")
274
+ end
275
+ elsif opts.key?(:template)
276
+ val = opts[:template]
277
+ if val.is_a?(String) || val.is_a?(Symbol)
278
+ @renders << { kind: :template, target: val.to_s, line: node.location.start_line }
279
+ else
280
+ record_dynamic_warning("render", node.location.start_line,
281
+ "Dynamic template render; declare targets in include: { views: [...] }.")
282
+ end
283
+ elsif opts.key?(:action)
284
+ val = opts[:action]
285
+ if val.is_a?(String) || val.is_a?(Symbol)
286
+ @renders << { kind: :template, target: val.to_s, line: node.location.start_line }
287
+ end
288
+ else
289
+ first = args.first
290
+ unless first.is_a?(Prism::KeywordHashNode) || first.is_a?(Prism::HashNode)
291
+ if first.is_a?(Prism::StringNode) || first.is_a?(Prism::SymbolNode)
292
+ kind = (@is_view || @is_helper) ? :partial : :template
293
+ @renders << { kind: kind, target: first.unescaped, line: node.location.start_line }
294
+ else
295
+ record_dynamic_warning("render", node.location.start_line,
296
+ "Dynamic render expression; declare targets in include: { partials: [...] } or include: { views: [...] }.")
297
+ end
298
+ end
299
+ end
300
+
301
+ # Independently handle `layout:` option (e.g. `render partial: "row", layout: "card"`).
302
+ if opts.key?(:layout)
303
+ layout_val = opts[:layout]
304
+ if layout_val.is_a?(String) || layout_val.is_a?(Symbol)
305
+ if @is_view || @is_helper || opts.key?(:partial)
306
+ @renders << { kind: :partial, target: layout_val.to_s, line: node.location.start_line }
307
+ else
308
+ @layouts << { target: layout_val.to_s, line: node.location.start_line }
309
+ end
310
+ end
311
+ end
312
+ end
313
+
314
+ def extract_layout(node)
315
+ first = Array(node.arguments&.arguments).first
316
+ return unless first.is_a?(Prism::StringNode) || first.is_a?(Prism::SymbolNode)
317
+
318
+ @layouts << { target: first.unescaped, line: node.location.start_line }
319
+ end
320
+
321
+ def extract_helper(node)
322
+ Array(node.arguments&.arguments).each do |arg|
323
+ case arg
324
+ when Prism::SymbolNode, Prism::StringNode
325
+ @helper_decls << { kind: :name, value: arg.unescaped, line: node.location.start_line }
326
+ else
327
+ segs = constant_node_segments(arg)
328
+ @helper_decls << { kind: :const, value: segs.join("::"), line: node.location.start_line } if segs
329
+ end
330
+ end
331
+ end
332
+
333
+ def record_dynamic_warning(kind, line, message)
334
+ @dynamic_warnings << {
335
+ "level" => "warning",
336
+ "kind" => kind,
337
+ "file" => @rel_path,
338
+ "line" => line,
339
+ "message" => message
340
+ }
341
+ end
342
+
343
+ def constant_node_segments(node)
344
+ case node
345
+ when Prism::ConstantReadNode
346
+ [node.name.to_s]
347
+ when Prism::ConstantPathNode
348
+ if node.parent.nil?
349
+ [node.name.to_s]
350
+ else
351
+ parent = constant_node_segments(node.parent)
352
+ parent ? parent + [node.name.to_s] : nil
353
+ end
354
+ else
355
+ nil
356
+ end
357
+ end
358
+
359
+ def top_level_const?(node)
360
+ cur = node
361
+ cur = cur.parent while cur.is_a?(Prism::ConstantPathNode) && cur.parent
362
+ cur.is_a?(Prism::ConstantPathNode) && cur.parent.nil?
363
+ end
364
+
365
+ def extract_keyword_hash(call)
366
+ opts = {}
367
+ Array(call.arguments&.arguments).each do |arg|
368
+ next unless arg.is_a?(Prism::KeywordHashNode) || arg.is_a?(Prism::HashNode)
369
+
370
+ arg.elements.each do |assoc|
371
+ next unless assoc.is_a?(Prism::AssocNode)
372
+
373
+ key = literal(assoc.key)
374
+ next unless key.is_a?(Symbol) || key.is_a?(String)
375
+
376
+ val = literal(assoc.value)
377
+ opts[key.to_sym] = val.nil? ? DYNAMIC : val
378
+ end
379
+ end
380
+ opts
381
+ end
382
+
383
+ def literal(node)
384
+ case node
385
+ when Prism::SymbolNode then node.unescaped.to_sym
386
+ when Prism::StringNode then node.unescaped
387
+ when Prism::IntegerNode, Prism::FloatNode then node.value
388
+ when Prism::TrueNode then true
389
+ when Prism::FalseNode then false
390
+ when Prism::NilNode then false
391
+ else nil
392
+ end
393
+ end
394
+ end
395
+
396
+ def self.trace(source_root:, route_analysis:, overrides: nil, native: false, migration_paths: nil, overlay_dir: nil)
397
+ new(
398
+ source_root: source_root,
399
+ route_analysis: route_analysis,
400
+ overrides: overrides,
401
+ native: native,
402
+ migration_paths: migration_paths,
403
+ overlay_dir: overlay_dir
404
+ ).trace
405
+ end
406
+
407
+ # +overlay_dir+ holds files that replace the app's own under app/ once it
408
+ # is staged (AppStage copies it over last). The trace reads those in place
409
+ # of the originals, so what is staged is what the staged code reaches: a
410
+ # partial only the replaced controller rendered is left behind.
411
+ def initialize(source_root:, route_analysis:, overrides: nil, native: false, migration_paths: nil, overlay_dir: nil)
412
+ @source_root = File.expand_path(source_root.to_s)
413
+ @overlay_dir = overlay_dir && File.directory?(overlay_dir) ? File.expand_path(overlay_dir.to_s) : nil
414
+ @route_analysis = route_analysis
415
+ @overrides = Manifest.merge_overrides(route_analysis.overrides, overrides)
416
+ @native = native
417
+ @migration_paths = migration_paths
418
+
419
+ @staged_controllers = Set.new
420
+ @staged_models = Set.new
421
+ @staged_views = Set.new
422
+ @staged_helpers = Set.new
423
+ @staged_screens = Set.new
424
+ @staged_extra_files = Set.new
425
+
426
+ @visited = Set.new
427
+ @queue = []
428
+ @model_metadata = {}
429
+ @concern_syncable = Set.new
430
+ @diagnostics = []
431
+ @errors = []
432
+ end
433
+
434
+ def trace
435
+ index_app_files!
436
+ if @route_analysis.has_local_first
437
+ seed_island!
438
+ else
439
+ seed_full_app!
440
+ end
441
+ process_queue!
442
+ resolve_model_inheritance!
443
+ check_sti_subclasses!
444
+ migrations, manifest_migrations = filter_migrations
445
+
446
+ unless @errors.empty?
447
+ raise BuildError, format_errors(@errors)
448
+ end
449
+
450
+ Result.new(
451
+ controllers: @staged_controllers.to_a.sort,
452
+ models: @staged_models.to_a.sort,
453
+ views: @staged_views.to_a.sort,
454
+ helpers: @staged_helpers.to_a.sort,
455
+ screens: @staged_screens.to_a.sort,
456
+ migrations: migrations,
457
+ manifest_migrations: manifest_migrations,
458
+ extra_files: @staged_extra_files.to_a.sort,
459
+ model_metadata: @model_metadata,
460
+ diagnostics: @diagnostics.uniq
461
+ )
462
+ end
463
+
464
+ private
465
+
466
+ def index_app_files!
467
+ @controller_files = glob_rel("app/controllers/**/*.rb")
468
+ @model_files = glob_rel("app/models/**/*.rb")
469
+ @helper_files = glob_rel("app/helpers/**/*.rb")
470
+ @view_files = glob_rel("app/views/**/*").select { |rel| File.file?(File.join(@source_root, rel)) }
471
+ @screen_files = glob_rel("app/screens/**/*.rb")
472
+
473
+ # Map constant names -> relative file paths for stageable categories.
474
+ @stageable_constants = {}
475
+ @controller_files.each { |rel| register_const_path(@stageable_constants, const_from_rel(rel, "app/controllers/"), rel) }
476
+ @model_files.each do |rel|
477
+ register_const_path(@stageable_constants, const_from_rel(rel, "app/models/"), rel)
478
+ if rel.start_with?("app/models/concerns/")
479
+ register_const_path(@stageable_constants, const_from_rel(rel, "app/models/concerns/"), rel)
480
+ end
481
+ end
482
+ @helper_files.each { |rel| register_const_path(@stageable_constants, const_from_rel(rel, "app/helpers/"), rel) }
483
+ @controller_files.each do |rel|
484
+ if rel.start_with?("app/controllers/concerns/")
485
+ register_const_path(@stageable_constants, const_from_rel(rel, "app/controllers/concerns/"), rel)
486
+ end
487
+ end
488
+ @screen_files.each { |rel| register_const_path(@stageable_constants, const_from_rel(rel, "app/screens/"), rel) } if @native
489
+
490
+ # Index unstaged app directories (jobs, services, mailers, channels, non-native screens, lib)
491
+ # for crisp missing-symbol diagnostics.
492
+ @unstaged_constants = {}
493
+ Dir.glob("app/**/*.rb", base: @source_root).sort.each do |rel|
494
+ next if rel.start_with?("app/controllers/", "app/models/", "app/helpers/")
495
+ next if @native && rel.start_with?("app/screens/")
496
+
497
+ top_dir = rel.split("/")[1]
498
+ const_name = const_from_rel(rel, "app/#{top_dir}/")
499
+ @unstaged_constants[const_name] ||= rel
500
+ end
501
+ Dir.glob("lib/**/*.rb", base: @source_root).sort.each do |rel|
502
+ next if rel.start_with?("lib/tasks/")
503
+
504
+ const_name = const_from_rel(rel, "lib/")
505
+ @unstaged_constants[const_name] ||= rel
506
+ end
507
+
508
+ # Index public helper methods -> helper rel path so views/helpers calling one automatically stage it.
509
+ @helper_methods = {}
510
+ @helper_files.each do |rel|
511
+ parsed = Prism.parse_file(File.join(@source_root, rel))
512
+ next unless parsed.success?
513
+
514
+ extract_public_helper_defs(parsed.value).each do |method_name|
515
+ (@helper_methods[method_name] ||= []) << rel
516
+ end
517
+ end
518
+ end
519
+
520
+ def seed_island!
521
+ enqueue_if_exists("app/controllers/application_controller.rb")
522
+ enqueue_if_exists("app/models/application_record.rb")
523
+ enqueue_if_exists("app/helpers/application_helper.rb")
524
+ glob_rel("app/views/layouts/application.*").each { |rel| enqueue(rel) }
525
+
526
+ @route_analysis.local_routes.each do |route|
527
+ controller = route["controller"]
528
+ action = route["action"]
529
+ next if controller.nil? || controller.empty?
530
+
531
+ ctrl_rel = "app/controllers/#{controller}_controller.rb"
532
+ if safe_source_file?(ctrl_rel)
533
+ enqueue(ctrl_rel)
534
+ else
535
+ @errors << "Missing controller for local_first route #{route['method']} #{route['path']} " \
536
+ "-> #{controller}##{action} (expected #{ctrl_rel})."
537
+ next
538
+ end
539
+
540
+ if action && !action.empty?
541
+ find_view_files(controller, action, partial: false).each { |rel| enqueue(rel) }
542
+ end
543
+
544
+ enqueue_if_exists("app/helpers/#{controller}_helper.rb")
545
+ top_ns = controller.split("/").first
546
+ enqueue_if_exists("app/helpers/#{top_ns}_helper.rb") if controller.include?("/")
547
+ end
548
+
549
+ @screen_files.each { |rel| enqueue(rel) } if @native
550
+
551
+ apply_explicit_includes!
552
+ end
553
+
554
+ def seed_full_app!
555
+ @controller_files.each { |rel| enqueue(rel) }
556
+ @model_files.each { |rel| enqueue(rel) }
557
+ @helper_files.each { |rel| enqueue(rel) }
558
+ @view_files.each { |rel| enqueue(rel) }
559
+ @screen_files.each { |rel| enqueue(rel) } if @native
560
+ apply_explicit_includes!
561
+ end
562
+
563
+ def apply_explicit_includes!
564
+ inc = @overrides[:include]
565
+
566
+ inc["models"].each do |entry|
567
+ rel = resolve_model_override(entry)
568
+ if rel
569
+ enqueue(rel)
570
+ else
571
+ @errors << "Explicit include.models entry #{entry.inspect} was not found under app/models/."
572
+ end
573
+ end
574
+
575
+ inc["controllers"].each do |entry|
576
+ rel = resolve_controller_override(entry)
577
+ if rel
578
+ enqueue(rel)
579
+ else
580
+ @errors << "Explicit include.controllers entry #{entry.inspect} was not found under app/controllers/."
581
+ end
582
+ end
583
+
584
+ inc["helpers"].each do |entry|
585
+ rel = resolve_helper_override(entry)
586
+ if rel
587
+ enqueue(rel)
588
+ else
589
+ @errors << "Explicit include.helpers entry #{entry.inspect} was not found under app/helpers/."
590
+ end
591
+ end
592
+
593
+ inc["views"].each do |entry|
594
+ matches = resolve_view_override(entry, partial: false)
595
+ if matches.any?
596
+ matches.each { |rel| enqueue(rel) }
597
+ else
598
+ @errors << "Explicit include.views entry #{entry.inspect} was not found under app/views/."
599
+ end
600
+ end
601
+
602
+ inc["partials"].each do |entry|
603
+ matches = resolve_view_override(entry, partial: true)
604
+ if matches.any?
605
+ matches.each { |rel| enqueue(rel) }
606
+ else
607
+ @errors << "Explicit include.partials entry #{entry.inspect} was not found under app/views/."
608
+ end
609
+ end
610
+
611
+ inc["files"].each do |entry|
612
+ rel = sanitize_relative_path(entry)
613
+ if rel && safe_source_file?(rel)
614
+ @staged_extra_files << rel
615
+ enqueue(rel) if rel.end_with?(".rb", ".erb")
616
+ else
617
+ @errors << "Explicit include.files entry #{entry.inspect} does not exist inside #{@source_root}."
618
+ end
619
+ end
620
+ end
621
+
622
+ def process_queue!
623
+ while (rel = @queue.shift)
624
+ next if @visited.include?(rel)
625
+
626
+ @visited << rel
627
+ categorize(rel)
628
+
629
+ full = overlaid(rel) || File.join(@source_root, rel)
630
+ next unless File.file?(full)
631
+
632
+ if rel.end_with?(".rb")
633
+ visit_ruby_file(rel, full)
634
+ elsif rel.end_with?(".erb")
635
+ visit_erb_file(rel, full)
636
+ end
637
+ end
638
+ end
639
+
640
+ # The overlay's replacement for an app file, if it has one.
641
+ def overlaid(rel)
642
+ return unless @overlay_dir && rel.start_with?("app/")
643
+
644
+ path = File.join(@overlay_dir, rel.delete_prefix("app/"))
645
+ path if File.file?(path)
646
+ end
647
+
648
+ def visit_ruby_file(rel, full)
649
+ source = File.read(full, encoding: "UTF-8")
650
+ parsed = Prism.parse(source)
651
+ unless parsed.success?
652
+ errors = parsed.errors.map { |e| "line #{e.location.start_line}: #{e.message}" }.join("; ")
653
+ @errors << "Syntax error in #{rel}: #{errors}"
654
+ return
655
+ end
656
+
657
+ is_helper = rel.start_with?("app/helpers/")
658
+ visitor = FileVisitor.new(rel_path: rel, is_view: false, is_helper: is_helper)
659
+ parsed.value.accept(visitor)
660
+
661
+ @diagnostics.concat(visitor.dynamic_warnings)
662
+ if rel.start_with?("app/models/concerns/")
663
+ if visitor.syncable
664
+ @concern_syncable << const_from_rel(rel, "app/models/concerns/")
665
+ @concern_syncable << const_from_rel(rel, "app/models/")
666
+ end
667
+ elsif rel.start_with?("app/models/")
668
+ record_model_metadata(rel, visitor)
669
+ end
670
+
671
+ resolve_visitor_edges!(rel, visitor, is_view: false, is_helper: is_helper)
672
+ end
673
+
674
+ def visit_erb_file(rel, full)
675
+ erb_source = File.read(full, encoding: "UTF-8")
676
+ ruby_source = ActionView::Template::Handlers::ERB::Erubi.new(erb_source).src
677
+ # Wrap in a method body so `yield` in layouts is valid Ruby, preserving 1-based line numbers via line: 0.
678
+ parsed = Prism.parse("def _instant_record_template\n#{ruby_source}\nend\n", line: 0)
679
+ unless parsed.success?
680
+ errors = parsed.errors.map { |e| "line #{e.location.start_line}: #{e.message}" }.join("; ")
681
+ @errors << "ERB syntax error in #{rel}: #{errors}"
682
+ return
683
+ end
684
+
685
+ visitor = FileVisitor.new(rel_path: rel, is_view: true)
686
+ parsed.value.accept(visitor)
687
+
688
+ @diagnostics.concat(visitor.dynamic_warnings)
689
+ resolve_visitor_edges!(rel, visitor, is_view: true, is_helper: false)
690
+ end
691
+
692
+ def resolve_visitor_edges!(rel, visitor, is_view:, is_helper:)
693
+ # 1. Constant references: check exact/longer matches across BOTH tables before falling back to prefixes.
694
+ visitor.constants.each do |ref|
695
+ kind, target_rel = resolve_constant_with_precedence(ref)
696
+ if kind == :stageable
697
+ enqueue(target_rel)
698
+ elsif kind == :unstaged && @route_analysis.has_local_first && !@staged_extra_files.include?(target_rel)
699
+ const_name = ref[:segments].join("::")
700
+ @errors << "Missing symbol #{const_name} referenced at #{rel}:#{ref[:line]} — " \
701
+ "defined in #{target_rel} (outside local-first island). " \
702
+ "Wrap server-only code in `server_only do ... end` or add it to `include: { files: [#{target_rel.inspect}] }`."
703
+ end
704
+ end
705
+
706
+ # 2. ActiveRecord associations -> stage target model or flag missing model.
707
+ visitor.associations.each do |assoc|
708
+ assoc_ref = { segments: assoc[:class_name].split("::"), top_level: false, namespace: assoc[:namespace] }
709
+ model_rel = lookup_constant(@stageable_constants, assoc_ref)
710
+ if model_rel
711
+ enqueue(model_rel)
712
+ elsif @route_analysis.has_local_first && !assoc[:through]
713
+ expected = "app/models/#{ActiveSupport::Inflector.underscore(assoc[:class_name])}.rb"
714
+ unless safe_source_file?(expected)
715
+ @errors << "Missing model #{assoc[:class_name]} for association :#{assoc[:name]} at #{rel}:#{assoc[:line]} " \
716
+ "(expected #{expected})."
717
+ end
718
+ end
719
+ end
720
+
721
+ # 3. Render calls -> stage matching partials/templates or flag missing template.
722
+ current_dir = view_dir_for(rel, is_view: is_view)
723
+ visitor.renders.each do |render_ref|
724
+ is_partial = render_ref[:kind] == :partial
725
+ matches = resolve_render_target(render_ref[:target], current_dir, partial: is_partial)
726
+ if matches.any?
727
+ matches.each { |path| enqueue(path) }
728
+ elsif @route_analysis.has_local_first
729
+ kind_label = is_partial ? "partial" : "template"
730
+ hint_key = is_partial ? "partials" : "views"
731
+ @errors << "Missing #{kind_label} #{render_ref[:target].inspect} rendered at #{rel}:#{render_ref[:line]} " \
732
+ "(searched under app/views/#{current_dir}). Add the file or declare include: { #{hint_key}: [...] }."
733
+ end
734
+ end
735
+
736
+ # 4. Controller layout declarations.
737
+ visitor.layouts.each do |layout_ref|
738
+ matches = find_view_files("layouts", layout_ref[:target], partial: false)
739
+ if matches.any?
740
+ matches.each { |path| enqueue(path) }
741
+ elsif @route_analysis.has_local_first
742
+ @errors << "Missing layout #{layout_ref[:target].inspect} declared at #{rel}:#{layout_ref[:line]} " \
743
+ "(expected app/views/layouts/#{layout_ref[:target]}.html.erb)."
744
+ end
745
+ end
746
+
747
+ # 5. Controller helper declarations.
748
+ visitor.helper_decls.each do |decl|
749
+ helper_rel =
750
+ if decl[:kind] == :name
751
+ resolve_helper_override(decl[:value])
752
+ else
753
+ candidate = @stageable_constants[decl[:value]]
754
+ candidate&.start_with?("app/helpers/") ? candidate : nil
755
+ end
756
+ if helper_rel
757
+ enqueue(helper_rel)
758
+ elsif @route_analysis.has_local_first
759
+ @errors << "Missing helper #{decl[:value].inspect} declared at #{rel}:#{decl[:line]}."
760
+ end
761
+ end
762
+
763
+ # 6. Helper method calls in views, controllers, and helpers -> stage helper that defines them.
764
+ if is_view || is_helper || rel.start_with?("app/controllers/")
765
+ visitor.bare_calls.each do |method_name|
766
+ Array(@helper_methods[method_name]).each { |helper_rel| enqueue(helper_rel) }
767
+ end
768
+ end
769
+ end
770
+
771
+ def record_model_metadata(rel, visitor)
772
+ model_name = const_from_rel(rel, "app/models/")
773
+ sync_scope =
774
+ if visitor.sync_scope_column || visitor.sync_scope_policy
775
+ { "column" => visitor.sync_scope_column, "policy" => visitor.sync_scope_policy }
776
+ end
777
+
778
+ @model_metadata[model_name] = {
779
+ "name" => model_name,
780
+ "explicit_table_name" => visitor.table_name,
781
+ "table" => nil,
782
+ "file" => rel,
783
+ "superclass" => visitor.superclass,
784
+ "abstract_class" => visitor.abstract_class || model_name == "ApplicationRecord",
785
+ "includes" => visitor.includes,
786
+ "active_record" => false,
787
+ "syncable" => visitor.syncable,
788
+ "sync_window" => visitor.sync_window,
789
+ "sync_scope" => sync_scope,
790
+ "sync_file" => visitor.sync_file
791
+ }
792
+ end
793
+
794
+ # Post-BFS inheritance resolution: handles multi-level STI, abstract base
795
+ # models, and Syncable inherited via superclass or concern.
796
+ def resolve_model_inheritance!
797
+ @model_metadata.each do |name, meta|
798
+ chain = superclass_chain(name)
799
+ is_ar = meta["syncable"] ||
800
+ chain.any? { |sup| sup == "ApplicationRecord" || sup == "ActiveRecord::Base" }
801
+ meta["active_record"] = is_ar
802
+
803
+ # Propagate Syncable from included concerns or concrete/abstract ancestors.
804
+ unless meta["syncable"]
805
+ if meta["includes"].any? { |inc| @concern_syncable.include?(inc) } ||
806
+ chain.any? { |sup| @model_metadata.dig(sup, "syncable") }
807
+ meta["syncable"] = true
808
+ end
809
+ end
810
+
811
+ # Resolve table name: abstract models own no table; STI children share
812
+ # their highest concrete ActiveRecord ancestor's table.
813
+ next unless is_ar && !meta["abstract_class"]
814
+
815
+ meta["table"] =
816
+ if meta["explicit_table_name"]
817
+ meta["explicit_table_name"]
818
+ else
819
+ concrete_ancestors = chain.select do |sup|
820
+ sup_meta = @model_metadata[sup]
821
+ sup_meta && !sup_meta["abstract_class"]
822
+ end
823
+ base = concrete_ancestors.last
824
+ if base
825
+ @model_metadata[base]["explicit_table_name"] || ActiveSupport::Inflector.tableize(base)
826
+ else
827
+ ActiveSupport::Inflector.tableize(name)
828
+ end
829
+ end
830
+ end
831
+ end
832
+
833
+ def superclass_chain(model_name)
834
+ chain = []
835
+ seen = Set.new([model_name])
836
+ cur = @model_metadata.dig(model_name, "superclass")
837
+ while cur && !seen.include?(cur)
838
+ seen << cur
839
+ chain << cur
840
+ cur = @model_metadata.dig(cur, "superclass")
841
+ end
842
+ chain
843
+ end
844
+
845
+ # Warn if a staged concrete model has STI subclasses in app/models/ that weren't staged.
846
+ def check_sti_subclasses!
847
+ return unless @route_analysis.has_local_first
848
+
849
+ concrete_staged = @model_metadata.each_with_object(Set.new) do |(name, meta), set|
850
+ set << name unless meta["abstract_class"]
851
+ end
852
+ return if concrete_staged.empty?
853
+
854
+ unstaged_models = @model_files.reject { |rel| @staged_models.include?(rel) || rel.start_with?("app/models/concerns/") }
855
+ return if unstaged_models.empty?
856
+
857
+ subclasses_by_parent = Hash.new { |h, k| h[k] = [] }
858
+ unstaged_models.each do |rel|
859
+ parsed = Prism.parse_file(File.join(@source_root, rel))
860
+ next unless parsed.success?
861
+
862
+ visitor = FileVisitor.new(rel_path: rel)
863
+ parsed.value.accept(visitor)
864
+ if visitor.superclass && concrete_staged.include?(visitor.superclass)
865
+ subclasses_by_parent[visitor.superclass] << const_from_rel(rel, "app/models/")
866
+ end
867
+ end
868
+
869
+ subclasses_by_parent.each do |parent, kids|
870
+ kids.sort!
871
+ @diagnostics << {
872
+ "level" => "warning",
873
+ "kind" => "sti_subclass",
874
+ "file" => @model_metadata.dig(parent, "file"),
875
+ "line" => 1,
876
+ "message" => "Model #{parent} has unstaged subclass(es) #{kids.join(', ')}. " \
877
+ "If using STI, add include: { models: #{kids.inspect} }."
878
+ }
879
+ end
880
+ end
881
+
882
+ def filter_migrations
883
+ dirs = Array(@migration_paths || [File.join(@source_root, "db/migrate")])
884
+ all_files = dirs.flat_map do |dir|
885
+ next [] unless File.directory?(dir)
886
+
887
+ Dir.glob("[0-9]*_*.rb", base: dir).map { |name| File.join(dir, name) }
888
+ end.uniq.sort_by { |file| File.basename(file).to_i }
889
+
890
+ unless @route_analysis.has_local_first
891
+ return [all_files, all_files.map { |f| manifest_migration_label(f) }]
892
+ end
893
+
894
+ reachable_tables = FRAMEWORK_TABLES.to_set
895
+ @model_metadata.each_value do |meta|
896
+ reachable_tables << meta["table"] if meta["table"]
897
+ end
898
+
899
+ explicit = @overrides[:include]["migrations"]
900
+ matched_explicit = Set.new
901
+
902
+ kept = all_files.select do |file|
903
+ basename = File.basename(file)
904
+ version = basename.to_i.to_s
905
+ rel = manifest_migration_label(file)
906
+
907
+ hit = explicit.find { |item| item == version || item == basename || item == rel || basename.start_with?("#{item}_") }
908
+ if hit
909
+ matched_explicit << hit
910
+ next true
911
+ end
912
+
913
+ tables = migration_tables(file)
914
+ tables.any? { |tbl| reachable_tables.include?(tbl) }
915
+ end
916
+
917
+ (explicit - matched_explicit.to_a).each do |missing|
918
+ @errors << "Explicit include.migrations entry #{missing.inspect} did not match any migration file."
919
+ end
920
+
921
+ [kept, kept.map { |f| manifest_migration_label(f) }]
922
+ end
923
+
924
+ def migration_tables(file)
925
+ parsed = Prism.parse_file(file)
926
+ return [] unless parsed.success?
927
+
928
+ tables = Set.new
929
+ queue = [parsed.value]
930
+ while (node = queue.shift)
931
+ if node.is_a?(Prism::CallNode) && node.receiver.nil?
932
+ if DDL_TABLE_CALLS.include?(node.name)
933
+ first = Array(node.arguments&.arguments).first
934
+ tables << first.unescaped if first.is_a?(Prism::SymbolNode) || first.is_a?(Prism::StringNode)
935
+ if node.name == :rename_table
936
+ second = Array(node.arguments&.arguments)[1]
937
+ tables << second.unescaped if second.is_a?(Prism::SymbolNode) || second.is_a?(Prism::StringNode)
938
+ end
939
+ elsif node.name == :execute
940
+ first = Array(node.arguments&.arguments).first
941
+ if first.is_a?(Prism::StringNode)
942
+ first.unescaped.scan(/\b(?:FROM|INTO|UPDATE|TABLE|ON)\s+["`]?([a-z_][a-z0-9_]*)["`]?/i).each do |match|
943
+ tables << match.first
944
+ end
945
+ end
946
+ end
947
+ end
948
+ queue.concat(node.compact_child_nodes)
949
+ end
950
+ tables.to_a
951
+ end
952
+
953
+ # --- Constant & path resolution helpers ---
954
+
955
+ # Check full constant path in both stageable and unstaged indexes before
956
+ # progressively shortening segments, so a parent namespace like `Slack`
957
+ # never shadows `Slack::FakeReplyJob` in app/jobs/.
958
+ def resolve_constant_with_precedence(ref)
959
+ segments = ref[:segments]
960
+ segments.length.downto(1) do |len|
961
+ slice = segments[0, len]
962
+ candidates = candidate_constant_names(slice, ref[:namespace], ref[:top_level])
963
+ candidates.each do |name|
964
+ return [:stageable, @stageable_constants[name]] if @stageable_constants.key?(name)
965
+ return [:unstaged, @unstaged_constants[name]] if @unstaged_constants.key?(name)
966
+ end
967
+ end
968
+ [nil, nil]
969
+ end
970
+
971
+ def lookup_constant(table, ref)
972
+ segments = ref[:segments]
973
+ segments.length.downto(1) do |len|
974
+ slice = segments[0, len]
975
+ candidate_constant_names(slice, ref[:namespace], ref[:top_level]).each do |name|
976
+ return table[name] if table.key?(name)
977
+ end
978
+ end
979
+ nil
980
+ end
981
+
982
+ def candidate_constant_names(segments, namespace, top_level)
983
+ joined = segments.join("::")
984
+ return [joined] if top_level || namespace.empty?
985
+
986
+ list = []
987
+ namespace.length.downto(1) do |depth|
988
+ list << (namespace[0, depth] + segments).join("::")
989
+ end
990
+ list << joined
991
+ list.uniq
992
+ end
993
+
994
+ def resolve_render_target(target, current_dir, partial:)
995
+ cleaned = target.to_s.delete_prefix("/")
996
+ if cleaned.include?("/")
997
+ parts = cleaned.split("/")
998
+ leaf = parts.pop
999
+ dir = parts.join("/")
1000
+ find_view_files(dir, leaf, partial: partial)
1001
+ else
1002
+ find_view_files(current_dir, cleaned, partial: partial)
1003
+ end
1004
+ end
1005
+
1006
+ def find_view_files(dir, name, partial:)
1007
+ prefix = dir.to_s.empty? ? "app/views" : "app/views/#{dir}"
1008
+ stem = partial ? "_#{name.delete_prefix('_')}" : name
1009
+ exact_prefix = "#{prefix}/#{stem}."
1010
+ exact_path = "#{prefix}/#{stem}"
1011
+
1012
+ @view_files.select { |rel| rel == exact_path || rel.start_with?(exact_prefix) }
1013
+ end
1014
+
1015
+ def view_dir_for(rel, is_view:)
1016
+ if is_view
1017
+ dir = File.dirname(rel).delete_prefix("app/views").delete_prefix("/")
1018
+ dir == "." ? "" : dir
1019
+ elsif rel.start_with?("app/controllers/")
1020
+ rel.delete_prefix("app/controllers/").delete_suffix("_controller.rb")
1021
+ else
1022
+ ""
1023
+ end
1024
+ end
1025
+
1026
+ def resolve_model_override(entry)
1027
+ rel = sanitize_relative_path(entry)
1028
+ return rel if rel&.start_with?("app/models/") && safe_source_file?(rel)
1029
+
1030
+ candidate = @stageable_constants[entry]
1031
+ return candidate if candidate&.start_with?("app/models/")
1032
+
1033
+ underscored = sanitize_relative_path("app/models/#{ActiveSupport::Inflector.underscore(entry)}.rb")
1034
+ underscored && safe_source_file?(underscored) ? underscored : nil
1035
+ end
1036
+
1037
+ def resolve_controller_override(entry)
1038
+ rel = sanitize_relative_path(entry)
1039
+ return rel if rel&.start_with?("app/controllers/") && safe_source_file?(rel)
1040
+
1041
+ candidate = @stageable_constants[entry]
1042
+ return candidate if candidate&.start_with?("app/controllers/")
1043
+
1044
+ normalized = entry.end_with?("_controller") ? entry : "#{ActiveSupport::Inflector.underscore(entry)}_controller"
1045
+ candidate_rel = sanitize_relative_path("app/controllers/#{normalized}.rb")
1046
+ candidate_rel && safe_source_file?(candidate_rel) ? candidate_rel : nil
1047
+ end
1048
+
1049
+ def resolve_helper_override(entry)
1050
+ rel = sanitize_relative_path(entry)
1051
+ return rel if rel&.start_with?("app/helpers/") && safe_source_file?(rel)
1052
+
1053
+ candidate = @stageable_constants[entry]
1054
+ return candidate if candidate&.start_with?("app/helpers/")
1055
+
1056
+ underscored = ActiveSupport::Inflector.underscore(entry)
1057
+ underscored = "#{underscored}_helper" unless underscored.end_with?("_helper")
1058
+ candidate_rel = sanitize_relative_path("app/helpers/#{underscored}.rb")
1059
+ candidate_rel && safe_source_file?(candidate_rel) ? candidate_rel : nil
1060
+ end
1061
+
1062
+ def resolve_view_override(entry, partial:)
1063
+ rel = sanitize_relative_path(entry)
1064
+ return [rel] if rel&.start_with?("app/views/") && safe_source_file?(rel)
1065
+
1066
+ cleaned = entry.delete_prefix("/")
1067
+ return [] if cleaned.include?("..")
1068
+
1069
+ if cleaned.include?("/")
1070
+ parts = cleaned.split("/")
1071
+ leaf = parts.pop
1072
+ find_view_files(parts.join("/"), leaf, partial: partial)
1073
+ else
1074
+ find_view_files("", cleaned, partial: partial)
1075
+ end
1076
+ end
1077
+
1078
+ def sanitize_relative_path(entry)
1079
+ raw = entry.to_s.delete_prefix("/")
1080
+ return nil if raw.empty?
1081
+
1082
+ expanded = File.expand_path(raw, @source_root)
1083
+ return nil unless expanded.start_with?("#{@source_root}#{File::SEPARATOR}")
1084
+
1085
+ expanded.delete_prefix("#{@source_root}#{File::SEPARATOR}")
1086
+ end
1087
+
1088
+ def safe_source_file?(rel)
1089
+ expanded = File.expand_path(rel, @source_root)
1090
+ return false unless expanded.start_with?("#{@source_root}#{File::SEPARATOR}")
1091
+ return false unless File.file?(expanded)
1092
+
1093
+ File.realpath(expanded).start_with?("#{File.realpath(@source_root)}#{File::SEPARATOR}")
1094
+ end
1095
+
1096
+ def categorize(rel)
1097
+ if rel.start_with?("app/controllers/")
1098
+ @staged_controllers << rel
1099
+ elsif rel.start_with?("app/models/")
1100
+ @staged_models << rel
1101
+ elsif rel.start_with?("app/views/")
1102
+ @staged_views << rel
1103
+ elsif rel.start_with?("app/helpers/")
1104
+ @staged_helpers << rel
1105
+ elsif rel.start_with?("app/screens/")
1106
+ @staged_screens << rel
1107
+ end
1108
+ end
1109
+
1110
+ def enqueue(rel)
1111
+ @queue << rel unless @visited.include?(rel)
1112
+ end
1113
+
1114
+ def enqueue_if_exists(rel)
1115
+ enqueue(rel) if safe_source_file?(rel)
1116
+ end
1117
+
1118
+ def glob_rel(pattern)
1119
+ Dir.glob(pattern, base: @source_root).sort
1120
+ end
1121
+
1122
+ def const_from_rel(rel, prefix)
1123
+ rel.delete_prefix(prefix).delete_suffix(".rb").split("/").map { |part| ActiveSupport::Inflector.camelize(part) }.join("::")
1124
+ end
1125
+
1126
+ def register_const_path(map, const_name, rel)
1127
+ map[const_name] ||= rel
1128
+ end
1129
+
1130
+ # Extract top-level public helper method definitions, skipping server_only
1131
+ # blocks and methods defined after `private` / `protected`.
1132
+ def extract_public_helper_defs(node)
1133
+ names = []
1134
+ collect_public_defs(node, names)
1135
+ names
1136
+ end
1137
+
1138
+ def collect_public_defs(node, names)
1139
+ return unless node
1140
+
1141
+ case node
1142
+ when Prism::ProgramNode
1143
+ collect_public_defs(node.statements, names)
1144
+ when Prism::ModuleNode
1145
+ collect_public_defs(node.body, names)
1146
+ when Prism::StatementsNode
1147
+ visibility = :public
1148
+ node.body.each do |stmt|
1149
+ if stmt.is_a?(Prism::CallNode) && stmt.receiver.nil?
1150
+ if stmt.name == :server_only && stmt.block
1151
+ next
1152
+ elsif %i[private protected].include?(stmt.name) && stmt.arguments.nil?
1153
+ visibility = stmt.name
1154
+ next
1155
+ elsif stmt.name == :public && stmt.arguments.nil?
1156
+ visibility = :public
1157
+ next
1158
+ elsif %i[browser_only client_only].include?(stmt.name) && stmt.block
1159
+ collect_public_defs(stmt.block.body, names) if visibility == :public
1160
+ next
1161
+ end
1162
+ end
1163
+ if stmt.is_a?(Prism::DefNode) && stmt.receiver.nil? && visibility == :public
1164
+ names << stmt.name.to_s
1165
+ elsif stmt.is_a?(Prism::ModuleNode)
1166
+ collect_public_defs(stmt, names)
1167
+ end
1168
+ end
1169
+ end
1170
+ end
1171
+
1172
+ # Never leak host build-machine paths into public instant_record.manifest.json.
1173
+ def manifest_migration_label(file)
1174
+ prefix = "#{@source_root}#{File::SEPARATOR}"
1175
+ if file.start_with?(prefix)
1176
+ file.delete_prefix(prefix)
1177
+ else
1178
+ "db/migrate/#{File.basename(file)}"
1179
+ end
1180
+ end
1181
+
1182
+ def format_errors(errors)
1183
+ header = "Local-first island reachability check failed (#{errors.size} #{errors.size == 1 ? 'error' : 'errors'}):"
1184
+ ([header] + errors.map { |err| " - #{err}" }).join("\n")
1185
+ end
1186
+ end
1187
+ end
1188
+ end