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,606 @@
1
+ require "active_record"
2
+ require "active_record/connection_adapters/sqlite3_adapter"
3
+ require "active_support/inflector"
4
+ require "digest"
5
+ require "fileutils"
6
+ require "json"
7
+ require "set"
8
+ require_relative "../outbox_upcaster"
9
+ require_relative "browser_migrations"
10
+ require_relative "runner"
11
+
12
+ module InstantRecord
13
+ class Compiler
14
+ # Committed schema lockfile (`db/instant_record_lock.json`) and upgrade-ladder
15
+ # CI/doctor replay verifier.
16
+ #
17
+ # Records every published browser migration version's compiled SQLite DDL and
18
+ # cumulative sqlite_master schema snapshot. Verification replays EVERY
19
+ # historical schema version — populated with realistic rows AND pending
20
+ # OutboxMutation rows — through every subsequent transactional migration step
21
+ # up to HEAD, confirming SQLite integrity, outbox survival, final schema
22
+ # parity, and outbox-to-HEAD attribute compatibility (via `upcast_outbox`).
23
+ class SchemaLock
24
+ LOCKFILE_VERSION = 1
25
+ FILENAME = "db/instant_record_lock.json"
26
+
27
+ INTERNAL_TABLES = %w[
28
+ instant_record_outbox
29
+ instant_record_sync_metadata
30
+ instant_record_sync_notices
31
+ instant_record_changes
32
+ instant_record_applied_mutations
33
+ ar_internal_metadata
34
+ schema_migrations
35
+ ].freeze
36
+
37
+ OUTBOX_TABLE_DDL = <<~SQL.strip
38
+ CREATE TABLE IF NOT EXISTS "instant_record_outbox" (
39
+ "id" varchar NOT NULL PRIMARY KEY,
40
+ "record_type" varchar NOT NULL,
41
+ "record_id" varchar NOT NULL,
42
+ "operation" varchar NOT NULL,
43
+ "changes_payload" text,
44
+ "base_version" integer DEFAULT 0 NOT NULL,
45
+ "created_at" datetime(6) NOT NULL,
46
+ "updated_at" datetime(6) NOT NULL
47
+ )
48
+ SQL
49
+
50
+ SYNC_METADATA_TABLE_DDL = <<~SQL.strip
51
+ CREATE TABLE IF NOT EXISTS "instant_record_sync_metadata" (
52
+ "key" varchar NOT NULL PRIMARY KEY,
53
+ "value" varchar,
54
+ "created_at" datetime(6) NOT NULL,
55
+ "updated_at" datetime(6) NOT NULL
56
+ )
57
+ SQL
58
+
59
+ Check = Struct.new(:name, :status, :detail, keyword_init: true) do
60
+ def ok? = status != :error
61
+ end
62
+
63
+ Report = Struct.new(:lock_path, :checks, :replayed_versions, keyword_init: true) do
64
+ def ok? = checks.all?(&:ok?)
65
+
66
+ def errors
67
+ checks.reject(&:ok?).map { |c| "#{c.name}: #{c.detail}" }
68
+ end
69
+
70
+ def to_s
71
+ lines = ["InstantRecord schema lock check — #{lock_path}"]
72
+ checks.each do |check|
73
+ badge = check.ok? ? "OK" : "ERROR"
74
+ lines << format(" [%-8s] %-24s %s", badge, check.name, check.detail)
75
+ end
76
+ lines.join("\n")
77
+ end
78
+ end
79
+
80
+ class << self
81
+ def path(root)
82
+ File.join(root.to_s, FILENAME)
83
+ end
84
+
85
+ def generate(root:, baseline: nil, migration_paths: nil, existing: nil)
86
+ plan = BrowserMigrations.plan(root: root, baseline: baseline, migration_paths: migration_paths)
87
+ validate_immutability!(plan, existing) if existing
88
+
89
+ baseline_int = plan["baseline"]
90
+ baseline_schema_sql = build_baseline_schema_sql(
91
+ root: root,
92
+ baseline: baseline_int,
93
+ migration_paths: migration_paths,
94
+ existing: existing
95
+ )
96
+
97
+ versions = []
98
+ with_sqlite do |conn|
99
+ baseline_schema_sql.each { |sql| execute_sql(conn, sql) }
100
+
101
+ plan.fetch("migrations", {}).sort_by { |v, _| v.to_i }.each do |version_str, statements|
102
+ version_int = version_str.to_i
103
+ apply_version_transactionally!(conn, version_int, statements)
104
+ versions << {
105
+ "version" => version_int,
106
+ "digest" => plan.fetch("history").fetch(version_str),
107
+ "statements" => statements,
108
+ "schema_sql" => snapshot_schema_sql(conn)
109
+ }
110
+ end
111
+ end
112
+
113
+ lock = {
114
+ "lockfile_version" => LOCKFILE_VERSION,
115
+ "schema_version" => plan["version"],
116
+ "baseline" => baseline_int,
117
+ "versions" => versions
118
+ }
119
+ lock["baseline_schema_sql"] = baseline_schema_sql unless baseline_schema_sql.empty?
120
+ lock
121
+ end
122
+
123
+ def write!(root:, baseline: nil, migration_paths: nil, lock_path: nil, force: false)
124
+ target = lock_path || path(root)
125
+ existing = !force && File.file?(target) ? JSON.parse(File.read(target)) : nil
126
+ lock = generate(root: root, baseline: baseline, migration_paths: migration_paths, existing: existing)
127
+ FileUtils.mkdir_p(File.dirname(target))
128
+ File.write(target, JSON.pretty_generate(lock) + "\n")
129
+ lock
130
+ end
131
+
132
+ def verify(root:, baseline: nil, migration_paths: nil, models: nil, lock_path: nil)
133
+ target = lock_path || path(root)
134
+ checks = []
135
+ replayed_versions = []
136
+
137
+ unless File.file?(target)
138
+ checks << Check.new(
139
+ name: "lockfile",
140
+ status: :error,
141
+ detail: "missing #{target} (run `bin/rails instant_record:schema:lock`)"
142
+ )
143
+ return Report.new(lock_path: target, checks: checks, replayed_versions: replayed_versions)
144
+ end
145
+
146
+ lock = parse_lockfile(target)
147
+ unless lock.is_a?(Hash) && lock["lockfile_version"] == LOCKFILE_VERSION && lock["versions"].is_a?(Array)
148
+ checks << Check.new(name: "lockfile", status: :error, detail: "invalid or unsupported lockfile format")
149
+ return Report.new(lock_path: target, checks: checks, replayed_versions: replayed_versions)
150
+ end
151
+ checks << Check.new(name: "lockfile", status: :ok, detail: "v#{lock['lockfile_version']} (#{lock['versions'].size} versions)")
152
+
153
+ begin
154
+ plan = BrowserMigrations.plan(root: root, baseline: baseline, migration_paths: migration_paths)
155
+ rescue BuildError => e
156
+ checks << Check.new(name: "migrations plan", status: :error, detail: e.message)
157
+ return Report.new(lock_path: target, checks: checks, replayed_versions: replayed_versions)
158
+ end
159
+
160
+ if lock["schema_version"] != plan["version"]
161
+ checks << Check.new(
162
+ name: "schema version",
163
+ status: :error,
164
+ detail: "lockfile is at #{lock['schema_version']}, db/schema.rb is at #{plan['version']} (run `bin/rails instant_record:schema:lock`)"
165
+ )
166
+ elsif lock["baseline"] != plan["baseline"]
167
+ checks << Check.new(
168
+ name: "schema baseline",
169
+ status: :error,
170
+ detail: "lockfile baseline #{lock['baseline'].inspect} differs from configured #{plan['baseline'].inspect}"
171
+ )
172
+ else
173
+ checks << Check.new(name: "schema version", status: :ok, detail: plan["version"].to_s)
174
+ end
175
+
176
+ drift_errors = compare_versions(plan, lock)
177
+ if drift_errors.empty?
178
+ checks << Check.new(name: "migration history", status: :ok, detail: "all #{lock['versions'].size} locked versions immutable and current")
179
+ else
180
+ drift_errors.each do |msg|
181
+ checks << Check.new(name: "migration history", status: :error, detail: msg)
182
+ end
183
+ return Report.new(lock_path: target, checks: checks, replayed_versions: replayed_versions)
184
+ end
185
+
186
+ model_index = index_models(models)
187
+ replay_upgrade_ladder!(lock, model_index, checks, replayed_versions)
188
+
189
+ Report.new(lock_path: target, checks: checks, replayed_versions: replayed_versions)
190
+ end
191
+
192
+ private
193
+
194
+ def parse_lockfile(path)
195
+ JSON.parse(File.read(path))
196
+ rescue JSON::ParserError
197
+ nil
198
+ end
199
+
200
+ def validate_immutability!(plan, existing)
201
+ baseline_int = plan["baseline"]
202
+ current_migrations = plan.fetch("migrations", {})
203
+ current_history = plan.fetch("history", {})
204
+
205
+ Array(existing["versions"]).each do |entry|
206
+ version_str = entry["version"].to_i.to_s
207
+ next if baseline_int && entry["version"].to_i <= baseline_int
208
+
209
+ unless current_migrations.key?(version_str)
210
+ raise BuildError, "Published browser migration #{version_str} was removed from #{FILENAME}. Add a new migration instead."
211
+ end
212
+
213
+ if current_history[version_str] != entry["digest"] || current_migrations[version_str] != entry["statements"]
214
+ raise BuildError, "Published browser migration #{version_str} changed from #{FILENAME}. Add a new migration instead."
215
+ end
216
+ end
217
+ end
218
+
219
+ def compare_versions(plan, lock)
220
+ errors = []
221
+ baseline_int = plan["baseline"]
222
+ current_migrations = plan.fetch("migrations", {})
223
+ current_history = plan.fetch("history", {})
224
+ locked_by_version = lock["versions"].each_with_object({}) { |entry, map| map[entry["version"].to_i.to_s] = entry }
225
+
226
+ locked_by_version.each do |version_str, entry|
227
+ next if baseline_int && version_str.to_i <= baseline_int
228
+
229
+ unless current_migrations.key?(version_str)
230
+ errors << "published migration #{version_str} was deleted"
231
+ next
232
+ end
233
+
234
+ expected_digest = Digest::SHA256.hexdigest(JSON.generate(entry["statements"]))
235
+ if entry["digest"] != expected_digest
236
+ errors << "lockfile digest mismatch for migration #{version_str}"
237
+ elsif current_history[version_str] != entry["digest"] || current_migrations[version_str] != entry["statements"]
238
+ errors << "published migration #{version_str} changed; add a new migration instead"
239
+ end
240
+ end
241
+
242
+ current_migrations.each_key do |version_str|
243
+ unless locked_by_version.key?(version_str)
244
+ errors << "migration #{version_str} is not recorded in #{FILENAME} (run `bin/rails instant_record:schema:lock`)"
245
+ end
246
+ end
247
+
248
+ errors
249
+ end
250
+
251
+ def build_baseline_schema_sql(root:, baseline:, migration_paths:, existing:)
252
+ return [] if baseline.nil?
253
+
254
+ if existing && existing["baseline"] == baseline && existing["baseline_schema_sql"].is_a?(Array) && !existing["baseline_schema_sql"].empty?
255
+ return existing["baseline_schema_sql"]
256
+ end
257
+
258
+ # Compile migrations <= baseline from migration_paths if available so
259
+ # post-baseline upgrades can replay against a real baseline schema.
260
+ full_plan = BrowserMigrations.plan(root: root, baseline: nil, migration_paths: migration_paths)
261
+ pre = full_plan.fetch("migrations", {}).select { |v, _| v.to_i <= baseline }
262
+ return [] if pre.empty?
263
+
264
+ with_sqlite do |conn|
265
+ pre.sort_by { |v, _| v.to_i }.each do |v, stmts|
266
+ apply_version_transactionally!(conn, v.to_i, stmts)
267
+ end
268
+ snapshot_schema_sql(conn)
269
+ end
270
+ rescue BuildError
271
+ []
272
+ end
273
+
274
+ def replay_upgrade_ladder!(lock, model_index, checks, replayed_versions)
275
+ versions = lock["versions"].sort_by { |entry| entry["version"].to_i }
276
+ baseline_sql = Array(lock["baseline_schema_sql"])
277
+
278
+ # Reference HEAD schema built cleanly from start -> HEAD.
279
+ head_schema = nil
280
+ begin
281
+ with_sqlite do |conn|
282
+ baseline_sql.each { |sql| execute_sql(conn, sql) }
283
+ versions.each { |entry| apply_version_transactionally!(conn, entry["version"], entry["statements"]) }
284
+ verify_integrity!(conn)
285
+ head_schema = introspect_tables(conn)
286
+ end
287
+ checks << Check.new(
288
+ name: "fresh HEAD schema",
289
+ status: :ok,
290
+ detail: "#{head_schema.size} table(s), PRAGMA integrity_check ok"
291
+ )
292
+ rescue StandardError => e
293
+ checks << Check.new(name: "fresh HEAD schema", status: :error, detail: e.message)
294
+ return
295
+ end
296
+
297
+ return if versions.empty?
298
+
299
+ head_version = lock["schema_version"]
300
+
301
+ # Replay from EVERY historical version V_i (plus baseline if present) up to HEAD.
302
+ starting_points = []
303
+ unless baseline_sql.empty?
304
+ starting_points << { version: lock["baseline"], schema_sql: baseline_sql, next_index: 0 }
305
+ end
306
+ versions.each_with_index do |entry, idx|
307
+ starting_points << { version: entry["version"], schema_sql: Array(entry["schema_sql"]), next_index: idx + 1 }
308
+ end
309
+
310
+ starting_points.each do |start|
311
+ from_version = start[:version]
312
+ remaining = versions[start[:next_index]..] || []
313
+ replayed_versions << from_version
314
+
315
+ begin
316
+ seeded_ids = []
317
+ with_sqlite do |conn|
318
+ start[:schema_sql].each { |sql| execute_sql(conn, sql) }
319
+ ensure_gem_tables!(conn, remaining)
320
+
321
+ seeded = seed_rows_and_outbox!(conn, from_version, model_index)
322
+ seeded_ids = seeded.map { |m| m[:id] }
323
+
324
+ remaining.each do |step|
325
+ apply_version_transactionally!(conn, step["version"], step["statements"])
326
+ end
327
+
328
+ verify_integrity!(conn)
329
+ surviving = table_exists?(conn, "instant_record_outbox") ? read_outbox_rows(conn) : []
330
+ verify_outbox_survival!(from_version, seeded_ids, surviving)
331
+ verify_schema_parity!(from_version, head_schema, introspect_tables(conn))
332
+ verify_outbox_compatibility!(from_version, head_version, surviving, head_schema, model_index)
333
+ end
334
+
335
+ checks << Check.new(
336
+ name: "replay #{from_version}",
337
+ status: :ok,
338
+ detail: "#{remaining.size} step(s) -> #{head_version}, #{seeded_ids.size} pending outbox row(s) preserved & compatible"
339
+ )
340
+ rescue StandardError => e
341
+ checks << Check.new(
342
+ name: "replay #{from_version}",
343
+ status: :error,
344
+ detail: e.message
345
+ )
346
+ end
347
+ end
348
+ end
349
+
350
+ def with_sqlite
351
+ conn = ActiveRecord::ConnectionAdapters::SQLite3Adapter.new({ adapter: "sqlite3", database: ":memory:" })
352
+ yield conn
353
+ ensure
354
+ conn&.disconnect!
355
+ end
356
+
357
+ def execute_sql(conn, sql)
358
+ conn.raw_connection.execute_batch(sql)
359
+ end
360
+
361
+ def apply_version_transactionally!(conn, version, statements)
362
+ return if statements.empty?
363
+
364
+ raw = conn.raw_connection
365
+ raw.execute("BEGIN IMMEDIATE")
366
+ begin
367
+ statements.each { |sql| raw.execute_batch(sql) }
368
+ raw.execute("COMMIT")
369
+ rescue StandardError => e
370
+ begin
371
+ raw.execute("ROLLBACK")
372
+ rescue StandardError
373
+ end
374
+ raise BuildError, "migration #{version} failed inside transaction: #{e.message}"
375
+ end
376
+ end
377
+
378
+ def snapshot_schema_sql(conn)
379
+ conn.select_values(
380
+ "SELECT sql FROM sqlite_master WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%' ORDER BY type DESC, name ASC"
381
+ )
382
+ end
383
+
384
+ def introspect_tables(conn)
385
+ tables = conn.select_values(
386
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name ASC"
387
+ )
388
+ tables.each_with_object({}) do |table, map|
389
+ cols = conn.select_all("PRAGMA table_info(#{conn.quote_table_name(table)})").map { |row| row["name"].to_s }
390
+ map[table] = cols.to_set
391
+ end
392
+ end
393
+
394
+ def table_exists?(conn, name)
395
+ conn.select_value(
396
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = #{conn.quote(name)}"
397
+ ) == 1
398
+ end
399
+
400
+ def remaining_creates_table?(remaining, table_name)
401
+ pattern = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?#{Regexp.escape(table_name)}["`]?\b/i
402
+ remaining.any? { |step| Array(step["statements"]).any? { |sql| pattern.match?(sql) } }
403
+ end
404
+
405
+ def ensure_gem_tables!(conn, remaining)
406
+ if !table_exists?(conn, "instant_record_outbox") && !remaining_creates_table?(remaining, "instant_record_outbox")
407
+ execute_sql(conn, OUTBOX_TABLE_DDL)
408
+ end
409
+ if !table_exists?(conn, "instant_record_sync_metadata") && !remaining_creates_table?(remaining, "instant_record_sync_metadata")
410
+ execute_sql(conn, SYNC_METADATA_TABLE_DDL)
411
+ end
412
+ end
413
+
414
+ def verify_integrity!(conn)
415
+ result = conn.select_values("PRAGMA integrity_check")
416
+ raise "SQLite PRAGMA integrity_check failed: #{result.join(', ')}" unless result == ["ok"]
417
+ end
418
+
419
+ def seed_rows_and_outbox!(conn, version, model_index)
420
+ now = "2026-11-20T00:00:00.000000Z"
421
+ if table_exists?(conn, "instant_record_sync_metadata")
422
+ conn.raw_connection.execute(
423
+ "INSERT OR REPLACE INTO instant_record_sync_metadata (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)",
424
+ ["schema_version", format("%020d", version.to_i), now, now]
425
+ )
426
+ end
427
+
428
+ has_outbox = table_exists?(conn, "instant_record_outbox")
429
+ tables = conn.select_values(
430
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name ASC"
431
+ )
432
+
433
+ seeded_outbox = []
434
+ tables.each_with_index do |table, idx|
435
+ next if INTERNAL_TABLES.include?(table)
436
+
437
+ columns = conn.select_all("PRAGMA table_info(#{conn.quote_table_name(table)})")
438
+ next if columns.empty?
439
+
440
+ row_attrs = build_sample_row(columns, table, idx, now)
441
+ insert_sample_row!(conn, table, row_attrs)
442
+ next unless has_outbox
443
+
444
+ record_type = resolve_record_type(table, model_index)
445
+ record_id = (row_attrs["id"] || "rec-#{version}-#{idx}").to_s
446
+ changes = row_attrs.reject { |k, _| k == "sync_state" }
447
+ mutation_id = "replay-#{version}-#{table}-create"
448
+
449
+ conn.raw_connection.execute(
450
+ "INSERT INTO instant_record_outbox (id, record_type, record_id, operation, changes_payload, base_version, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
451
+ [mutation_id, record_type, record_id, "create", JSON.generate(changes), 0, now, now]
452
+ )
453
+ seeded_outbox << { id: mutation_id, table: table, record_type: record_type }
454
+ end
455
+
456
+ seeded_outbox
457
+ end
458
+
459
+ def build_sample_row(columns, table, idx, now)
460
+ attrs = {}
461
+ columns.each_with_index do |col, col_idx|
462
+ name = col["name"].to_s
463
+ type = col["type"].to_s.downcase
464
+ pk = col["pk"].to_i > 0
465
+ dflt = col["dflt_value"]
466
+
467
+ attrs[name] =
468
+ if name == "id" && !type.include?("int")
469
+ "seed-#{table}-#{idx}"
470
+ elsif pk && type.include?("int")
471
+ idx + 1
472
+ elsif name == "sync_state"
473
+ "pending"
474
+ elsif name == "server_version"
475
+ 0
476
+ elsif name == "created_at" || name == "updated_at" || type.include?("datetime") || type.include?("timestamp")
477
+ now
478
+ elsif type.include?("date")
479
+ "2026-11-20"
480
+ elsif type.include?("bool")
481
+ 0
482
+ elsif type.include?("int")
483
+ dflt ? dflt.to_i : (col_idx + 1)
484
+ elsif type.include?("float") || type.include?("real") || type.include?("dec") || type.include?("num")
485
+ 1.0
486
+ elsif type.include?("blob")
487
+ "seed"
488
+ else
489
+ "seed-#{table}-#{name}-#{idx}"
490
+ end
491
+ end
492
+ attrs
493
+ end
494
+
495
+ def insert_sample_row!(conn, table, row_attrs)
496
+ cols = row_attrs.keys.map { |c| conn.quote_column_name(c) }.join(", ")
497
+ placeholders = Array.new(row_attrs.size, "?").join(", ")
498
+ conn.raw_connection.execute(
499
+ "INSERT INTO #{conn.quote_table_name(table)} (#{cols}) VALUES (#{placeholders})",
500
+ row_attrs.values
501
+ )
502
+ end
503
+
504
+ def read_outbox_rows(conn)
505
+ conn.select_all(
506
+ "SELECT id, record_type, record_id, operation, changes_payload, base_version, created_at, updated_at FROM instant_record_outbox ORDER BY created_at, id"
507
+ ).to_a
508
+ end
509
+
510
+ def verify_outbox_survival!(from_version, seeded_ids, surviving)
511
+ surviving_ids = surviving.map { |row| row["id"].to_s }
512
+ missing = seeded_ids - surviving_ids
513
+ unless missing.empty?
514
+ raise "upgrade from #{from_version} lost #{missing.size} pending OutboxMutation row(s): #{missing.join(', ')}"
515
+ end
516
+
517
+ surviving.each do |row|
518
+ JSON.parse(row["changes_payload"].to_s)
519
+ rescue JSON::ParserError => e
520
+ raise "upgrade from #{from_version} corrupted OutboxMutation #{row['id']} JSON: #{e.message}"
521
+ end
522
+ end
523
+
524
+ def verify_schema_parity!(from_version, head_schema, upgraded_schema)
525
+ head_schema.each do |table, expected_cols|
526
+ actual_cols = upgraded_schema[table]
527
+ unless actual_cols
528
+ raise "upgrade from #{from_version} is missing table #{table.inspect} present at HEAD"
529
+ end
530
+
531
+ missing_cols = expected_cols - actual_cols
532
+ extra_cols = actual_cols - expected_cols
533
+ if missing_cols.any? || extra_cols.any?
534
+ details = []
535
+ details << "missing columns: #{missing_cols.to_a.sort.join(', ')}" if missing_cols.any?
536
+ details << "extra columns: #{extra_cols.to_a.sort.join(', ')}" if extra_cols.any?
537
+ raise "upgrade from #{from_version} drifted on table #{table.inspect} (#{details.join('; ')})"
538
+ end
539
+ end
540
+ end
541
+
542
+ def verify_outbox_compatibility!(from_version, head_version, surviving, head_schema, model_index)
543
+ surviving.each do |row|
544
+ changes = JSON.parse(row["changes_payload"].to_s)
545
+ next unless changes.is_a?(Hash)
546
+
547
+ mutation = {
548
+ id: row["id"],
549
+ record_type: row["record_type"],
550
+ record_id: row["record_id"],
551
+ operation: row["operation"],
552
+ base_version: row["base_version"].to_i,
553
+ schema_version: from_version,
554
+ changes: changes
555
+ }
556
+
557
+ mutation, changes = OutboxUpcaster.apply_global(mutation, changes)
558
+ model = find_model(mutation[:record_type], model_index)
559
+ changes = OutboxUpcaster.apply_for_model(model, changes, mutation) if model
560
+
561
+ table_name =
562
+ if model && model.respond_to?(:table_name) && head_schema.key?(model.table_name)
563
+ model.table_name
564
+ else
565
+ guess = mutation[:record_type].to_s.tableize
566
+ head_schema.key?(guess) ? guess : nil
567
+ end
568
+ next unless table_name
569
+
570
+ head_cols = head_schema.fetch(table_name)
571
+ unknown = changes.keys.map(&:to_s).reject { |k| k == "sync_state" || head_cols.include?(k) }
572
+ next if unknown.empty?
573
+
574
+ raise "pending OutboxMutation from schema #{from_version} for #{mutation[:record_type]} carries column(s) " \
575
+ "#{unknown.join(', ')} missing at HEAD #{head_version}. Add an upcast_outbox transform on #{mutation[:record_type]}."
576
+ end
577
+ end
578
+
579
+ def index_models(models)
580
+ by_name = {}
581
+ by_table = {}
582
+ Array(models).each do |item|
583
+ klass = item.is_a?(String) ? item.safe_constantize : item
584
+ next unless klass.is_a?(Class)
585
+
586
+ by_name[klass.name] = klass if klass.name
587
+ by_table[klass.table_name] = klass if klass.respond_to?(:table_name) && klass.table_name
588
+ end
589
+ { by_name: by_name, by_table: by_table }
590
+ end
591
+
592
+ def resolve_record_type(table, model_index)
593
+ if (klass = model_index[:by_table][table]) && klass.name
594
+ return klass.name
595
+ end
596
+
597
+ ActiveSupport::Inflector.classify(table)
598
+ end
599
+
600
+ def find_model(record_type, model_index)
601
+ model_index[:by_name][record_type.to_s] || InstantRecord.synced_model(record_type)
602
+ end
603
+ end
604
+ end
605
+ end
606
+ end
@@ -0,0 +1,77 @@
1
+ require "cgi"
2
+ require "fileutils"
3
+ require "pathname"
4
+
5
+ module InstantRecord
6
+ class Compiler
7
+ # Build lazy source drawers from the same app copy Roundhouse compiled.
8
+ module SourcePages
9
+ PAGES = {
10
+ "assistant" => ["assistant/turns", "index", %w[assistant_chat assistant_turn]],
11
+ "auth" => ["auth/notes", "index", %w[auth_note auth_person]],
12
+ "home" => ["home", "index", []],
13
+ "email" => ["email/mailboxes", "index", %w[mail_entry mail_directory]],
14
+ "todo" => ["todo/issues", "index", %w[issue]],
15
+ "instant" => ["instant/todos", "index", %w[issue]],
16
+ "slack" => ["slack/channels", "show", %w[channel chat_user message]],
17
+ "migrate" => ["migrate/notes", "index", %w[note release]],
18
+ "console" => ["console/sessions", "index", %w[issue]],
19
+ "receipts" => ["receipts", "index", []]
20
+ }.freeze
21
+
22
+ MARKER = /InstantRecord[.:]|\b(?:server_only|browser_only|client_only|sync_window|sync_state|pending_count|on_discarded_change)\b/
23
+
24
+ module_function
25
+
26
+ def write(app_dir:, dist_dir:, version:, demo_dir:, pipeline_dir:)
27
+ root = Pathname(app_dir)
28
+ demo_root = Pathname(demo_dir)
29
+ dest = Pathname(dist_dir).join("assets", "source", version)
30
+ FileUtils.mkdir_p(dest)
31
+
32
+ PAGES.each do |key, (controller, action, models)|
33
+ files = models.map { |model| ["app/models/#{model}.rb", root.join("app/models/#{model}.rb")] }
34
+ files << ["app/controllers/#{controller}_controller.rb", root.join("app/controllers/#{controller}_controller.rb")]
35
+ files << ["app/views/#{controller}/#{action}.html.erb", root.join("app/views/#{controller}/#{action}.html.erb")]
36
+
37
+ case key
38
+ when "email"
39
+ files << ["app/frontend/pages/Email/Inbox.jsx", demo_root.join("app/frontend/pages/Email/Inbox.jsx")]
40
+ when "assistant"
41
+ %w[
42
+ app/javascript/controllers/assistant_chat_controller.js
43
+ app/views/assistant/turns/_turns.html.erb
44
+ app/javascript/controllers/assistant_local_model.js
45
+ ].each { |part| files << [part, root.join(part)] }
46
+ %w[app/jobs/assistant/reply_job.rb app/models/assistant/reply.rb].each do |server|
47
+ files << [server, demo_root.join(server)]
48
+ end
49
+ when "auth"
50
+ files << ["app/javascript/controllers/auth_controller.js", root.join("app/javascript/controllers/auth_controller.js")]
51
+ %w[app/controllers/auth/sessions_controller.rb config/initializers/instant_record.rb].each do |server|
52
+ files << [server, demo_root.join(server)]
53
+ end
54
+ when "migrate"
55
+ files[1] = ["compiled/pipeline/sqlite_release.rb", Pathname(pipeline_dir).join("sqlite_release.rb")]
56
+ end
57
+
58
+ parts = ['<p class="source-note">Source used by this compiled build. Marked lines use InstantRecord.</p>']
59
+ files.each do |label, path|
60
+ lines = path.read.lines(chomp: true)
61
+ marked = lines.count { |line| MARKER.match?(line) }
62
+ parts << %(<section class="source-file"><header><span class="source-path">#{label}</span>) +
63
+ %(<span class="source-count">#{marked} InstantRecord lines of #{lines.length}</span></header><div class="source-code">)
64
+ lines.each_with_index do |line, idx|
65
+ css = MARKER.match?(line) ? " instant-record" : ""
66
+ parts << %(<div class="source-line#{css}"><span class="source-ln">#{idx + 1}</span>) +
67
+ %(<span class="source-text">#{CGI.escapeHTML(line)}</span></div>)
68
+ end
69
+ parts << "</div></section>"
70
+ end
71
+
72
+ dest.join("#{key}.html").write(parts.join)
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end