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,126 @@
1
+ require "json"
2
+ require "open3"
3
+ require "pathname"
4
+
5
+ module InstantRecord
6
+ module Trace
7
+ # Runs `compiled/web/src/replay.js` in Node to replay an `.irtrace` file
8
+ # deterministically against a compiled app's `.wasm` module.
9
+ class Replayer
10
+ Result = Struct.new(:ok, :status, :stdout, :stderr, :report, keyword_init: true) do
11
+ def ok? = !!ok
12
+ end
13
+
14
+ def self.gem_root
15
+ Pathname(__dir__).join("../../..").realpath
16
+ end
17
+
18
+ def self.replay_script
19
+ gem_root.join("compiled/web/src/replay.js").to_s
20
+ end
21
+
22
+ def initialize(
23
+ trace_path:,
24
+ wasm_path: nil,
25
+ db_path: nil,
26
+ root: nil,
27
+ toolchain: nil,
28
+ node_modules: nil,
29
+ json: false,
30
+ allow_digest_mismatch: false,
31
+ stop_on_fault: false,
32
+ max_steps: nil,
33
+ node_bin: ENV.fetch("NODE", "node")
34
+ )
35
+ @trace_path = File.expand_path(trace_path.to_s)
36
+ @root = root ? File.expand_path(root.to_s) : nil
37
+ @wasm_path = wasm_path ? File.expand_path(wasm_path.to_s) : discover_wasm
38
+ @db_path = db_path ? File.expand_path(db_path.to_s) : nil
39
+ @toolchain = toolchain
40
+ @node_modules = discover_node_modules(node_modules)
41
+ @json = !!json
42
+ @allow_digest_mismatch = !!allow_digest_mismatch
43
+ @stop_on_fault = !!stop_on_fault
44
+ @max_steps = max_steps
45
+ @node_bin = node_bin
46
+ end
47
+
48
+ def run
49
+ raise Error, "Trace file not found: #{@trace_path}" unless File.file?(@trace_path)
50
+ unless @wasm_path && File.file?(@wasm_path)
51
+ raise Error, "Could not find a compiled app-*.wasm module. Pass WASM=/path/to/app.wasm or run bin/rails instant_record:compile first."
52
+ end
53
+
54
+ cmd = [@node_bin, self.class.replay_script, @trace_path, "--wasm", @wasm_path]
55
+ cmd.push("--db", @db_path) if @db_path
56
+ @node_modules.each { |dir| cmd.push("--node-modules", dir) }
57
+ cmd << "--json" if @json
58
+ cmd << "--allow-digest-mismatch" if @allow_digest_mismatch
59
+ cmd << "--stop-on-fault" if @stop_on_fault
60
+ cmd.push("--max-steps", @max_steps.to_s) if @max_steps
61
+
62
+ stdout, stderr, status = Open3.capture3(*cmd)
63
+ report = nil
64
+ if @json && !stdout.strip.empty?
65
+ begin
66
+ report = JSON.parse(stdout)
67
+ rescue JSON::ParserError
68
+ report = nil
69
+ end
70
+ end
71
+
72
+ Result.new(
73
+ ok: status.success?,
74
+ status: status.exitstatus || 1,
75
+ stdout: stdout,
76
+ stderr: stderr,
77
+ report: report
78
+ )
79
+ end
80
+
81
+ private
82
+
83
+ def discover_wasm
84
+ search_roots = []
85
+ if @root
86
+ search_roots << File.join(@root, "tmp/instant_record/compiled/web/dist")
87
+ search_roots << File.join(@root, "public/instant_record_compiled/current")
88
+ end
89
+ search_roots << self.class.gem_root.join("compiled/web/dist").to_s
90
+
91
+ search_roots.each do |dir|
92
+ next unless File.directory?(dir)
93
+
94
+ candidates = Dir.glob(File.join(dir, "app*.wasm")).sort_by { |path| -File.mtime(path).to_f }
95
+ return candidates.first if candidates.any?
96
+ end
97
+ nil
98
+ end
99
+
100
+ def discover_node_modules(explicit)
101
+ dirs = []
102
+ Array(explicit).compact.each { |dir| dirs << File.expand_path(dir.to_s) if File.directory?(dir.to_s) }
103
+ if ENV["INSTANT_RECORD_WEB_NODE_MODULES"] && File.directory?(ENV["INSTANT_RECORD_WEB_NODE_MODULES"])
104
+ dirs << File.expand_path(ENV["INSTANT_RECORD_WEB_NODE_MODULES"])
105
+ end
106
+ if @root
107
+ staged = File.join(@root, "tmp/instant_record/compiled/web/node_modules")
108
+ dirs << staged if File.directory?(staged)
109
+ end
110
+ if @toolchain && File.file?(@toolchain.to_s)
111
+ begin
112
+ require "instant_record/compiler/toolchain"
113
+ tc = InstantRecord::Compiler::Toolchain.load(@toolchain)
114
+ nm = tc["WEB_NODE_MODULES"]
115
+ dirs << nm if nm && File.directory?(nm)
116
+ rescue StandardError
117
+ nil
118
+ end
119
+ end
120
+ gem_nm = self.class.gem_root.join("compiled/web/node_modules").to_s
121
+ dirs << gem_nm if File.directory?(gem_nm)
122
+ dirs.uniq
123
+ end
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,37 @@
1
+ module InstantRecord
2
+ module Trace
3
+ # Extracts a compact `{ table_name => [column_names...] }` map from a Rails
4
+ # `db/schema.rb` without requiring an active database connection. Used at
5
+ # compile time (`VITE_TRACE_SCHEMA`) and by Ruby-side trace redaction.
6
+ module SchemaExtractor
7
+ CREATE_TABLE_RE = /^\s*create_table\s+["']([^"']+)["']/
8
+ COLUMN_RE = /^\s*t\.(?:string|text|integer|bigint|float|decimal|boolean|datetime|timestamp|date|time|binary|json|jsonb|uuid)\s+["']([^"']+)["']/
9
+ TIMESTAMPS_RE = /^\s*t\.timestamps\b/
10
+
11
+ module_function
12
+
13
+ def from_schema_rb(source)
14
+ tables = {}
15
+ current = nil
16
+ source.to_s.each_line do |line|
17
+ if (match = CREATE_TABLE_RE.match(line))
18
+ current = match[1]
19
+ tables[current] = ["id"]
20
+ elsif current
21
+ if line.match?(/^\s*end\s*$/)
22
+ current = nil
23
+ elsif (col = COLUMN_RE.match(line))
24
+ name = col[1]
25
+ tables[current] << name unless tables[current].include?(name)
26
+ elsif TIMESTAMPS_RE.match?(line)
27
+ %w[created_at updated_at].each do |ts|
28
+ tables[current] << ts unless tables[current].include?(ts)
29
+ end
30
+ end
31
+ end
32
+ end
33
+ tables
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,22 @@
1
+ require_relative "trace/schema_extractor"
2
+ require_relative "trace/redactor"
3
+ require_relative "trace/replayer"
4
+
5
+ module InstantRecord
6
+ # Deterministic `.irtrace` flight-recorder utilities: schema extraction for
7
+ # PII redaction, Ruby-side SQLite checkpoint redaction, and Node AppHost replay.
8
+ module Trace
9
+ FORMAT = "instant_record.trace".freeze
10
+ VERSION = 1
11
+
12
+ class Error < StandardError; end
13
+
14
+ def self.replay(**options)
15
+ Replayer.new(**options).run
16
+ end
17
+
18
+ def self.redact(trace, **options)
19
+ Redactor.new(**options).redact_trace(trace)
20
+ end
21
+ end
22
+ end
@@ -1,3 +1,3 @@
1
1
  module InstantRecord
2
- VERSION = "0.1.0"
2
+ VERSION = "0.3.0"
3
3
  end
@@ -4,13 +4,20 @@ require "base64"
4
4
  module InstantRecord
5
5
  DEFAULT_MOUNT_PATH = "/instant_record".freeze
6
6
 
7
- # Both engine controllers serve a PWA that may run on another origin in
8
- # development (Vite dev server); auth on the sync endpoints is out of scope
9
- # for the PoC.
7
+ # Raised by `config.authenticate_request`, `config.scope_from`,
8
+ # `config.partition_from`, or `authorize_partition` to reject a sync request
9
+ # with HTTP 401 or 403.
10
+ Unauthorized = Class.new(StandardError)
11
+ Forbidden = Class.new(StandardError)
12
+
13
+ # Engine endpoints allow cross-origin reads and JSON writes so a separately
14
+ # hosted compiled site or Vite dev server can reach Rails. Access control is
15
+ # enforced per model via `sync_scope`, `sync_partition`, `syncable_to`, and
16
+ # `writable_by`.
10
17
  CORS_HEADERS = {
11
18
  "access-control-allow-origin" => "*",
12
19
  "access-control-allow-methods" => "GET, POST, OPTIONS",
13
- "access-control-allow-headers" => "content-type, last-event-id"
20
+ "access-control-allow-headers" => "content-type, last-event-id, authorization, x-instant-record-scope, x-instant-record-partition, x-instant-record-member"
14
21
  }.freeze
15
22
 
16
23
  # Every timestamp crossing the wire carries microseconds, in both directions.
@@ -29,19 +36,19 @@ end
29
36
 
30
37
  require "active_support/isolated_execution_state"
31
38
  require "instant_record/version"
39
+ require "instant_record/host"
32
40
  require "instant_record/configuration"
33
41
  require "instant_record/runtime_scoped"
34
- require "wasmify-rails" # browser build tasks + PGlite adapter; inert outside wasm builds
35
- require "instant_record/engine" if defined?(Rails::Engine)
42
+ require "instant_record/inertia"
43
+ require "instant_record/read_tracker"
44
+ require "instant_record/native"
45
+ InstantRecord::Host.load_engine
36
46
 
37
47
  module InstantRecord
38
48
  class << self
39
- # True when running inside the browser (ruby.wasm). Delegates to
40
- # wasmify-rails' Kernel#on_wasm?; kept as a method so it stays the
41
- # single stub point for tests and the public name for apps.
42
- def browser?
43
- on_wasm?
44
- end
49
+ # Delegated to InstantRecord::Host so AOT builds swap the host adapter
50
+ # module instead of string-patching this file.
51
+ def browser? = Host.browser?
45
52
 
46
53
  def config
47
54
  @config ||= Configuration.new
@@ -64,8 +71,7 @@ module InstantRecord
64
71
  def synced_model(record_type)
65
72
  return synced_models.find { |model| model.name == record_type } if synced_models.any?
66
73
 
67
- klass = record_type.to_s.safe_constantize
68
- klass if klass.respond_to?(:instant_record_syncable?) && klass.instant_record_syncable?
74
+ Host.resolve_syncable_model(record_type)
69
75
  end
70
76
 
71
77
  # Every model participating in sync: the explicit allowlist when set,
@@ -73,10 +79,7 @@ module InstantRecord
73
79
  def syncable_models
74
80
  return synced_models if synced_models.any?
75
81
 
76
- ActiveRecord::Base.descendants.select do |model|
77
- !model.abstract_class? && model.name &&
78
- model.respond_to?(:instant_record_syncable?) && model.instant_record_syncable?
79
- end
82
+ Host.discover_syncable_models
80
83
  end
81
84
 
82
85
  # One record's attributes as they cross the wire, in either direction and on
@@ -86,36 +89,49 @@ module InstantRecord
86
89
  # the (created_at, id) keyset cursor round-trips exactly and both sides of a
87
90
  # last-write-wins comparison are measured with the same ruler.
88
91
  def wire_attributes(attributes)
89
- attributes.except("sync_state").transform_values do |value|
92
+ snapshot_attributes(attributes.except("sync_state"))
93
+ end
94
+
95
+ # Full local row snapshot for delay-line rollback: keeps sync_state alongside
96
+ # every other column, with timestamps at TIME_PRECISION so restore is lossless.
97
+ def snapshot_attributes(attributes)
98
+ attributes.transform_values do |value|
90
99
  # usec, not iso8601: a Date answers to iso8601 but takes no precision
91
100
  # argument, and its default JSON form already round-trips exactly.
92
101
  value.respond_to?(:usec) ? value.iso8601(TIME_PRECISION) : value
93
102
  end
94
103
  end
95
104
 
105
+ # The scope a record belongs to, or nil for a record every client may see.
106
+ def scope_of(record)
107
+ column = record.class.instant_record_sync_scope
108
+ record[column].presence if column
109
+ end
110
+
111
+ # The partition key-value a record belongs to (e.g. "mailbox_id:support"),
112
+ # or nil for an unpartitioned model.
113
+ def partition_of(record)
114
+ partition = record.class.instant_record_sync_partition
115
+ partition&.change_partition_for(record)
116
+ end
117
+
96
118
  # The wire shape for one record, shared by the bootstrap and records
97
119
  # endpoints and mirroring Change#as_event: clients apply all three through
98
120
  # the same upsert path.
99
121
  def record_payload(record)
100
- {
122
+ payload = {
101
123
  type: record.class.name,
102
124
  id: record.id,
103
125
  version: record[:server_version],
104
126
  attributes: wire_attributes(record.attributes)
105
127
  }
128
+ if (stamp = HLC.record_hlc(record.class.name, record.id))
129
+ payload[:hlc] = stamp
130
+ end
131
+ payload
106
132
  end
107
133
 
108
- # Bring this runtime's database up to the app's schema. Stands in for a bare
109
- # `ActiveRecord::Tasks::DatabaseTasks.prepare_all` at boot, which cannot see
110
- # the app's migrations from the browser VM's working directory and so leaves
111
- # a returning visitor on the schema they first booted with — see LocalSchema.
112
- def prepare_database! = LocalSchema.prepare!
113
-
114
- # Begin background sync (browser runtime only; a no-op on the server).
115
- # The gem's service worker shim schedules `tick` on config.sync_interval.
116
- # cold_boot: false skips the boot-time window eviction — the service
117
- # worker passes it when it was restarted under already-open tabs (an idle
118
- # SW restart mid-read must not trim scrollback the reader is holding).
134
+ # Begin background sync in the browser.
119
135
  def start(cold_boot: true)
120
136
  return false unless browser?
121
137
 
@@ -176,14 +192,49 @@ module InstantRecord
176
192
  return JSON.generate(ok: false, busy: true) if result == :busy
177
193
  return JSON.generate(ok: false, started: false) if result == :not_started
178
194
 
179
- JSON.generate(ok: true, pending: pending_count)
195
+ payload = { ok: true, pending: pending_count }
196
+ next_ms = next_release_ms
197
+ payload[:next_release_ms] = next_ms unless next_ms.nil?
198
+ JSON.generate(payload)
180
199
  rescue StandardError => e
181
200
  # Never raise across the JS boundary; a failed pass is a retry, not a crash.
182
201
  JSON.generate(ok: false, error: e.message, pending: safe_pending_count)
183
202
  end
184
203
 
185
204
  def pending_count = Client.pending_count
205
+ def held_count = Client.held_count
206
+ def held_mutations = Client.held_mutations
207
+ def next_release_at = Client.next_release_at
208
+ def next_release_ms = Client.next_release_ms
186
209
  def cursor = Client.cursor
210
+ def sync_notices = SyncNotice.active.recent
211
+ def sync_notices_count = SyncNotice.active.count
212
+ def resolve_sync_notice(id, action:, overrides: {}) = SyncNotice.resolve(id, action: action, overrides: overrides)
213
+
214
+ # Hold local outbox writes created inside the block for `seconds` before they
215
+ # mature for sync, recording a pre-mutation snapshot so cancel_pending can
216
+ # restore local SQLite and drop the outbox row before release.
217
+ def hold_for(seconds, &block)
218
+ Client.with_hold(seconds, &block)
219
+ end
220
+
221
+ # Cancel a held outbox mutation before its release_at matures, restoring the
222
+ # local SQLite row from its pre-mutation snapshot and deleting the outbox row.
223
+ def cancel_pending(mutation_id)
224
+ Client.cancel_pending(mutation_id)
225
+ end
226
+
227
+ # Copy-on-write local SQLite staging branch. Forks the live local SQLite
228
+ # workspace into an isolated offline copy for safe bulk edits and visual UI
229
+ # preview, then either approves (extracting & replaying queued outbox
230
+ # mutations onto current `main`) or discards with zero server impact.
231
+ def branch!(name: nil, directory: nil, &block)
232
+ Branch.open(name: name, directory: directory, &block)
233
+ end
234
+
235
+ def current_branch = Branch.current
236
+ def branched? = Branch.active?
237
+ def branch_name = Branch.current_name
187
238
 
188
239
  # On-demand history page for a windowed model (see Client.fetch_history).
189
240
  # Shares the tick's single-flight guard both ways: a fetch during a sync
@@ -221,7 +272,11 @@ module InstantRecord
221
272
  # ignored — which is why app code builds this URL without asking which
222
273
  # runtime it is in.
223
274
  def server_url(path)
224
- "#{endpoint.to_s.delete_suffix(mount_path)}#{path}?#{NETWORK_MARKER}"
275
+ path_str = path.to_s
276
+ separator = path_str.include?("?") ? "&" : "?"
277
+ current_mount = mount_path
278
+ base = (endpoint == DEFAULT_MOUNT_PATH && current_mount != DEFAULT_MOUNT_PATH) ? "" : endpoint.to_s.delete_suffix(current_mount)
279
+ "#{base}#{path_str}#{separator}#{NETWORK_MARKER}"
225
280
  end
226
281
 
227
282
  # Tell the sync loop a stream is live, so its own catch-up poll stands down.
@@ -297,6 +352,13 @@ module InstantRecord
297
352
  JSON.generate(ok: false, error: e.message)
298
353
  end
299
354
 
355
+ # Execute a declared sync_action in the active runtime (optimistically inside
356
+ # a local SQLite savepoint on the client, or in one transaction on the server).
357
+ def mutate(mutator_name, args = nil, mutation_id: nil, **kwargs)
358
+ merged = args ? (kwargs.empty? ? args : args.merge(kwargs)) : kwargs
359
+ SyncActions.mutate(mutator_name, merged, mutation_id: mutation_id)
360
+ end
361
+
300
362
  # Server-side change logging (Syncable) must not fire while a client
301
363
  # mutation is being applied — MutationApplier logs those itself.
302
364
  # IsolatedExecutionState is fiber-aware for Falcon's fiber-per-request.
@@ -318,8 +380,9 @@ module InstantRecord
318
380
  # that mount, so stripping it leaves the app's own base — read from config
319
381
  # rather than assumed, because an app is free to move the mount.
320
382
  def mount_path
321
- configured = Rails.application.config.instant_record.mount_path if defined?(Rails) && Rails.application
322
- configured.is_a?(String) ? configured : DEFAULT_MOUNT_PATH
383
+ return config.mount_path if config.mount_path.is_a?(String)
384
+
385
+ Host.default_mount_path
323
386
  end
324
387
 
325
388
  # The retry decision must survive a database that is itself unhappy:
@@ -347,10 +410,17 @@ module InstantRecord
347
410
  end
348
411
 
349
412
  ActiveSupport.on_load(:active_record) do
350
- require "instant_record/local_schema"
351
413
  require "instant_record/sync_window"
414
+ require "instant_record/sync_partition"
415
+ require "instant_record/sync_metadata"
416
+ require "instant_record/hlc"
417
+ require "instant_record/sync_actions"
352
418
  require "instant_record/syncable"
353
419
  require "instant_record/outbox_mutation"
354
- require "instant_record/sync_metadata"
420
+ require "instant_record/sync_notice"
355
421
  require "instant_record/client"
422
+ require "instant_record/branch"
423
+ InstantRecord::Host.load_branch_store
356
424
  end
425
+
426
+ InstantRecord::Host.install_active_job_guard