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,388 @@
1
+ require "time"
2
+
3
+ module InstantRecord
4
+ # Copy-on-write local SQLite staging branches.
5
+ #
6
+ # A branch forks the live local SQLite database into an isolated offline copy
7
+ # so a user or AI agent can run bulk edits, inspect the resulting state through
8
+ # the real Rails UI, and then either:
9
+ #
10
+ # * approve! — extract only the OutboxMutations recorded on the branch and
11
+ # replay them safely onto current `main` (preserving any remote deltas or
12
+ # concurrent updates that arrived on `main` during review), then sync.
13
+ # * discard! — drop the branch file with zero impact on `main` or the server.
14
+ #
15
+ # The extraction, summary, and replay methods are Spinel-safe so the compiled
16
+ # WASM and native runtimes share the exact same merge semantics as CRuby.
17
+ class Branch
18
+ Error = Class.new(StandardError)
19
+
20
+ CONFLICT_STRATEGIES = %w[lww branch_wins].freeze
21
+
22
+ class << self
23
+ attr_accessor :current, :store_class
24
+
25
+ def active?
26
+ !@current.nil? || !env_branch_name.empty?
27
+ end
28
+
29
+ def current_name
30
+ return @current.name if @current
31
+
32
+ name = env_branch_name
33
+ name.empty? ? nil : name
34
+ end
35
+
36
+ # Fork the live local SQLite workspace into an isolated offline branch.
37
+ # With a block, yields the branch handle and safely discards it if the
38
+ # block neither approves nor discards (or raises an exception).
39
+ def open(name: nil, directory: nil, &block)
40
+ raise Error, "Staging branches are only available in the local client runtime" unless InstantRecord.browser?
41
+ raise Error, "Already on staging branch '#{current_name}' — approve or discard it first" if active?
42
+ raise Error, "Local SQLite branching requires CRuby sqlite3 support (or the compiled worker host)" unless store_class
43
+
44
+ base_outbox_ids = OutboxMutation.ordered.map(&:id)
45
+ branch_name = normalize_name(name)
46
+ store = store_class.fork!(name: branch_name, directory: directory)
47
+
48
+ branch = new(name: branch_name, store: store, base_outbox_ids: base_outbox_ids)
49
+ @current = branch
50
+ Client.forget_database
51
+
52
+ return branch unless block
53
+
54
+ begin
55
+ result = block.call(branch)
56
+ branch.discard! if branch.active?
57
+ result
58
+ rescue StandardError
59
+ branch.discard! if branch.active?
60
+ raise
61
+ end
62
+ end
63
+
64
+ # Extract only OutboxMutations created after `since_ids`, in causal order.
65
+ # Spinel-safe: uses only OutboxMutation.ordered and plain hashes.
66
+ def extract_mutations(since_ids: [])
67
+ excluded = {}
68
+ Array(since_ids).each { |id| excluded[id.to_s] = true }
69
+
70
+ extracted = []
71
+ OutboxMutation.ordered.each do |row|
72
+ next if excluded[row.id.to_s]
73
+
74
+ mutation = row.as_mutation
75
+ created = row.created_at
76
+ mutation[:created_at] = created.respond_to?(:usec) ? created.utc.iso8601(InstantRecord::TIME_PRECISION) : created.to_s
77
+ extracted << mutation
78
+ end
79
+ extracted
80
+ end
81
+
82
+ # Structured diff summary for preview UIs and agents.
83
+ def summary(since_ids: [])
84
+ mutations = extract_mutations(since_ids: since_ids)
85
+ by_operation = {}
86
+ by_type = {}
87
+
88
+ mutations.each do |mutation|
89
+ op = mutation[:operation].to_s
90
+ type = mutation[:record_type].to_s
91
+ by_operation[op] = (by_operation[op] || 0) + 1
92
+ by_type[type] = (by_type[type] || 0) + 1
93
+ end
94
+
95
+ {
96
+ "count" => mutations.size,
97
+ "by_operation" => by_operation,
98
+ "by_type" => by_type,
99
+ "mutations" => mutations
100
+ }
101
+ end
102
+
103
+ # Safely replay extracted branch OutboxMutations onto the currently active
104
+ # `main` SQLite database inside a single transaction.
105
+ #
106
+ # Concurrent remote deltas that arrived on `main` during branch review are
107
+ # preserved:
108
+ # - Untouched records and newly arrived remote records stay intact.
109
+ # - Partial `update` payloads merge onto current `main` rows, preserving
110
+ # concurrent remote changes to other columns.
111
+ # - Under `conflict: :lww` (default), a branch update whose `updated_at`
112
+ # is strictly older than `main`'s current row is skipped and reported
113
+ # in `conflicts` (matching MutationApplier#stale? semantics).
114
+ # - Under `conflict: :branch_wins`, a stale branch update is restamped
115
+ # to the approval time so it supersedes the older row on both `main`
116
+ # and the server.
117
+ # - Updates to rows deleted on `main` during review, creates whose id
118
+ # already exists, and redundant destroys are recorded cleanly without
119
+ # aborting the rest of the replay.
120
+ def replay_mutations(mutations, conflict: :lww)
121
+ strategy = conflict.to_s
122
+ unless CONFLICT_STRATEGIES.include?(strategy)
123
+ raise ArgumentError, "Unknown conflict strategy #{conflict.inspect}; expected :lww or :branch_wins"
124
+ end
125
+
126
+ applied = 0
127
+ skipped = 0
128
+ conflicts = []
129
+ list = Array(mutations)
130
+ return { "applied" => 0, "skipped" => 0, "conflicts" => [] } if list.empty?
131
+
132
+ OutboxMutation.transaction do
133
+ last_outbox_at = latest_outbox_time
134
+
135
+ list.each do |raw|
136
+ mutation = raw.deep_stringify_keys
137
+ mutation_id = mutation["id"].to_s
138
+ record_type = mutation["record_type"].to_s
139
+ record_id = mutation["record_id"].to_s
140
+ operation = mutation["operation"].to_s
141
+ changes = (mutation["changes"] || {}).deep_stringify_keys
142
+
143
+ # Idempotency guard: never enqueue the same branch mutation twice.
144
+ if !mutation_id.empty? && OutboxMutation.find_by(id: mutation_id)
145
+ skipped += 1
146
+ next
147
+ end
148
+
149
+ model = InstantRecord.synced_model(record_type)
150
+ unless model
151
+ skipped += 1
152
+ conflicts << conflict_entry(mutation_id, record_type, record_id, operation, "unknown record type")
153
+ next
154
+ end
155
+
156
+ outcome = Client.applying_remote do
157
+ apply_one_mutation(model, mutation_id, record_type, record_id, operation, changes, strategy)
158
+ end
159
+
160
+ if outcome[:status] == :applied
161
+ ts = next_outbox_time(mutation["created_at"], last_outbox_at)
162
+ last_outbox_at = ts
163
+ OutboxMutation.create!(
164
+ id: mutation_id.empty? ? nil : mutation_id,
165
+ record_type: record_type,
166
+ record_id: record_id,
167
+ operation: operation,
168
+ changes_payload: outcome[:changes],
169
+ base_version: outcome[:base_version],
170
+ created_at: ts,
171
+ updated_at: ts
172
+ )
173
+ Client.note_change(record_type, record_id)
174
+ applied += 1
175
+ else
176
+ skipped += 1
177
+ conflicts << conflict_entry(mutation_id, record_type, record_id, operation, outcome[:reason])
178
+ end
179
+ end
180
+ end
181
+
182
+ Client.notify_changed if applied > 0
183
+ { "applied" => applied, "skipped" => skipped, "conflicts" => conflicts }
184
+ end
185
+
186
+ private
187
+
188
+ def env_branch_name
189
+ ENV["INSTANT_RECORD_BRANCH"].to_s
190
+ end
191
+
192
+ def normalize_name(name)
193
+ cleaned = name.to_s.strip
194
+ cleaned.empty? ? "staging" : cleaned
195
+ end
196
+
197
+ def apply_one_mutation(model, _mutation_id, _record_type, record_id, operation, changes, strategy)
198
+ case operation
199
+ when "create"
200
+ if model.find_by(id: record_id)
201
+ return { status: :skipped, reason: "id already exists" }
202
+ end
203
+
204
+ attrs = changes.slice(*model.column_names)
205
+ record = model.new
206
+ record.id = record_id
207
+ record.assign_attributes(attrs.except("id", "server_version", "sync_state"))
208
+ record.server_version = 0
209
+ record.sync_state = "pending"
210
+ record.save!(validate: false)
211
+ { status: :applied, base_version: 0, changes: changes }
212
+ when "update"
213
+ record = model.find_by(id: record_id)
214
+ return { status: :skipped, reason: "record not found" } unless record
215
+
216
+ incoming_at = parse_timestamp(changes["updated_at"])
217
+ local_at = record.respond_to?(:updated_at) ? record.updated_at : nil
218
+ effective_changes = changes
219
+
220
+ if incoming_at && local_at && incoming_at < local_at
221
+ if strategy == "branch_wins"
222
+ now_utc = Time.now.utc
223
+ # Add 10 usec (Float-safe in Spinel) so iso8601(6) never truncates back to local_at.
224
+ stamped = now_utc > local_at ? now_utc : (local_at.utc + 0.00001)
225
+ effective_changes = changes.merge("updated_at" => stamped.iso8601(InstantRecord::TIME_PRECISION))
226
+ else
227
+ return { status: :skipped, reason: "stale" }
228
+ end
229
+ end
230
+
231
+ attrs = effective_changes.except("id", "server_version", "sync_state").slice(*model.column_names)
232
+ record.assign_attributes(attrs)
233
+ record.sync_state = "pending"
234
+ record.save!(validate: false)
235
+ { status: :applied, base_version: record[:server_version] || 0, changes: effective_changes }
236
+ when "destroy"
237
+ record = model.find_by(id: record_id)
238
+ return { status: :skipped, reason: "already destroyed" } unless record
239
+
240
+ base_version = record[:server_version] || 0
241
+ record.destroy!
242
+ { status: :applied, base_version: base_version, changes: {} }
243
+ else
244
+ { status: :skipped, reason: "unknown operation" }
245
+ end
246
+ end
247
+
248
+ def parse_timestamp(value)
249
+ return nil if value.nil? || value.to_s.empty?
250
+
251
+ Time.parse(value.to_s)
252
+ rescue ArgumentError
253
+ nil
254
+ end
255
+
256
+ def latest_outbox_time
257
+ last = OutboxMutation.ordered.last
258
+ last&.created_at&.to_time
259
+ end
260
+
261
+ def next_outbox_time(raw_created_at, previous)
262
+ candidate = parse_timestamp(raw_created_at) || Time.now.utc
263
+ if previous && candidate <= previous
264
+ previous + 0.00001
265
+ else
266
+ candidate
267
+ end
268
+ end
269
+
270
+ def conflict_entry(mutation_id, record_type, record_id, operation, reason)
271
+ {
272
+ "mutation_id" => mutation_id,
273
+ "record_type" => record_type,
274
+ "record_id" => record_id,
275
+ "operation" => operation,
276
+ "reason" => reason
277
+ }
278
+ end
279
+ end
280
+
281
+ attr_reader :name, :base_outbox_ids
282
+
283
+ def initialize(name:, store:, base_outbox_ids:)
284
+ @name = name
285
+ @store = store
286
+ @base_outbox_ids = base_outbox_ids.freeze
287
+ @state = :active
288
+ end
289
+
290
+ def active?
291
+ @state == :active
292
+ end
293
+
294
+ def approved?
295
+ @state == :approved
296
+ end
297
+
298
+ def discarded?
299
+ @state == :discarded
300
+ end
301
+
302
+ def path
303
+ @store.branch_path
304
+ end
305
+
306
+ def staged_mutations
307
+ ensure_active!
308
+ self.class.extract_mutations(since_ids: @base_outbox_ids)
309
+ end
310
+
311
+ def staged_count
312
+ staged_mutations.size
313
+ end
314
+
315
+ def preview_diff
316
+ ensure_active!
317
+ self.class.summary(since_ids: @base_outbox_ids)
318
+ end
319
+
320
+ # Temporarily switch back to `main` while this branch stays open (for
321
+ # inspecting `main` or delivering concurrent remote deltas during review).
322
+ def on_main
323
+ ensure_active!
324
+ previous = self.class.current
325
+ self.class.current = nil
326
+ @store.with_main do
327
+ Client.forget_database
328
+ yield
329
+ end
330
+ ensure
331
+ self.class.current = previous
332
+ Client.forget_database
333
+ end
334
+
335
+ # Extract only this branch's queued OutboxMutations, switch back to current
336
+ # `main` (preserving any concurrent updates that arrived during review),
337
+ # replay the mutations onto `main`, and optionally run a sync pass.
338
+ def approve!(sync: false, conflict: :lww)
339
+ ensure_active!
340
+ mutations = self.class.extract_mutations(since_ids: @base_outbox_ids)
341
+ @store.restore_main!
342
+ @state = :approved
343
+ self.class.current = nil
344
+ Client.forget_database
345
+
346
+ replay = self.class.replay_mutations(mutations, conflict: conflict)
347
+ @store.cleanup!
348
+
349
+ synced = false
350
+ if sync && replay["applied"] > 0
351
+ synced = !!Client.sync_pass
352
+ end
353
+
354
+ {
355
+ approved: true,
356
+ name: @name,
357
+ applied: replay["applied"],
358
+ skipped: replay["skipped"],
359
+ conflicts: replay["conflicts"],
360
+ synced: synced
361
+ }
362
+ end
363
+
364
+ # Drop the staging SQLite file and return to current `main` with zero
365
+ # mutations applied to `main` and zero server impact.
366
+ def discard!
367
+ ensure_active!
368
+ dropped = self.class.extract_mutations(since_ids: @base_outbox_ids).size
369
+ @store.restore_main!
370
+ @state = :discarded
371
+ self.class.current = nil
372
+ Client.forget_database
373
+ @store.cleanup!
374
+
375
+ {
376
+ discarded: true,
377
+ name: @name,
378
+ dropped: dropped
379
+ }
380
+ end
381
+
382
+ private
383
+
384
+ def ensure_active!
385
+ raise Error, "Staging branch '#{@name}' is already #{@state}" unless active?
386
+ end
387
+ end
388
+ end
@@ -1,21 +1,17 @@
1
1
  module InstantRecord
2
2
  module Client
3
3
  module Notifier
4
- # Tells every open tab that local data changed so pages re-render.
5
- # Runs in the service worker context; indexes the client list rather
6
- # than passing Ruby procs to JS (narrower interop surface).
7
- class JsClients
8
- def initialize
9
- require "js"
4
+ class Worker
5
+ def records_changed
6
+ # The notice, then one compact JSON delta line per changed record
7
+ # when the client can list them (Client.changes_notice).
8
+ InstantRecord::Host.write_channel("notify", InstantRecord::Client.changes_notice)
10
9
  end
11
10
 
12
- def records_changed
13
- clients = JS.global[:clients].matchAll.await
14
- message = JS.eval("return {type: 'records_changed'}")
11
+ def events_emitted(payload)
12
+ return unless File.directory?("/host")
15
13
 
16
- clients[:length].to_i.times do |i|
17
- clients[i].postMessage(message)
18
- end
14
+ File.write("/host/events", payload)
19
15
  end
20
16
  end
21
17
  end