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,338 @@
1
+ // Deterministic `.irtrace` flight-recorder replayer in Node AppHost.
2
+ // Invoked directly via `node compiled/web/src/replay.js <trace.irtrace> --wasm <app.wasm>`
3
+ // or via `bin/rails instant_record:replay <trace.irtrace>`.
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { createRequire } from "node:module";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { createAppHostClass } from "./app-host-core.js";
9
+ import { TRACE_FORMAT, TRACE_VERSION } from "./flight-recorder.js";
10
+ import { base64ToBytes, sha256Hex } from "./sha256.js";
11
+ import * as minimalWasi from "./wasi-minimal.js";
12
+
13
+ const encoder = new TextEncoder();
14
+
15
+ export async function loadWasiShim(extraNodeModules = []) {
16
+ const candidates = [];
17
+ for (const dir of extraNodeModules) {
18
+ if (dir) candidates.push(resolve(dir));
19
+ }
20
+ if (process.env.INSTANT_RECORD_WEB_NODE_MODULES) {
21
+ candidates.push(resolve(process.env.INSTANT_RECORD_WEB_NODE_MODULES));
22
+ }
23
+ const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
24
+ candidates.push(join(webRoot, "node_modules"));
25
+
26
+ for (const dir of candidates) {
27
+ const pkgDir = join(dir, "@bjorn3", "browser_wasi_shim");
28
+ const pkgJsonPath = join(pkgDir, "package.json");
29
+ if (!existsSync(pkgJsonPath)) continue;
30
+ try {
31
+ const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
32
+ const entry =
33
+ pkg.exports?.["."]?.import ||
34
+ pkg.exports?.["."]?.default ||
35
+ pkg.module ||
36
+ pkg.main ||
37
+ "dist/index.js";
38
+ const loaded = await import(pathToFileURL(join(pkgDir, entry)).href);
39
+ if (loaded?.WASI) return { shim: loaded, source: pkgDir };
40
+ } catch {
41
+ try {
42
+ const req = createRequire(join(dir, "_noop.js"));
43
+ const loaded = req("@bjorn3/browser_wasi_shim");
44
+ if (loaded?.WASI) return { shim: loaded, source: pkgDir };
45
+ } catch {
46
+ // Fall through to next candidate.
47
+ }
48
+ }
49
+ }
50
+ return { shim: minimalWasi, source: "wasi-minimal" };
51
+ }
52
+
53
+ export function decodeStepInput(input) {
54
+ if (!input) return new Uint8Array();
55
+ if (input instanceof Uint8Array) return input;
56
+ if (typeof input === "string") return encoder.encode(input);
57
+ if (input.encoding === "base64") return base64ToBytes(input.data || "");
58
+ return encoder.encode(input.data || "");
59
+ }
60
+
61
+ export function validateTrace(trace) {
62
+ if (!trace || typeof trace !== "object") throw new Error("Trace file must be a JSON object");
63
+ if (trace.format !== TRACE_FORMAT) {
64
+ throw new Error(`Unsupported trace format ${JSON.stringify(trace.format)} (expected ${JSON.stringify(TRACE_FORMAT)})`);
65
+ }
66
+ if (trace.version !== TRACE_VERSION) {
67
+ throw new Error(`Unsupported trace version ${trace.version} (expected ${TRACE_VERSION})`);
68
+ }
69
+ if (!Array.isArray(trace.steps)) {
70
+ throw new Error("Trace is missing a steps array");
71
+ }
72
+ return trace;
73
+ }
74
+
75
+ export async function replayTrace(
76
+ trace,
77
+ {
78
+ wasmModule = null,
79
+ wasmBytes = null,
80
+ wasmPath = null,
81
+ dbBytes = null,
82
+ allowDigestMismatch = false,
83
+ stopOnFault = false,
84
+ maxSteps = null,
85
+ nodeModules = [],
86
+ wasiShim = null,
87
+ } = {},
88
+ ) {
89
+ validateTrace(trace);
90
+
91
+ let module = wasmModule;
92
+ if (!module) {
93
+ const raw = wasmBytes || (wasmPath ? new Uint8Array(readFileSync(wasmPath)) : null);
94
+ if (!raw) throw new Error("Replay requires a WASM module (pass --wasm <path> or WASM=<path>)");
95
+ module = new WebAssembly.Module(raw);
96
+ }
97
+
98
+ const resolvedWasi = wasiShim ? { shim: wasiShim, source: "injected" } : await loadWasiShim(nodeModules);
99
+ const AppHost = createAppHostClass(resolvedWasi.shim);
100
+
101
+ const checkpoint = trace.checkpoint || { mode: "empty" };
102
+ let initialDb = null;
103
+ if (dbBytes) {
104
+ initialDb = dbBytes instanceof Uint8Array ? dbBytes : new Uint8Array(dbBytes);
105
+ } else if (checkpoint.mode === "sqlite3" && checkpoint.data) {
106
+ initialDb = base64ToBytes(checkpoint.data);
107
+ } else if (checkpoint.mode === "digest") {
108
+ throw new Error(
109
+ `Trace checkpoint is digest-only (${checkpoint.omittedReason || "no embedded DB"}); supply matching SQLite file with --db <path> (expected sha256:${checkpoint.digest})`,
110
+ );
111
+ }
112
+
113
+ let actualDbDigest = null;
114
+ if (initialDb) {
115
+ actualDbDigest = sha256Hex(initialDb);
116
+ if (checkpoint.digest && actualDbDigest !== checkpoint.digest && !allowDigestMismatch) {
117
+ throw new Error(
118
+ `Base DB digest mismatch: expected ${checkpoint.digest}, got ${actualDbDigest} (pass --allow-digest-mismatch to override)`,
119
+ );
120
+ }
121
+ }
122
+
123
+ let activeExchanges = [];
124
+ let exchangeIndex = 0;
125
+ let exchangeMismatchError = null;
126
+
127
+ const replayExchange = (method, url, requestBody) => {
128
+ if (exchangeIndex >= activeExchanges.length) {
129
+ exchangeMismatchError = new Error(
130
+ `Unexpected network exchange during replay: ${method} ${url} (recorded ${activeExchanges.length} exchange(s) for this step)`,
131
+ );
132
+ throw exchangeMismatchError;
133
+ }
134
+ const recorded = activeExchanges[exchangeIndex++];
135
+ if (recorded.method && recorded.method !== method) {
136
+ exchangeMismatchError = new Error(
137
+ `Exchange method mismatch at index ${exchangeIndex - 1}: expected ${recorded.method}, got ${method}`,
138
+ );
139
+ throw exchangeMismatchError;
140
+ }
141
+ if (recorded.url && recorded.url !== url) {
142
+ exchangeMismatchError = new Error(
143
+ `Exchange URL mismatch at index ${exchangeIndex - 1}: expected ${recorded.url}, got ${url}`,
144
+ );
145
+ throw exchangeMismatchError;
146
+ }
147
+ return {
148
+ status: recorded.status ?? 0,
149
+ body: recorded.responseBody ?? "",
150
+ requestBody,
151
+ };
152
+ };
153
+
154
+ const host = new AppHost(module, {
155
+ env: checkpoint.env || {},
156
+ exchange: replayExchange,
157
+ });
158
+
159
+ if (checkpoint.cookies && typeof checkpoint.cookies === "object") {
160
+ for (const [k, v] of Object.entries(checkpoint.cookies)) host.cookies.set(k, v);
161
+ }
162
+ if (initialDb) {
163
+ host.restoreDatabase(initialDb, checkpoint.schemaVersion || 0);
164
+ }
165
+
166
+ let bootFault = null;
167
+ try {
168
+ host.ensureBooted();
169
+ } catch (error) {
170
+ bootFault = error.fault || { kind: "wasm_trap", exportName: "wasm_boot", message: error.message, errors: error.errors || [] };
171
+ return {
172
+ ok: false,
173
+ wasiSource: resolvedWasi.source,
174
+ checkpointDigest: actualDbDigest,
175
+ bootFault,
176
+ reproducedFault: true,
177
+ mismatches: 0,
178
+ steps: [],
179
+ };
180
+ }
181
+
182
+ const stepsToRun = maxSteps != null ? trace.steps.slice(0, Number(maxSteps)) : trace.steps;
183
+ const results = [];
184
+ let mismatches = 0;
185
+ let reproducedFault = false;
186
+
187
+ for (const step of stepsToRun) {
188
+ activeExchanges = Array.isArray(step.exchanges) ? step.exchanges : [];
189
+ exchangeIndex = 0;
190
+ exchangeMismatchError = null;
191
+
192
+ const inputBytes = decodeStepInput(step.input);
193
+ const actual = host.call(step.exportName, inputBytes);
194
+ const actualOutDigest = actual.out ? sha256Hex(actual.out) : null;
195
+ const expected = step.outcome || {};
196
+
197
+ const exitMatches = expected.exit === undefined ? true : actual.exit === expected.exit;
198
+ const trappedMatches = expected.trapped === undefined ? true : actual.trapped === expected.trapped;
199
+ const outDigestMatches = !expected.outDigest ? true : actualOutDigest === expected.outDigest;
200
+ const exchangesConsumed = !exchangeMismatchError && exchangeIndex === activeExchanges.length;
201
+ const matched = exitMatches && trappedMatches && outDigestMatches && exchangesConsumed;
202
+
203
+ if (!matched) mismatches += 1;
204
+ if (actual.fault && expected.fault) reproducedFault = true;
205
+
206
+ results.push({
207
+ seq: step.seq,
208
+ exportName: step.exportName,
209
+ matched,
210
+ exitMatches,
211
+ trappedMatches,
212
+ outDigestMatches,
213
+ exchangesConsumed,
214
+ exchangeError: exchangeMismatchError ? exchangeMismatchError.message : null,
215
+ expected: {
216
+ exit: expected.exit,
217
+ trapped: !!expected.trapped,
218
+ errors: expected.errors || [],
219
+ outDigest: expected.outDigest || null,
220
+ events: expected.events || [],
221
+ },
222
+ actual: {
223
+ exit: actual.exit,
224
+ trapped: !!actual.trapped,
225
+ errors: actual.errors || [],
226
+ outDigest: actualOutDigest,
227
+ events: actual.events || [],
228
+ fault: actual.fault || null,
229
+ },
230
+ });
231
+
232
+ if (host.poisoned || (stopOnFault && actual.fault)) break;
233
+ }
234
+
235
+ return {
236
+ ok: mismatches === 0,
237
+ wasiSource: resolvedWasi.source,
238
+ checkpointDigest: actualDbDigest,
239
+ bootFault: null,
240
+ reproducedFault,
241
+ mismatches,
242
+ totalSteps: stepsToRun.length,
243
+ executedSteps: results.length,
244
+ steps: results,
245
+ };
246
+ }
247
+
248
+ export function formatReplayReport(report) {
249
+ const lines = [];
250
+ lines.push(`InstantRecord deterministic replay (${report.wasiSource})`);
251
+ if (report.checkpointDigest) lines.push(` checkpoint sha256: ${report.checkpointDigest}`);
252
+ if (report.bootFault) {
253
+ lines.push(` [BOOT FAULT] ${report.bootFault.message}`);
254
+ for (const err of report.bootFault.errors || []) lines.push(` stderr: ${err}`);
255
+ return lines.join("\n");
256
+ }
257
+ for (const step of report.steps) {
258
+ const tag = step.actual.fault
259
+ ? (step.matched ? "FAULT REPRODUCED" : "FAULT")
260
+ : (step.matched ? "OK" : "DIVERGED");
261
+ lines.push(
262
+ ` #${step.seq} ${step.exportName} -> exit=${JSON.stringify(step.actual.exit)} (expected ${JSON.stringify(step.expected.exit)}) [${tag}]`,
263
+ );
264
+ for (const err of step.actual.errors) lines.push(` stderr: ${err}`);
265
+ for (const ev of step.actual.events) {
266
+ lines.push(` event: ${ev.name} ${JSON.stringify(ev.payload || {})}`);
267
+ }
268
+ if (!step.matched) {
269
+ if (!step.outDigestMatches) {
270
+ lines.push(` outDigest mismatch: actual=${step.actual.outDigest} expected=${step.expected.outDigest}`);
271
+ }
272
+ if (!step.exchangesConsumed) {
273
+ lines.push(` unconsumed exchanges in step #${step.seq}`);
274
+ }
275
+ }
276
+ }
277
+ lines.push(
278
+ `Summary: ${report.executedSteps}/${report.totalSteps} step(s) replayed, ${report.mismatches} divergence(s)` +
279
+ (report.reproducedFault ? ", recorded fault reproduced" : ""),
280
+ );
281
+ return lines.join("\n");
282
+ }
283
+
284
+ function parseCliArgs(argv) {
285
+ const opts = {
286
+ tracePath: null,
287
+ wasmPath: null,
288
+ dbPath: null,
289
+ nodeModules: [],
290
+ json: false,
291
+ allowDigestMismatch: false,
292
+ stopOnFault: false,
293
+ maxSteps: null,
294
+ };
295
+ for (let i = 0; i < argv.length; i++) {
296
+ const arg = argv[i];
297
+ if (arg === "--wasm" && argv[i + 1]) opts.wasmPath = argv[++i];
298
+ else if (arg === "--db" && argv[i + 1]) opts.dbPath = argv[++i];
299
+ else if (arg === "--node-modules" && argv[i + 1]) opts.nodeModules.push(argv[++i]);
300
+ else if (arg === "--max-steps" && argv[i + 1]) opts.maxSteps = Number(argv[++i]);
301
+ else if (arg === "--json") opts.json = true;
302
+ else if (arg === "--allow-digest-mismatch") opts.allowDigestMismatch = true;
303
+ else if (arg === "--stop-on-fault") opts.stopOnFault = true;
304
+ else if (!arg.startsWith("-") && !opts.tracePath) opts.tracePath = arg;
305
+ else throw new Error(`Unknown argument: ${arg}`);
306
+ }
307
+ return opts;
308
+ }
309
+
310
+ const isCli = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
311
+ if (isCli) {
312
+ try {
313
+ const opts = parseCliArgs(process.argv.slice(2));
314
+ if (!opts.tracePath) {
315
+ console.error("Usage: node replay.js <file.irtrace> --wasm <app.wasm> [--db <file.sqlite3>] [--json] [--stop-on-fault]");
316
+ process.exit(2);
317
+ }
318
+ const trace = JSON.parse(readFileSync(opts.tracePath, "utf8"));
319
+ const dbBytes = opts.dbPath ? new Uint8Array(readFileSync(opts.dbPath)) : null;
320
+ const report = await replayTrace(trace, {
321
+ wasmPath: opts.wasmPath,
322
+ dbBytes,
323
+ allowDigestMismatch: opts.allowDigestMismatch,
324
+ stopOnFault: opts.stopOnFault,
325
+ maxSteps: opts.maxSteps,
326
+ nodeModules: opts.nodeModules,
327
+ });
328
+ if (opts.json) {
329
+ console.log(JSON.stringify(report, null, 2));
330
+ } else {
331
+ console.log(formatReplayReport(report));
332
+ }
333
+ process.exit(report.ok ? 0 : 1);
334
+ } catch (error) {
335
+ console.error(`Replay error: ${error.message}`);
336
+ process.exit(1);
337
+ }
338
+ }
@@ -0,0 +1,204 @@
1
+ // Outbox-preserving schema drift detection and auto-rehydration for the
2
+ // compiled browser worker. Replaces fatal boot/snapshot errors with:
3
+ // 1. Extract pending instant_record_outbox rows from the drifted SQLite image
4
+ // 2. Boot a clean SQLite database on the target release's schema
5
+ // 3. Re-insert preserved outbox rows atomically
6
+ // 4. Trigger a normal outbox drain + re-bootstrap from the server
7
+
8
+ export function detectSchemaDrift({
9
+ bytes,
10
+ version,
11
+ targetSchema,
12
+ legacySchema,
13
+ history,
14
+ migrationHistory,
15
+ previousDigest,
16
+ schemaDigest,
17
+ }) {
18
+ if (bytes && version == null && !legacySchema) {
19
+ return "unversioned_snapshot";
20
+ }
21
+ const previous = version ?? Number(legacySchema);
22
+ if (bytes && previous > targetSchema) {
23
+ return `schema_version_ahead:${previous}`;
24
+ }
25
+ if (bytes && legacySchema && previous < Number(legacySchema)) {
26
+ return `schema_version_below_baseline:${previous}`;
27
+ }
28
+ if (history) {
29
+ const priorVersions = new Set([...Object.keys(history), ...Object.keys(migrationHistory || {})]);
30
+ for (const key of priorVersions) {
31
+ if (Number(key) <= previous && migrationHistory?.[key] !== history[key]) {
32
+ return `published_migration_changed:${key}`;
33
+ }
34
+ }
35
+ }
36
+ if (version === targetSchema && previousDigest && previousDigest !== schemaDigest) {
37
+ return "schema_digest_mismatch";
38
+ }
39
+ if (bytes && previous < targetSchema && !(targetSchema in (migrationHistory || {}))) {
40
+ return `missing_browser_migration:${targetSchema}`;
41
+ }
42
+ return null;
43
+ }
44
+
45
+ export function rehydrateFromBytes({ bytes, reason, createHost, prepareFresh, onReport }) {
46
+ const started = performance.now();
47
+ let extracted = [];
48
+ let extractFailed = false;
49
+
50
+ if (bytes && bytes.length > 0) {
51
+ try {
52
+ const extractor = createHost();
53
+ extracted = extractor.extractOutbox(bytes);
54
+ } catch {
55
+ extractFailed = true;
56
+ extracted = [];
57
+ }
58
+ }
59
+
60
+ const fresh = createHost();
61
+ prepareFresh?.(fresh);
62
+ const initStart = performance.now();
63
+ fresh.ensureBooted();
64
+ if (extracted.length > 0) {
65
+ fresh.importOutbox(extracted);
66
+ }
67
+ const runtimeMs = performance.now() - initStart;
68
+ const status = extractFailed
69
+ ? "extract_failed; clean rebuild"
70
+ : `${extracted.length} outbox preserved`;
71
+
72
+ onReport?.({
73
+ kind: "schema",
74
+ method: "REHYDRATE",
75
+ path: reason,
76
+ status,
77
+ ms: Math.round(performance.now() - started),
78
+ });
79
+
80
+ return {
81
+ host: fresh,
82
+ restored: false,
83
+ fromShell: false,
84
+ runtimeMs,
85
+ rehydrated: {
86
+ reason,
87
+ preservedOutbox: extracted.length,
88
+ extractFailed,
89
+ },
90
+ };
91
+ }
92
+
93
+ export function openOrRehydrate({
94
+ bytes,
95
+ version,
96
+ targetSchema,
97
+ legacySchema,
98
+ history,
99
+ migrationHistory,
100
+ previousDigest,
101
+ schemaDigest,
102
+ shell,
103
+ createHost,
104
+ onReport,
105
+ }) {
106
+ const drift = detectSchemaDrift({
107
+ bytes,
108
+ version,
109
+ targetSchema,
110
+ legacySchema,
111
+ history,
112
+ migrationHistory,
113
+ previousDigest,
114
+ schemaDigest,
115
+ });
116
+
117
+ if (drift) {
118
+ return rehydrateFromBytes({ bytes, reason: drift, createHost, onReport });
119
+ }
120
+
121
+ const previous = version ?? Number(legacySchema);
122
+ const candidate = createHost();
123
+ const fromShell = !bytes && !!shell;
124
+ if (bytes) candidate.restoreDatabase(bytes, previous);
125
+ if (fromShell) candidate.restoreDatabase(shell.bytes, targetSchema);
126
+
127
+ const initStart = performance.now();
128
+ try {
129
+ candidate.ensureBooted();
130
+ } catch (error) {
131
+ if (bytes) {
132
+ return rehydrateFromBytes({
133
+ bytes,
134
+ reason: "migration_failed",
135
+ createHost,
136
+ onReport,
137
+ });
138
+ }
139
+ throw error;
140
+ }
141
+
142
+ return {
143
+ host: candidate,
144
+ restored: !!bytes,
145
+ fromShell,
146
+ runtimeMs: performance.now() - initStart,
147
+ rehydrated: null,
148
+ };
149
+ }
150
+
151
+ export function reloadOrRehydrateSnapshot({
152
+ bytes,
153
+ savedSchema,
154
+ targetSchema,
155
+ createHost,
156
+ onReleaseRequired,
157
+ onReport,
158
+ }) {
159
+ if (savedSchema !== targetSchema) {
160
+ const peerAhead = savedSchema != null && savedSchema > targetSchema;
161
+ if (peerAhead) onReleaseRequired?.();
162
+ const outcome = rehydrateFromBytes({
163
+ bytes,
164
+ reason: peerAhead
165
+ ? `peer_schema_ahead:${savedSchema}`
166
+ : `snapshot_schema_mismatch:${savedSchema}`,
167
+ createHost,
168
+ onReport,
169
+ });
170
+ return {
171
+ ...outcome,
172
+ persist: !peerAhead,
173
+ needsBootstrap: true,
174
+ };
175
+ }
176
+
177
+ const restored = createHost();
178
+ if (bytes) restored.restoreDatabase(bytes, targetSchema);
179
+ try {
180
+ restored.ensureBooted();
181
+ } catch (error) {
182
+ if (bytes) {
183
+ const outcome = rehydrateFromBytes({
184
+ bytes,
185
+ reason: "snapshot_boot_failed",
186
+ createHost,
187
+ onReport,
188
+ });
189
+ return {
190
+ ...outcome,
191
+ persist: true,
192
+ needsBootstrap: true,
193
+ };
194
+ }
195
+ throw error;
196
+ }
197
+
198
+ return {
199
+ host: restored,
200
+ rehydrated: null,
201
+ persist: false,
202
+ needsBootstrap: false,
203
+ };
204
+ }
@@ -0,0 +1,68 @@
1
+ // Pure routing helpers shared between main.js and worker.js so consumer apps
2
+ // can use custom mount paths, InstantRecord.server_url, and service workers.
3
+
4
+ const trimTrailingSlash = (value) => String(value || "").replace(/\/+$/, "");
5
+
6
+ // Derive the Rails app root from the configured sync endpoint and mount path.
7
+ // Examples:
8
+ // ("/instant_record", "/instant_record") -> ""
9
+ // ("/sync", "/sync") -> ""
10
+ // ("http://localhost:3000/sync", "/sync") -> "http://localhost:3000"
11
+ // ("http://localhost:3000/api/sync", "/sync") -> "http://localhost:3000/api"
12
+ export function serverRoot(publicEndpoint, mountPath = "/instant_record") {
13
+ const endpoint = trimTrailingSlash(publicEndpoint);
14
+ const mount = trimTrailingSlash(mountPath || "/instant_record");
15
+ if (mount && endpoint.endsWith(mount)) {
16
+ return endpoint.slice(0, endpoint.length - mount.length);
17
+ }
18
+ if (/^https?:\/\//i.test(endpoint)) {
19
+ return new URL(endpoint).origin;
20
+ }
21
+ return "";
22
+ }
23
+
24
+ // Validate a page-initiated serverRequest path and strip the network marker.
25
+ // Rejects protocol-relative or cross-origin paths.
26
+ export function resolveServerRequest(path, origin) {
27
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//") || path.includes("\\")) {
28
+ throw new Error("Invalid server request path");
29
+ }
30
+ const baseOrigin = new URL(origin).origin;
31
+ const url = new URL(path, baseOrigin);
32
+ if (url.origin !== baseOrigin || !url.pathname.startsWith("/") || url.pathname.startsWith("//")) {
33
+ throw new Error("Invalid server request path");
34
+ }
35
+ url.searchParams.delete("instant_record_network");
36
+ return url.pathname + url.search;
37
+ }
38
+
39
+ // Decide whether a browser fetch should be answered by the local Wasm app
40
+ // instead of passing through to the network.
41
+ export function isLocalUrl(url, origin, syncEndpoint = "/instant_record") {
42
+ if (url.origin !== origin) return false;
43
+ const pathname = url.pathname;
44
+ if (
45
+ pathname === "/service-worker.js" ||
46
+ pathname === "/instant-record-release.json" ||
47
+ pathname === "/instant_record.manifest.json" ||
48
+ pathname.startsWith("/assets/") ||
49
+ pathname.startsWith("/harness/") ||
50
+ /^\/app[-.\w]*\.wasm$/.test(pathname)
51
+ ) {
52
+ return false;
53
+ }
54
+ if (syncEndpoint) {
55
+ const syncUrl = new URL(syncEndpoint, origin);
56
+ const syncBase = trimTrailingSlash(syncUrl.pathname);
57
+ if (syncUrl.origin === origin && syncBase && (pathname === syncBase || pathname.startsWith(syncBase + "/"))) {
58
+ // Quarantined sync notices live in this browser's local SQLite ledger,
59
+ // so Hotwire form posts and reads under /<mount>/sync_notices stay local.
60
+ const noticesBase = syncBase + "/sync_notices";
61
+ if (pathname === noticesBase || pathname === noticesBase + ".json" || pathname.startsWith(noticesBase + "/")) {
62
+ return true;
63
+ }
64
+ return false;
65
+ }
66
+ }
67
+ return true;
68
+ }