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,333 @@
1
+ require "json"
2
+ require "pathname"
3
+ require "rbconfig"
4
+ require "time"
5
+ require_relative "compiler"
6
+ require_relative "testing/authoritative_server"
7
+ require_relative "testing/fault_network"
8
+ require_relative "testing/runtimes/base"
9
+ require_relative "testing/runtimes/cruby_runtime"
10
+ require_relative "testing/runtimes/wasm_runtime"
11
+ require_relative "testing/runtimes/native_runtime"
12
+ require_relative "testing/parity_suite"
13
+ require_relative "testing/chaos_simulator"
14
+
15
+ module InstantRecord
16
+ # CI-ready headless dual-runtime parity and seeded chaos simulation harness.
17
+ # Exercises CRuby (with Postgres or SQLite), compiled app.wasm (Node AppHost),
18
+ # and compiled Native C ABI (Ruby Fiddle) against the same authoritative sync
19
+ # server, strictly asserting empty WASI/native stderr and bit-for-bit convergence.
20
+ module Testing
21
+ INT32_MAX = 2_147_483_647
22
+ INT32_MIN = -2_147_483_648
23
+
24
+ Error = Class.new(StandardError)
25
+ ParityMismatch = Class.new(Error)
26
+ StderrError = Class.new(Error)
27
+ ConvergenceError = Class.new(Error)
28
+
29
+ Artifacts = Struct.new(:wasm_path, :native_lib_path, :toolchain_path, :web_node_modules, keyword_init: true) do
30
+ def wasm_available?
31
+ !wasm_path.nil? && File.file?(wasm_path) && !web_node_modules.nil? && File.directory?(web_node_modules)
32
+ end
33
+
34
+ def native_available?
35
+ !native_lib_path.nil? && File.file?(native_lib_path)
36
+ end
37
+ end
38
+
39
+ class << self
40
+ def gem_root
41
+ Compiler.gem_root
42
+ end
43
+
44
+ def shared_library_name
45
+ Compiler::NativeBuild.shared_library_name
46
+ end
47
+
48
+ # Discover compiled Wasm and Native artifacts (and optionally compile them
49
+ # on demand when build: true and a toolchain file is present).
50
+ def resolve_artifacts(root: nil, wasm_path: nil, native_lib_path: nil, toolchain: nil, build: false)
51
+ search_roots = [root, gem_root].compact.map { |p| Pathname(p).expand_path }.uniq
52
+ toolchain_path = find_toolchain(toolchain, search_roots)
53
+
54
+ if build && toolchain_path
55
+ build_artifacts!(root: root, toolchain_path: toolchain_path)
56
+ end
57
+
58
+ resolved_wasm = find_wasm(wasm_path, search_roots)
59
+ resolved_native = find_native_lib(native_lib_path, search_roots)
60
+ resolved_modules = find_web_node_modules(toolchain_path, search_roots)
61
+
62
+ Artifacts.new(
63
+ wasm_path: resolved_wasm,
64
+ native_lib_path: resolved_native,
65
+ toolchain_path: toolchain_path,
66
+ web_node_modules: resolved_modules
67
+ )
68
+ end
69
+
70
+ def select_runtimes(requested: nil, artifacts:, require_compiled: false)
71
+ wanted =
72
+ if requested.nil? || requested.to_s.strip.empty?
73
+ list = [:cruby]
74
+ list << :wasm if artifacts.wasm_available? || require_compiled
75
+ list << :native if artifacts.native_available? || require_compiled
76
+ list
77
+ else
78
+ Array(requested).flat_map { |r| r.to_s.split(",") }.map { |r| r.strip.downcase.to_sym }.reject(&:empty?).uniq
79
+ end
80
+
81
+ unknown = wanted - %i[cruby wasm native]
82
+ raise ArgumentError, "Unknown runtime(s): #{unknown.join(', ')}. Expected cruby, wasm, or native." unless unknown.empty?
83
+
84
+ if wanted.include?(:wasm) && !artifacts.wasm_available?
85
+ if require_compiled || requested
86
+ raise Error, "Wasm runtime requested but app.wasm or WEB_NODE_MODULES is missing " \
87
+ "(wasm=#{artifacts.wasm_path.inspect}, web_node_modules=#{artifacts.web_node_modules.inspect}). " \
88
+ "Build with `rake compile` or pass WASM_PATH=..."
89
+ end
90
+ wanted.delete(:wasm)
91
+ end
92
+
93
+ if wanted.include?(:native) && !artifacts.native_available?
94
+ if require_compiled || requested
95
+ raise Error, "Native C ABI runtime requested but #{shared_library_name} is missing " \
96
+ "(native=#{artifacts.native_lib_path.inspect}). " \
97
+ "Build with `rake compile:native` or pass NATIVE_LIB_PATH=..."
98
+ end
99
+ wanted.delete(:native)
100
+ end
101
+
102
+ wanted
103
+ end
104
+
105
+ # Canonicalize a record attribute value so Postgres, SQLite, Wasm, and
106
+ # Native values compare bit-for-bit deterministically.
107
+ def canonical_value(column, value)
108
+ return nil if value.nil?
109
+
110
+ col = column.to_s
111
+ if col.end_with?("_at")
112
+ canonical_timestamp(value)
113
+ elsif col == "server_version" || col == "word_count" || col == "revision"
114
+ value.to_i
115
+ elsif value == true || value == false
116
+ value
117
+ elsif value.is_a?(Integer)
118
+ value
119
+ else
120
+ value.to_s.encode(Encoding::UTF_8)
121
+ end
122
+ end
123
+
124
+ def canonical_timestamp(value)
125
+ time =
126
+ if value.is_a?(Time)
127
+ value.utc
128
+ else
129
+ str = value.to_s.strip
130
+ return nil if str.empty?
131
+
132
+ # SQLite stores UTC timestamps without zone suffix ("YYYY-MM-DD HH:MM:SS.ffffff").
133
+ if str.match?(/\A\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?\z/)
134
+ Time.parse("#{str.tr(' ', 'T')}Z").utc
135
+ else
136
+ Time.parse(str).utc
137
+ end
138
+ end
139
+ time.iso8601(InstantRecord::TIME_PRECISION)
140
+ end
141
+
142
+ def canonical_rows(rows, exclude_columns: %w[sync_state])
143
+ excluded = Array(exclude_columns).map(&:to_s)
144
+ Array(rows).map do |row|
145
+ pairs = row.each_with_object({}) do |(key, val), acc|
146
+ col = key.to_s
147
+ next if excluded.include?(col)
148
+
149
+ acc[col] = canonical_value(col, val)
150
+ end
151
+ pairs.sort.to_h
152
+ end.sort_by { |row| row["id"].to_s }
153
+ end
154
+
155
+ def canonical_json(object)
156
+ JSON.pretty_generate(deep_sort(object))
157
+ end
158
+
159
+ def verify_parity(
160
+ rails_app: nil,
161
+ root: nil,
162
+ database_url: ENV["DATABASE_URL"],
163
+ runtimes: ENV["RUNTIMES"],
164
+ wasm_path: ENV["WASM_PATH"],
165
+ native_lib_path: ENV["NATIVE_LIB_PATH"],
166
+ toolchain: ENV["INSTANT_RECORD_TOOLCHAIN"],
167
+ build: ENV["BUILD"] == "1",
168
+ require_compiled: ENV["REQUIRE_COMPILED"] == "1",
169
+ out: $stdout
170
+ )
171
+ artifacts = resolve_artifacts(
172
+ root: root,
173
+ wasm_path: wasm_path,
174
+ native_lib_path: native_lib_path,
175
+ toolchain: toolchain,
176
+ build: build
177
+ )
178
+ selected = select_runtimes(requested: runtimes, artifacts: artifacts, require_compiled: require_compiled)
179
+
180
+ suite = ParitySuite.new(
181
+ runtimes: selected,
182
+ artifacts: artifacts,
183
+ rails_app: rails_app,
184
+ database_url: database_url,
185
+ out: out
186
+ )
187
+ suite.run
188
+ end
189
+
190
+ def run_chaos(
191
+ seeds: nil,
192
+ steps: ENV.fetch("STEPS", "60").to_i,
193
+ clients: ENV.fetch("CLIENTS", "3").to_i,
194
+ rails_app: nil,
195
+ root: nil,
196
+ database_url: ENV["DATABASE_URL"],
197
+ runtimes: ENV["RUNTIMES"],
198
+ wasm_path: ENV["WASM_PATH"],
199
+ native_lib_path: ENV["NATIVE_LIB_PATH"],
200
+ toolchain: ENV["INSTANT_RECORD_TOOLCHAIN"],
201
+ build: ENV["BUILD"] == "1",
202
+ require_compiled: ENV["REQUIRE_COMPILED"] == "1",
203
+ out: $stdout
204
+ )
205
+ artifacts = resolve_artifacts(
206
+ root: root,
207
+ wasm_path: wasm_path,
208
+ native_lib_path: native_lib_path,
209
+ toolchain: toolchain,
210
+ build: build
211
+ )
212
+ selected = select_runtimes(requested: runtimes, artifacts: artifacts, require_compiled: require_compiled)
213
+ seed_list = resolve_seeds(seeds)
214
+
215
+ reports = seed_list.map do |seed|
216
+ sim = ChaosSimulator.new(
217
+ seed: seed,
218
+ steps: steps,
219
+ client_count: clients,
220
+ runtimes: selected,
221
+ artifacts: artifacts,
222
+ rails_app: rails_app,
223
+ database_url: database_url,
224
+ out: out
225
+ )
226
+ sim.run
227
+ end
228
+ reports
229
+ end
230
+
231
+ private
232
+
233
+ def resolve_seeds(seeds)
234
+ if seeds
235
+ Array(seeds).map(&:to_i)
236
+ elsif ENV["SEED"] && !ENV["SEED"].strip.empty?
237
+ ENV["SEED"].split(",").map { |s| Integer(s.strip) }
238
+ else
239
+ count = ENV.fetch("SEEDS", "3").to_i
240
+ base = 20261121
241
+ Array.new([count, 1].max) { |i| base + i }
242
+ end
243
+ end
244
+
245
+ def deep_sort(obj)
246
+ case obj
247
+ when Hash
248
+ obj.keys.map(&:to_s).sort.each_with_object({}) do |key, acc|
249
+ raw_key = obj.key?(key) ? key : key.to_sym
250
+ acc[key] = deep_sort(obj[raw_key])
251
+ end
252
+ when Array
253
+ obj.map { |v| deep_sort(v) }
254
+ else
255
+ obj
256
+ end
257
+ end
258
+
259
+ def find_toolchain(explicit, search_roots)
260
+ candidates = []
261
+ candidates << explicit if explicit && !explicit.to_s.empty?
262
+ search_roots.each do |base|
263
+ candidates << base.join("config/instant_record_toolchain.env").to_s
264
+ candidates << base.join("compiled/toolchain.env").to_s
265
+ end
266
+ home = ENV["HOME"]
267
+ candidates << File.join(home, ".cache/instant-record-tools/toolchain.env") if home && !home.empty?
268
+ candidates.find { |path| File.file?(path) }
269
+ end
270
+
271
+ def find_wasm(explicit, search_roots)
272
+ return File.expand_path(explicit) if explicit && !explicit.to_s.empty?
273
+
274
+ patterns = search_roots.flat_map do |base|
275
+ [
276
+ base.join("compiled/web/dist/app-*.wasm").to_s,
277
+ base.join("tmp/instant_record/compiled/web/dist/app-*.wasm").to_s,
278
+ base.join("public/instant_record_compiled/current/app-*.wasm").to_s
279
+ ]
280
+ end
281
+ patterns.each do |glob|
282
+ found = Dir.glob(glob).max_by { |path| File.mtime(path) }
283
+ return File.expand_path(found) if found
284
+ end
285
+ nil
286
+ end
287
+
288
+ def find_native_lib(explicit, search_roots)
289
+ return File.expand_path(explicit) if explicit && !explicit.to_s.empty?
290
+
291
+ lib = shared_library_name
292
+ search_roots.each do |base|
293
+ [
294
+ base.join("compiled/.build-native", lib),
295
+ base.join("tmp/instant_record/compiled/.build-native", lib)
296
+ ].each do |candidate|
297
+ return candidate.to_s if candidate.file?
298
+ end
299
+ end
300
+ nil
301
+ end
302
+
303
+ def find_web_node_modules(toolchain_path, search_roots)
304
+ if toolchain_path && File.file?(toolchain_path)
305
+ tc = Compiler::Toolchain.load(toolchain_path)
306
+ configured = tc["WEB_NODE_MODULES"]
307
+ return configured if configured && File.directory?(configured)
308
+ end
309
+
310
+ search_roots.each do |base|
311
+ [
312
+ base.join("compiled/web/node_modules"),
313
+ base.join("tmp/instant_record/compiled/web/node_modules")
314
+ ].each do |candidate|
315
+ return candidate.to_s if candidate.directory?
316
+ end
317
+ end
318
+ nil
319
+ end
320
+
321
+ def build_artifacts!(root:, toolchain_path:)
322
+ if root && Pathname(root).realpath != gem_root
323
+ models = InstantRecord.syncable_models.map(&:name)
324
+ Compiler.build(root: root, models: models, toolchain: toolchain_path, endpoint: InstantRecord::DEFAULT_MOUNT_PATH)
325
+ Compiler.build_native(root: root, models: models, toolchain: toolchain_path, endpoint: InstantRecord::DEFAULT_MOUNT_PATH)
326
+ else
327
+ Compiler.build_demo(toolchain: toolchain_path)
328
+ Compiler.build_demo_native(toolchain: toolchain_path)
329
+ end
330
+ end
331
+ end
332
+ end
333
+ end
@@ -0,0 +1,278 @@
1
+ require "base64"
2
+ require "digest"
3
+ require "json"
4
+ require "securerandom"
5
+ require "sqlite3"
6
+ require "tmpdir"
7
+
8
+ module InstantRecord
9
+ module Trace
10
+ # Schema-aware PII redactor for `.irtrace` files and embedded SQLite
11
+ # checkpoints. Mirrors `compiled/web/src/redactor.js` and uses the real
12
+ # `sqlite3` gem + VACUUM so deleted raw PII bytes never linger in freelist
13
+ # pages.
14
+ class Redactor
15
+ STRUCTURAL_SAFE_COLUMNS = %w[
16
+ id created_at updated_at deleted_at server_version sync_state cursor
17
+ operation record_type record_id mutation_id base_version status kind
18
+ type version has_more position done completed archived unread starred
19
+ read_at sent_at published_at role state
20
+ ].freeze
21
+
22
+ DEFAULT_PII_PATTERNS = [
23
+ /(^|_)e?mail(_|$|s$|_address$)/i,
24
+ /(^|_)(phone|mobile|tel|telephone|fax)(_|$)/i,
25
+ /(^|_)(password|passwd|pwd|secret|token|api_key|access_key|private_key|auth|credential|bearer)(_|$)/i,
26
+ /(^|_)(ssn|social_security|tax_id|passport|license_number|national_id)(_|$)/i,
27
+ /(^|_)(credit_card|card_number|cvv|cvc|iban|routing_number|account_number)(_|$)/i,
28
+ /(^|_)(address|street|city|zip|postal|postcode)(_|$)/i,
29
+ /(^|_)(ip|ip_address|user_agent)(_|$)/i,
30
+ /(^|_)(cookie|session|csrf)(_|$)/i,
31
+ /(^|_)(first_name|last_name|full_name|real_name|display_name|username|dob|birth_?date)(_|$)/i,
32
+ /(^|_)(from_address|to_address|cc|bcc|reply_to|sender|recipient|from_email|to_email|author_email)(_|$)/i,
33
+ /\Aidentity\z/i
34
+ ].freeze
35
+
36
+ EMAIL_VALUE_RE = /\A[^\s@]+@[^\s@]+\.[^\s@]+\z/
37
+ SENSITIVE_ENV_RE = /(secret|token|key|password|passwd|auth|cookie|credential)/i
38
+
39
+ def initialize(schema: {}, pii_columns: {}, safe_columns: {}, salt: nil)
40
+ @schema = normalize_schema(schema)
41
+ @explicit_pii = normalize_column_map(pii_columns)
42
+ @explicit_safe = normalize_column_map(safe_columns)
43
+ @salt = salt || SecureRandom.hex(16)
44
+ end
45
+
46
+ def pii_column?(table_or_model, column_name)
47
+ col = column_name.to_s.downcase
48
+ return false if col.empty?
49
+
50
+ table = resolve_table_name(table_or_model)
51
+ return false if @explicit_safe[table]&.include?(col) || @explicit_safe["*"]&.include?(col)
52
+ return true if @explicit_pii[table]&.include?(col) || @explicit_pii["*"]&.include?(col)
53
+ return true if /(^|_)(tax|national)_id\z/i.match?(col)
54
+ return false if STRUCTURAL_SAFE_COLUMNS.include?(col) || col.end_with?("_id", "_at")
55
+
56
+ DEFAULT_PII_PATTERNS.any? { |pattern| pattern.match?(col) }
57
+ end
58
+
59
+ def pseudonymize(value, hint = "")
60
+ return value if value.nil? || value == ""
61
+
62
+ text = value.to_s
63
+ hash = Digest::SHA256.hexdigest("#{@salt}:#{hint}:#{text}")[0, 12]
64
+ lower_hint = hint.to_s.downcase
65
+ if lower_hint.include?("email") || EMAIL_VALUE_RE.match?(text)
66
+ "redacted-#{hash}@redacted.invalid"
67
+ elsif lower_hint.include?("phone") || lower_hint.include?("tel") || lower_hint.include?("mobile")
68
+ "+1-555-#{hash[0, 4]}"
69
+ else
70
+ "[redacted:#{hash}]"
71
+ end
72
+ end
73
+
74
+ def redact_attributes(table_or_model, attrs)
75
+ return attrs unless attrs.is_a?(Hash)
76
+
77
+ attrs.each_with_object({}) do |(key, value), out|
78
+ out[key] = redact_field_value(table_or_model, key.to_s, value)
79
+ end
80
+ end
81
+
82
+ def redact_database(bytes)
83
+ raw = bytes.b
84
+ original_digest = Digest::SHA256.hexdigest(raw)
85
+ redacted_columns = {}
86
+
87
+ Dir.mktmpdir("irtrace-redact-") do |dir|
88
+ file = File.join(dir, "checkpoint.sqlite3")
89
+ File.binwrite(file, raw)
90
+ db = SQLite3::Database.new(file)
91
+ db.results_as_hash = true
92
+ begin
93
+ tables = db.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
94
+ .map { |row| row["name"] }
95
+
96
+ tables.each do |table|
97
+ next if %w[schema_migrations ar_internal_metadata].include?(table)
98
+
99
+ if table == "instant_record_sync_metadata"
100
+ redact_sync_metadata(db, table, redacted_columns)
101
+ elsif table == "instant_record_outbox"
102
+ redact_outbox_table(db, table, redacted_columns)
103
+ else
104
+ redact_user_table(db, table, redacted_columns)
105
+ end
106
+ end
107
+
108
+ db.execute("VACUUM")
109
+ ensure
110
+ db.close
111
+ end
112
+
113
+ clean = File.binread(file)
114
+ {
115
+ bytes: clean,
116
+ digest: Digest::SHA256.hexdigest(clean),
117
+ original_digest: original_digest,
118
+ redacted_columns: redacted_columns
119
+ }
120
+ end
121
+ end
122
+
123
+ def redact_trace(trace)
124
+ copy = JSON.parse(JSON.generate(trace))
125
+ checkpoint = copy["checkpoint"]
126
+ if checkpoint.is_a?(Hash)
127
+ if checkpoint["env"].is_a?(Hash)
128
+ checkpoint["env"] = checkpoint["env"].each_with_object({}) do |(k, v), out|
129
+ out[k] = SENSITIVE_ENV_RE.match?(k.to_s) ? pseudonymize(v, k) : v
130
+ end
131
+ end
132
+ if checkpoint["cookies"].is_a?(Hash)
133
+ checkpoint["cookies"] = checkpoint["cookies"].each_with_object({}) do |(k, v), out|
134
+ out[k] = pseudonymize(v, "cookie:#{k}")
135
+ end
136
+ end
137
+ if checkpoint["mode"] == "sqlite3" && checkpoint["data"].is_a?(String) && !checkpoint["data"].empty?
138
+ db_bytes = Base64.strict_decode64(checkpoint["data"])
139
+ result = redact_database(db_bytes)
140
+ checkpoint["data"] = Base64.strict_encode64(result[:bytes])
141
+ checkpoint["digest"] = result[:digest]
142
+ checkpoint["originalDigest"] ||= result[:original_digest]
143
+ checkpoint["byteLength"] = result[:bytes].bytesize
144
+ checkpoint["redacted"] = true
145
+ checkpoint["redactedColumns"] = result[:redacted_columns]
146
+ copy["redaction"] ||= {}
147
+ copy["redaction"]["enabled"] = true
148
+ copy["redaction"]["strategy"] = "deterministic_pseudonym"
149
+ copy["redaction"]["redactedColumns"] = (copy["redaction"]["redactedColumns"] || {}).merge(result[:redacted_columns])
150
+ end
151
+ end
152
+ copy
153
+ end
154
+
155
+ private
156
+
157
+ def quote_ident(name)
158
+ %("#{name.to_s.gsub('"', '""')}")
159
+ end
160
+
161
+ def redact_sync_metadata(db, table, redacted_columns)
162
+ db.execute("SELECT key, value FROM #{quote_ident(table)}").each do |row|
163
+ next unless row["key"] == "identity" && row["value"] && !row["value"].empty?
164
+
165
+ db.execute("UPDATE #{quote_ident(table)} SET value = ? WHERE key = ?", [pseudonymize(row["value"], "identity"), row["key"]])
166
+ redacted_columns[table] = ((redacted_columns[table] || []) | ["identity"]).sort
167
+ end
168
+ end
169
+
170
+ def redact_outbox_table(db, table, redacted_columns)
171
+ db.execute("SELECT id, record_type, changes_payload FROM #{quote_ident(table)}").each do |row|
172
+ payload = row["changes_payload"]
173
+ next if payload.nil? || payload.empty?
174
+
175
+ begin
176
+ parsed = JSON.parse(payload)
177
+ redacted = redact_attributes(row["record_type"] || "*", parsed)
178
+ serialized = JSON.generate(redacted)
179
+ next if serialized == payload
180
+
181
+ db.execute("UPDATE #{quote_ident(table)} SET changes_payload = ? WHERE id = ?", [serialized, row["id"]])
182
+ redacted_columns[table] = ((redacted_columns[table] || []) | ["changes_payload"]).sort
183
+ rescue JSON::ParserError
184
+ next
185
+ end
186
+ end
187
+ end
188
+
189
+ def redact_user_table(db, table, redacted_columns)
190
+ cols = db.execute("PRAGMA table_info(#{quote_ident(table)})").map { |col| col["name"] }
191
+ pii_cols = cols.select { |col| pii_column?(table, col) }
192
+ return if pii_cols.empty?
193
+
194
+ quoted_table = quote_ident(table)
195
+ select_cols = pii_cols.map { |c| quote_ident(c) }.join(", ")
196
+ set_clause = pii_cols.map { |c| "#{quote_ident(c)} = ?" }.join(", ")
197
+
198
+ db.execute("SELECT rowid AS __ir_rowid, #{select_cols} FROM #{quoted_table}").each do |row|
199
+ values = pii_cols.map do |col|
200
+ val = row[col]
201
+ val.nil? || val == "" ? val : pseudonymize(val, col)
202
+ end
203
+ db.execute("UPDATE #{quoted_table} SET #{set_clause} WHERE rowid = ?", values + [row["__ir_rowid"]])
204
+ end
205
+
206
+ redacted_columns[table] = pii_cols.sort
207
+ end
208
+
209
+ def redact_field_value(table_or_model, field, value)
210
+ return value if value.nil?
211
+
212
+ if pii_column?(table_or_model, field)
213
+ return value.map { |v| pseudonymize(v, field) } if value.is_a?(Array)
214
+ return pseudonymize(JSON.generate(value), field) if value.is_a?(Hash)
215
+
216
+ return pseudonymize(value, field)
217
+ end
218
+
219
+ if value.is_a?(String) && EMAIL_VALUE_RE.match?(value.strip)
220
+ return pseudonymize(value.strip, "email")
221
+ end
222
+
223
+ if value.is_a?(Hash)
224
+ return redact_attributes(table_or_model, value)
225
+ end
226
+
227
+ if value.is_a?(Array)
228
+ return value.map { |item| item.is_a?(Hash) ? redact_attributes(table_or_model, item) : item }
229
+ end
230
+
231
+ value
232
+ end
233
+
234
+ def resolve_table_name(table_or_model)
235
+ return "*" if table_or_model.nil? || table_or_model.to_s.empty?
236
+
237
+ lower = table_or_model.to_s.downcase
238
+ return lower if @schema.key?(lower) || @explicit_pii.key?(lower) || @explicit_safe.key?(lower)
239
+
240
+ guessed = model_to_table(table_or_model.to_s)
241
+ return guessed if @schema.key?(guessed) || @explicit_pii.key?(guessed) || @explicit_safe.key?(guessed)
242
+
243
+ guessed
244
+ end
245
+
246
+ def model_to_table(model_name)
247
+ base = model_name.split("::").last.to_s
248
+ snake = base
249
+ .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
250
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
251
+ .downcase
252
+ if snake.end_with?("y") && !snake.match?(/[aeiou]y\z/)
253
+ "#{snake[0..-2]}ies"
254
+ elsif snake.match?(/(?:s|x|z|ch|sh)\z/)
255
+ "#{snake}es"
256
+ else
257
+ "#{snake}s"
258
+ end
259
+ end
260
+
261
+ def normalize_schema(schema)
262
+ return {} unless schema.is_a?(Hash)
263
+
264
+ schema.each_with_object({}) do |(table, cols), out|
265
+ out[table.to_s.downcase] = Array(cols).map(&:to_s)
266
+ end
267
+ end
268
+
269
+ def normalize_column_map(map)
270
+ return {} unless map.is_a?(Hash)
271
+
272
+ map.each_with_object({}) do |(table, cols), out|
273
+ out[table.to_s.downcase] = Array(cols).map { |c| c.to_s.downcase }
274
+ end
275
+ end
276
+ end
277
+ end
278
+ end