This repository was archived by the owner on Sep 2, 2026. It is now read-only.
Repository navigation
[Spec] Multi-machine sync - #62
Merged
Merged
Conversation
…34) - src/sync-relay/worker: dumb opaque-row Cloudflare Worker (D1 push/pull, monotonic serverSeq cursor, tombstones), device-auth seam (HMAC via Web Crypto, unknown/revoked rejection) for ticket #42 to populate. - src/sync-relay/crypto: NaCl secretbox row envelope with AAD bound to table/rowId/version/keyId (HKDF row key modelled on mobile-e2ee-v2-key-schedule.ts); wrong-key/tampered-AAD decode returns null, never throws. - src/sync-relay/client: minimal push/pull transport with capability negotiation from the handshake (remote-wire-compatibility Rule 1/2), client-side payload size cap before sending. LWW merge (#41) and pairing UI (#42) are explicitly out of scope; this exposes the seams. - config/tsconfig.node.json: cover src/sync-relay under the node typecheck project.
- docs/reference/sync-relay-deployment.md: D1 schema, wrangler deploy steps, device bootstrap/revoke, capability negotiation, payload cap. - src/sync-relay/worker/wrangler.toml: example deploy config (wrangler itself stays a manual, non-dependency tool). - .gitignore: allow-list the new tracked reference doc, matching the existing docs/reference/*.md pattern.
…ilures (#34) The relay's upsert overwrote unconditionally, so a lagging device could clobber a newer row or resurrect a tombstone — client-side merge cannot undo that once the relay itself holds the stale value. Accept a push only when its version strictly supersedes the stored one and report refusals with storedVersion. Auth distinguished unknown-device from revoked before verifying the signature, which let anyone enumerate paired device ids; both now answer an opaque 401 and only a caller holding the secret learns a device is revoked.
Self-hosted Cloudflare Worker + D1 relay storing only opaque E2E-encrypted rows, the per-row crypto envelope (NaCl secretbox + HKDF, AAD bound to table/rowId/version/keyId), and a capability-negotiated push/pull client. Reviewed before merge: added a server-side stale-write guard and closed a device-id enumeration leak in the auth path.
64ix
force-pushed
the
spec/29-multi-machine-sync
branch
from
August 24, 2026 19:28
d691c61 to
c3076fd
Compare
Core primitives: SyncUnitState, deterministic LWW conflict resolution (version then wall-clock updatedAt then stable content tiebreak), a pure pull reconciliation step, a durable offline write queue with a file-backed store, the row codec bridging to the sync-relay envelope, a worktree-meta remote-host eligibility filter, and a rename/rekey identity fold using WorktreeMeta.priorWorktreeIds. The reconciliation engine ties push/pull/queue/crypto together as the seam ticket #46 wires into the app.
…d, host filter (#41) 7 test files, 41 cases: version-ordering/no-dialogs conflict resolution (sync-lww-merge.test.ts), tombstone survival under a stale queued edit and a redelivered older pull (sync-reconciliation.test.ts), the write queue surviving a process restart via a real tmp-file store (sync-write-queue.test.ts), the row codec's seal/open round trip and wrong-key rejection (sync-row-codec.test.ts), remote-host exclusion (sync-worktree-meta-eligibility.test.ts), rename/rekey collapse into a tombstone incl. a two-hop chain (sync-worktree-meta-identity.test.ts), and end-to-end engine flows against a fake relay: cross-device propagation, a push rejection re-merged against the actual winning content rather than retried blind, and offline-queue durability across a restart flushed push-then-pull on reconnect (sync-reconciliation-engine.test.ts).
- New shared offer schema (relay URL + inviter device pubkey + one secret half) and orca://pair deep-link encode/decode, kept separate from mobile-relay-pairing-offer.ts (no Orca Cloud coupling). - HKDF combine for the two-half pairing secret (sync-pairing-secret-schedule.ts). - Worker routes: /v1/bootstrap (unauthenticated, only while sync_devices is empty), /v1/pair and /v1/revoke (authenticated as an already-active device), /v1/devices (lists public device metadata, never secrets). - SyncRelayClient: pairDevice/revokeDevice/listDevices instance methods plus standalone bootstrapSyncRelayDevice(). - Tests: full pairing round trip against an in-process worker, and an explicit two-half security test proving neither half alone authenticates.
…erSeq (#41) pull() is page-limited (500 rows) while latestServerSeq is the relay's global counter, so advancing the cursor to it after a full page silently stranded every row past that page — permanent, invisible divergence once a device fell more than one page behind. Advance to the highest serverSeq actually received and keep paging until an empty page proves we caught up. The fake relay in the tests never paginated, which is why this passed; it now mirrors the worker. Also expose serverCursor so #46 can persist it across restarts rather than refetching the whole changefeed on every launch.
Key/value last-write-wins over the per-key app-state shapes: deterministic conflict resolution with no dialogs, tombstones that a stale machine cannot resurrect, a durable offline write queue that flushes on reconnect, rename/rekey folding via priorWorktreeIds, and remote-host workspace exclusion. Reviewed before merge: fixed a changefeed cursor bug that silently stranded every row past the first pull page.
) - base32 encode/decode for the manually-typed pairing-secret half (sync-pairing-manual-code.ts), grouped for legibility. - src/main/sync-pairing/: per-machine sync-relay identity (deviceId, NaCl box keypair, relay credential, known peers) persisted via writeSecureJsonFile/hardenExistingSecureFile, deliberately separate from device-registry.ts's mobile/runtime-relay device notion.
…voke (#42) SyncPairingRuntime ties the local identity file to SyncRelayClient: bootstrap() for the first device, createInvite() (mints both secret halves, registers the combined secret via pairDevice, returns the orca://pair offer + manual code), joinWithInvite() (combines halves, verifies via a live handshake before persisting anything), plus listDevices()/revokeDevice(). Tests cover the full invite->join round trip, a wrong manual-code join, and immediate revocation.
- src/main/ipc/sync-pairing.ts + src/preload/api/sync-pairing-api.ts: sync:getStatus/bootstrap/createInvite/joinWithInvite/listDevices/ revokeDevice, wired in src/main/index.ts on the same stable getCanonicalUserDataPath() mobile pairing uses. - Settings > Sync Devices pane (desktop-only, like SSH Hosts): lists paired machines (name, paired-at, last-seen) with per-device revoke, an Invite dialog (QR + copyable link + manual pairing code), a Join dialog (paste link + type code), and a minimal bootstrap card for the very first device (relay URL input) — the seam #46's relay-config settings section will eventually front. - All new strings routed through translate().
…() (#42) Fixes verify:localization-coverage findings; also runs sync:localization-catalog to add the new auto.* keys to en.json.
…ect (#42) react-doctor(no-adjust-state-on-prop-change): reset invite/QR/name from the Dialog's onOpenChange handler instead of a useEffect keyed on `open`. Also hoists the pure copyToClipboard helper to module scope per prefer-module-scope-pure-function.
Updates 'Registering a device' to describe /v1/bootstrap (first device, unauthenticated while sync_devices is empty), /v1/pair + the two-half secret, /v1/revoke, and /v1/devices, replacing the now-superseded 'manual bootstrap only' note. Manual bootstrap remains documented as a fallback for the first device.
) registerSyncRelayDevice upserts with status='active', so any device holding a valid credential could re-pair an existing id — overwriting that device's secret, or flipping a revoked row back to active. Revocation was reversible, which contradicts the ticket's 'cuts access immediately' criterion. /v1/pair now refuses an existing id with 409; each invite already mints a fresh UUID, so the legitimate flow is unaffected.
Two-half pairing secret (deep-link/QR half + hand-typed half, HKDF-combined), device lifecycle routes on the relay, a Sync Devices settings pane listing paired machines with per-device revocation, and local device identity persistence. Reviewed before merge: made /v1/pair insert-only so a revoked device cannot be un-revoked and no credential holder can overwrite another device's secret.
…ion (#46) The engine's SyncRowCrypto needs one symmetric key every paired device agrees on, but each device's relay auth secret is deliberately unique (independent revocation). Generate a 32-byte content key once at bootstrap, seal it under each invite's one-time combined secret, and add SyncPairingRuntime#getRowCrypto() so #46's wiring can derive it.
…46) Adds syncRelay to GlobalSettings, normalized via normalizeSyncRelaySettings (src/shared/sync-relay-settings.ts) and merged in settings-update.ts. The Sync Devices pane now surfaces a relay-URL default and a master on/off switch that pauses syncing without unpairing.
SyncBoardRuntime wraps SyncReconciliationEngine with durable cursor+materialized-view persistence and exposes only two edit entry points (recordWorktreeMetaEdit/recordUiStateEdit), each gated by an explicit allowlist (sync-board-scope.ts) and the remote-host filter from #41. Widens collapseRenamedWorktreeMetaUnits to be generic over the narrower SyncedWorktreeMetaFields projection #46 actually syncs. Covers: stage/link/order/pin/archive changes propagating between two runtimes over a fake relay, dismissal tombstones, remote-host worktrees never leaving the device, a disallowed UI key being dropped even past a type-erasing boundary, restart resuming from the persisted snapshot, and derivation reproducing identically from synced meta + a cached GitHub snapshot.
…tes (#46) - Store gains onWorktreeMetaChanged, mirroring the existing onUIChanged/onSettingsChanged listener pattern, firing from the single setWorktreeMeta choke point so every write path (RPC, MCP, IPC, sort-order) is covered without patching each call site. - SyncPairingRuntime exposes getRelayTransport() alongside getRowCrypto() so the board runtime can be constructed from pairing state. - sync-board-live-wiring.ts subscribes to those listeners, applying the allowlist/eligibility-filtered edits into SyncBoardRuntime and flushing on real edits (coalesced, not a bare in-flight guard —a caller awaiting flushNow() during an in-progress flush now gets a queued follow-up round instead of a silent no-op) and on a timer. Depends only on a small structural store adapter, so it is fully unit-testable without mocking Electron. Problem -> Resolution: a synced worktreeMeta row for an id with no local record is never written to the Store (no orphan entries) since today's UI has no renderer for a peer-only board card; that surfacing is the still-open #24-family board-view work. A remote tombstone is likewise never applied locally to avoid deleting a record for a worktree that may still legitimately exist here under the same id.
Constructs the SyncPairingRuntime once, registers its IPC handlers, and starts startSyncBoardLiveWiring against the live Store — Store already satisfies SyncBoardStoreAdapter structurally, so no adapter wrapper is needed. Sync only runs once GlobalSettings.syncRelay.enabled is true and this device is paired.
Board sync wired through the LWW engine: worktree meta and board-shaped UI keys flow across paired machines, relay URL and a sync on/off switch live in settings, and an explicit allowlist keeps sessions, settings and automation runs machine- local. Remote-host workspaces stay host-authoritative. Adds a fleet-wide row content key, sealed under each invite's one-time two-half secret and AAD-bound to the joining device id.
An unknown deviceId and a known device's bad signature/malformed
header/stale timestamp now all return the identical 401
{error:'unauthenticated'}, closing a device-id enumeration channel via
the response body. The unknown-device path also now runs signature
verification against a fixed dummy secret instead of short-circuiting,
so response time no longer depends on whether the device exists
(timing enumeration). 403 device-revoked is unchanged and still only
reachable after a caller proves possession of the real secret.
…34) handleBootstrap now uses the insert-only registerNewSyncRelayDevice instead of the upsert registerSyncRelayDevice, so two concurrent first callers can't both pass the count()==0 check and have the second one silently overwrite the first device's secret (or reactivate a revoked row, had one already existed). The loser gets a clear 403 already-bootstrapped instead. Deleted registerSyncRelayDevice — it had no remaining production caller — and repointed its test-setup callers at registerNewSyncRelayDevice.
) handleRevoke previously let any active device revoke any other, including the fleet's last active one — after that, /v1/bootstrap permanently refuses too (revoked rows still count against its count()==0 gate), leaving the fleet unrecoverable without hand-editing D1. revokeSyncRelayDevice is now a single atomic UPDATE that refuses when the target is the only active device, returning 409 last-active-device; a concurrent pair of such revokes can't both win. The client and Settings > Sync Devices UI now surface this specific reason instead of a generic failure toast.
Five findings from the branch-wide review: - every pre-signature auth failure now answers identically, in body and in time, so paired device ids cannot be enumerated - /v1/bootstrap uses the insert-only registration; the upsert variant is gone - deleting a worktree now tombstones its synced row end to end (the mechanism existed and was tested, but nothing in the real wiring called it) - revoking the fleet's last active device is refused instead of bricking it
64ix
marked this pull request as ready for review
August 24, 2026 22:00
…es it Spec #29 named 'per-project column order' as a sync unit, but the field did not exist when the LWW layer landed — the engine was built generic over (table, rowId) precisely so the key could be added without touching the merge path. Spec #24 shipped featureBoardColumnOrder, so add it to the allowlist. featureBoardColumnWidth stays machine-local: it is a per-machine layout choice, not board state. Per-repo dismissed ghost ids remain undefined until spec #25.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Multi-machine sync for the board: board + worktree state follows the user across their machines through a self-hosted Cloudflare Worker + D1 relay that stores only opaque E2E-encrypted rows it cannot read. Key/value last-write-wins over the app-state per-key shapes (server-versioned, tombstones, offline queue flushed on reconnect), pairing through the
orca://pairdeep-link/QR flow with a two-half secret, a devices screen with per-device revocation, and end-to-end wiring that keeps machine-local state (sessions, settings, automation runs) and remote-host workspaces (host-authoritative) out of sync scope.No upstream Orca Cloud involvement: the existing
src/main/runtime/relay/*is bound to Orca Cloud identity (director/cells/OrcaCloudAuthConfig), andsrc/relay/**is the unrelated SSH execution daemon. This ships an independent relay undersrc/sync-relay/, reusing only Orca's crypto primitives (src/shared/e2ee-crypto.ts, the HKDF key-schedule pattern) and the pairing/deep-link conventions.Spec & Tickets
Closes #29
Closes #34
Closes #41
Closes #42
Closes #46
Criteria
sync-relay-worker.test.ts"never stores the plaintext substring anywhere the D1 layer can see" — inspects raw D1 rows through realnode:sqlitesync-row-envelope.test.ts— wrong key, version/table/rowId/keyId mismatch, tampered ciphertext; all returnnull, never throwfetchhandler + real SQLite (sync-relay-worker.test.ts,sync-relay-client.test.ts). Not run against live Cloudflare — no credentials in the build env. See QA plan.sync-relay-wire-protocol.test.ts; worker "old client" / "unknown capability" handshake tests; client tolerates a response with noserverCapabilitiesdocs/reference/sync-relay-deployment.md,wrangler.toml,sync-relay-schema.sql; nowranglerdependency addedsync-lww-merge.test.ts(10 cases incl. symmetry);sync-reconciliation-engine.test.tscross-device propagationsync-reconciliation.test.ts(stale queued edit vs pulled tombstone; redelivered older row);sync-relay-worker.test.ts"does not let a stale machine resurrect a tombstoned row"; end-to-end through the real wiring insync-board-live-wiring.test.ts(device A deletes → relay row inspected fortombstone: true)sync-write-queue.test.ts(restart durability, real tmp file);sync-reconciliation-engine.test.tsoffline→queued→restart→reconnect→flushSyncUnitState<T>is(table, rowId)-agnostic; no fields invented — see Decisionssync-worktree-meta-identity.test.ts(single rename + two-hoppriorWorktreeIdschain)sync-relay-pairing.test.ts,sync-pairing-runtime.test.ts,sync-pairing-deep-link.test.ts(encode → transport → decode → halves combined → device authenticates)sync-relay-pairing-routes.test.tsPOST /v1/devices(public metadata only, neversecret_b64);SyncDevicesPane.tsxsync-relay-pairing-routes.test.ts"cuts a revoked device off immediately", plus "cannot un-revoke a device by pairing its id again"sync-pairing-secret-schedule.test.ts— neither half alone reconstructs the HMAC secret; halfA rides the deep link, halfB is hand-typedsync-board-runtime.test.ts(two runtimes over a fake relay);sync-board-live-wiring.test.ts(real wiring layer, two devices)sync-relay-settings.test.ts;GlobalSettings+settings-update.ts; relay URL + "Sync board state" switch inSyncDevicesPane.tsxsync-board-scope.test.ts(explicit allowlist rejectssidebarWidth,terminalScrollbackRows,automationRuns, …);sync-board-live-wiring.test.tssync-board-materialized-view.test.ts+sync-board-runtime.test.ts(ssh:andruntime:host ids excluded viagetWorktreeExecutionHostId)sync-board-derivation-reproducibility.test.ts— unmodifiedderiveWorkflowStageover synced meta + a cached GitHub snapshotChanges
Relay (
src/sync-relay/) — Cloudflare Worker + D1 schema; opaque row storage with a relay-side stale-write guard; HMAC request auth over a per-device secret; device lifecycle routes (/v1/bootstrap,/v1/pair,/v1/revoke,/v1/devices); capability-negotiated JSON wire protocol.Crypto — per-row NaCl secretbox envelope with AAD bound to
table/rowId/version/keyId(digest embedded in the authenticated plaintext, thesealMobileE2EEV2Framepattern); HKDF row-key schedule; two-half pairing-secret combine; a fleet content key sealed under each invite's one-time secret.LWW layer (
src/main/sync/) — deterministic conflict resolution (version, then wall-clock, then stable content tiebreak); tombstones; durable offline write queue; changefeed cursor; rename/rekey folding; remote-host eligibility filter; the board-scoped runtime and its live wiring into the store.Pairing & UI (
src/main/sync-pairing/, settings) — device identity in a hardened secure file; invite/join runtime; Sync Devices pane with QR, manual code, device list, revocation, relay URL and a sync on/off switch.Docs —
docs/reference/sync-relay-deployment.md.Decisions
(table, rowId), so those keys sync for free once they land. Today it syncsWorktreeMeta(stage, links, archived/pinned, orders) plus the board-shapedPersistedUIStatekeys (manualRepoOrder,workspaceStatuses). No placeholder fields invented that would duplicate [Spec] Feature board view #24/[Spec] GitHub inbound ghost cards #25.src/relay/**is the SSH execution daemon andsrc/main/runtime/relay/*is Orca-Cloud-identity-bound — reusing either would reintroduce the cloud dependency the spec forbids. Resolution: independent relay undersrc/sync-relay/, borrowing only crypto primitives and wire-schema style.versionis server-assigned. Resolution: split into caller-declaredversion(AAD-bound, LWW-ordered) and relay-assignedserverSeq(changefeed cursor only).worktreeMetarow for a worktree this machine has no record of. Resolution: not written locally — there is no "foreign card" renderer until the [Spec] Feature board view #24-family board view lands; remote tombstones are likewise not applied to local-only records.Review
A branch-wide
/code-reviewat high effort raised five findings; all five are fixed on this branch:unauthenticatedwhile a known device with a bad signature answeredbad-signature/stale, so a prober could tell paired ids apart despite both being 401. Every pre-signature failure is now identical./v1/bootstrapused the upsert after a separate count check, so a race could overwrite a device's secret and reactivate a revoked one. It now uses the insert-only registration, and the upsert variant is deleted since nothing else called it.recordWorktreeMetaRemoved()was implemented and unit-tested but nothing in the real wiring invoked it, so a deleted worktree's meta lived on at the relay and returned to paired machines.Store.onWorktreeMetaRemovednow drives it (firing only when a record is genuinely deleted, not on the host-preserved SSH branch).Known limitations
/v1/bootstrapis unauthenticated whilesync_devicesis empty — first-come-wins, the same trust boundary as knowing the freshly-deployed Worker URL. Bootstrap immediately afterwrangler deploy; documented in the deployment reference.main/index.ts.QA plan
docs/reference/sync-relay-deployment.mdand apply the D1 schema; bootstrap the first device immediately.sync_rowstable directly: no plaintext board state is readable in any column.pairedAt/lastSeenAt.