Repository navigation
Persist profile state in SQLite with a durable background writer - #22612
Conversation
There was a problem hiding this comment.
ℹ️ No critical issues — the writer/revision protocol, migration admission, secret retention and backup/export paths all held up under a dedicated pass. A few rough edges inline.
Reviewed changes — this run read the full 392-file diff and checked it against the writer protocol, storage admission, secrets, backups, durability awaits, automation-runs storage, runtime reconciliation and packaging wiring.
- SQLite profile-state authority — one
profile-state.dbper profile behind the existingStoreinterface; domain payload rows plus per-row automation runs with a rebuilt projection, preserving normalization, encryption and ownership. - Background writer worker — live SQL runs in a worker; the main thread serializes commands, fences exact revisions and latches the connection on any indeterminate ack, so a committed write can never be misreported as a recoverable failure.
- Durable mutation API — PTY binding, SSH lease, terminal retirement and the codex ledger now await
runDurableMutation, with rollback that preserves newer bindings, secret changes and concurrent presentation edits. - Migration / admission / recovery — fail-closed classification, schema/identity/hash/revision validation, atomic empty-profile publication, versioned exports and rotating backups.
- Offline CLI, orcad/desktop packaging — two new worker entries and unpacked CLI sidecars wired through the build and plain-Node guard.
ℹ️ A valid legacy JSON profile beside any stray SQLite sidecar refuses startup
classifyProfileStateStorage counts profile-state.db-wal / -shm / -journal as database evidence, so a profile with intact orca-data.json plus an orphaned sidecar (or a zero-byte/corrupt .db) classifies as both and is routed into SQLite admission instead of the JSON it still has in hand. Admission then fails closed and the user is told to recover from a backup even though the primary JSON is valid. This is deliberate ("SQLite presence is authority evidence") and pinned by treats an orphaned SQLite %s sidecar as authority evidence with or without JSON, but it is the one way this change can strand a user with recoverable data.
Technical details
# Stray SQLite sidecar blocks a valid JSON profile
## Affected sites
- `src/main/persistence/profile-state/profile-state-storage-classification.ts:20-30` — existence of any `profileStateDatabaseFiles` entry drives `both`/`sqlite-only`.
- `src/main/persistence/profile-state/profile-state-authority-bootstrap.ts:83-99` — `both` → `readAcceptedState` → `openProfileStateDatabaseReadOnly`, which throws `Profile state database does not exist` when only a sidecar survives, then becomes `ProfileStateRecoveryRequiredError`.
- `src/main/persistence/profile-state/profile-state-recovery-required.ts:22-29` — no JSON fallback once database-family files exist.
## Required outcome
- Decide and document whether a sidecar without a primary database should refuse startup outright or be treated as ignorable residue when the primary JSON is independently valid.
## Open questions for the human
- Is refusing startup the intended tradeoff for the "JSON remains for deliberate recovery" contract, and is there a user-facing path to clear an orphaned sidecar without a manual delete?ℹ️ Nitpicks
src/main/persistence/profile-state/profile-state-recovery-copy.ts:23— on non-Darwin the function always does a directcopyFileSyncto the final target, so the exported API is not crash-atomic. Both current callers stage the target and validate/publish later, so this is only a hazard for a future caller.src/main/persistence/profile-state/profile-state-database.ts:104-227—quick_check(and full schema verification) runs on every open, including read-only opens in history GC / recovery; consider whether the per-open cost is acceptable for very large databases.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The single commit since the last review is test hardening plus a few small production tweaks; the previously opened inline threads are untouched by it and remain open, so this is a comment review rather than an approval.
Reviewed changes — reviewed b672ccaace (the only commit since the prior pullfrog review at 26675c1d16), its surrounding call sites, and reran the affected tests.
- Lazy startup milestones —
logStartupMilestonenow accepts() => detailsand snapshotstbefore invoking it; the loading store drops its duplicatelogPersistenceStartupMilestonehelper and uses the shared function. - Recovery-launch diagnostics — failure errors now carry bounded child output (
exitCode,signal,timedOut,outputTruncated, and the trailing 4096 stderr characters) onRuntimeClientError.data. - Background-launch policy — startup recovery-dialog suppression now routes through
isBackgroundLaunch()rather than a rawORCA_BACKGROUND_LAUNCHcomparison. - Schema cleanup — automation-runs table SQL is inlined into
profile-state-database-schema.tsand thecreateProfileStateAutomationRunsTablesSqlhelper is removed, with no dangling references. - Bundle-parity guard — the CLI/main bundle parity test moves to
config/scriptsand reads the exportedelectronViteConfiginput map, asserting exact source paths instead of key presence alone. - Test hardening — durable Store fixture reused in the pty respawn and remote retirement tests, retirement
onPtyExitawaited,launchUntilExitcaptures pre-renderer startup refusals from process creation, and raw Linux dev Electron gets the sandbox opt-out.
Locally verified the new/changed tests pass: config/scripts/cli-main-module-bundle-parity.test.ts (2), src/main/startup/startup-diagnostics.test.ts (4), src/cli/runtime/profile-state-recovery-launch.test.ts (13), and src/main/persistence-loading-store-extraction.test.ts (10).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues in this delta.
Reviewed changes — reviewed 5ef25a7ecc (the only commit since the prior pullfrog review at b672ccaace), traced its call sites in SshRelaySession, and reran the affected suite — including a check that the new regression test fails against the pre-fix logic.
- Live passthrough routing —
quarantineReattachDatanow owns thelivePassthroughcase and streams the frame whenownsPtyRecoveryAttempt(payload.id, pending)holds, instead of the provideronDatahandler short-circuiting toacceptPtyDatawhile recovery-transfer frames were queued intopending.liveDataand never drained. - Regression coverage — the new
keeps source output contiguous while the recovered pane binding waits for diskcase drives a frame through the source-activationtransferToRecoverysink whilepersistPtyBindingis deferred, assertingacceptOutputDatareceives[4, 8, 12]and the recovery lease commits only after the binding resolves. Reverting thelivePassthroughbranch makes it fail ([4]), so it exercises the real fix. - Test tidy-up —
emitSourceFramegaineddata/sinkparameters so the existing cases reuse the helper.
The three prior-review threads (plain-node-entry-guard.ts, stable-owner.ts, profile-state-backup-rotation.ts) anchor paths this commit does not touch, so they remain open and this is a comment review rather than an approval.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues in this delta.
Reviewed changes — reviewed 52481a66ab (the only commit since the 5ef25a7ecc review), traced its call sites and the retirement fence, and reran the affected suites.
- Durable-binding retirement on spawn-time exit — a new
registerPersistedPtySpawnwrapsruntime.registerPty(...); when registration throwsagent_session_exited_during_startand the runtime holds an earnedexitedverdict, it awaitsretirePersistedStablePaneOwner(...)before rethrowing, so a terminal that dies during the durablepersistPtyBindingwrite no longer leaves a persisted binding that would resurrect the closed pane. - Both spawn commit paths now use it —
commitRuntimePtySpawnandcommitPtyIpcSpawnawait the helper in place of a directregisterPtycall; the runtime path also destructuresctx.hostSessionBindinginto locals (no behavior change). - Coverage —
pty-spawn-exit-durability.test.ts(8 cases) exercises runtime and IPC controllers on local and SSH connections, proves a replacement binding (new and same ptyId, new incarnation) survives while retirement waits, retains the binding when loss of contact supplies no process-exit proof, and holds the rejection until SQLite cleanup completes.
The fence in retirePersistedStablePaneOwner matches on current.ptyId/current.incarnationId, so a replacement incarnation wins; the unverifiable case correctly leaves the binding alone. Affected suites rerun green (pty-spawn-exit-durability 8, spawn-commit-pty-size, spawn-reattach-size-cache, orca-runtime-terminal-retirement, spawn-commit-ssh-lease-cardinality 29). The three prior-review threads anchor paths this commit does not touch, so they remain open and this is a comment review rather than an approval.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues in this delta.
Reviewed changes — reviewed 30664b6b66 (the only commit since the prior pullfrog review at 52481a66ab), traced every registerPersistedPtySpawn call site, and reran the affected suites.
- Synchronous successful registration —
registerPersistedPtySpawnis no longerasync; on success it callsruntime.registerPty(...)and returnsundefinedsynchronously, so callers no longer yield a microtask before the remaining spawn publication. The confirmed-exit retirement path returnsretirePersistedStablePaneOwner(...).then(() => { throw error })(Promise<never>), while the non-retire throw paths still throw synchronously. - Callers updated —
commitPtyIpcSpawnand bothcommitRuntimePtySpawnsites now await only the returned rejection promise, which is behaviorally equivalent to the oldawaiton the retirement path and removes the success-path yield. - Telemetry extraction — the spawn
agent_startedblock moved verbatim intorecordPtySpawnTelemetry(spawn-telemetry.ts); both call sites are unchanged in effect. - Tests — the unverifiable case now asserts a synchronous throw, the retirement case consumes the returned promise, and a new case pins the synchronous success return (it fails against the pre-change
asyncversion).
Verified locally: pty-spawn-exit-durability (9), spawn-commit-pty-size (2), spawn-reattach-size-cache (5), and spawn-commit-ssh-lease-cardinality (8) all pass. The three prior-review threads (plain-node-entry-guard.ts, stable-owner.ts, profile-state-backup-rotation.ts) anchor paths this commit does not touch, so they remain open and this is a comment review rather than an approval.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found in this delta.
Reviewed changes — reviewed 1d6e677a1a (the only commit since the prior pullfrog review at 30664b6b66), traced the binding write path and the crash-hydration reconnect plan, and confirmed the new regression test fails against the pre-fix source.
- Activity recorded with the binding —
applyPtyBindingnow appends the binding's worktree tosession.activeWorktreeIdsOnShutdownwhen that list is present and omits it, so an acknowledged spawn or reattach survives a crash before the renderer writes its own activity snapshot; an absent list keeps the existing derive-from-tabs semantics. - Fast lane stays strict —
evaluatePtyBindingFastLaneadds aninactive_worktreemiss under the same condition, so an otherwise-matching durable reattach takes the write path and repairs the missing activity instead of being skipped. - Rollback — the fieldwise rollback restores the activity list on a known write failure; the durability test asserts the in-memory session returns to its pre-write value.
- Regression coverage —
pty-binding-async-durability.test.tspins that activity lands only after the SQLite transaction commits and that a same-binding reattach repairs the list exactly once; the newterminal-binding-crash-hydration.test.tsdrivesapplyPtyBinding→ hydrate →reconnectPersistedTerminalsfor repo and folder workspaces, with and without a pre-existing tab row. Reverting the production change fails all four cases.
The three prior-review threads remain open on files this commit does not touch, so this is a comment review rather than an approval. Local runs of the three affected suites pass (pty-binding-fast-lane 4, pty-binding-async-durability 11, terminal-binding-crash-hydration 4).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Reviewed the additional observations from the initial review as well:
All three inline threads are addressed in ac4a8c0. Full local typecheck, CLI/Electron builds and the changed-code quality gate pass. The Bun PR is being rebased onto this correction for a combined ad-hoc build. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — reviewed ac4a8c0bc3 (the only commit since the prior pullfrog review at 1d6e677a1a), traced the new durability branch through runDurableMutation, the guard/parity wiring and the backup-rotation lifecycle, and reran the affected suites. This commit retires all three previously open threads.
- Gated the retirement fast path on durability —
retirePersistedStablePaneOwnernow returnspersist: 'if-dirty'when the pane is already absent in memory, andrunDurableMutationskips the write only whenlastDurableWriteGeneration >= writeGeneration. A renderer removal still waiting for its debounced flush is therefore forced to disk before retirement is acknowledged, while an already-durable removal keeps the no-write fast path. - Consolidated the CLI plain-Node guard — the eleven sidecar inputs plus the
agent-hooks,codexand keychain entries now share one exportedCLI_MAIN_ENTRY_NAMESlist used by both the Rollup inputs and the guard; a parity test asserts everysrc/main/*module the CLI imports is inGUARDED_ENTRY_NAMES, and a per-entry test drives direct, static and dynamic Electron requires. - Tightened backup-rotation idleness —
assertIdle()now checks the wholependingoperation instead of thecopyingflag, so synchronous quarantine is fail-fast across queueing, snapshot copy and retention pruning. - Added regression coverage —
pty-retirement-async-durability.test.tsuses real SQLite to pin delayed acknowledgement, failure/retry and the already-durable no-write path for local and SSH owners; the backup suite adds the queued-before-start and blocked-prune intervals.
Locally verified: reverting the stable-owner.ts line to persist: false fails 4 of the 6 new retirement cases (both hosts, both delayed-ack cases); with the fix, pty-retirement-async-durability (6), profile-state-backup-rotation (9), plain-node-entry-guard (26) and cli-main-module-bundle-parity (3) all pass.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — reviewed the two commits since the prior pullfrog review at ac4a8c0bc3: 42f874d341 (dedup refactor) and 60cc397e89 (drain admitted terminal mutations, restore failed retirements), traced the retirement path through runDurableMutation and the maintenance drain, and confirmed the new regression suite fails against the pre-fix admission check.
- Admitted mutations survive finalization —
runDurableMutationnow sets adurableMutationPhasefor the duration of its synchronousmutate/rollbackcallbacks, andsetWorkspaceSessiontreats that as permission to publish a snapshot that was admitted before maintenance began. The relaxation is scoped to the callback (the phase resets before the disk await),writesFrozenstill throws unconditionally, and the before-unload stage path still passesfalse, so no new renderer snapshot can slip in. - Failed retirements restore without rebasing — on a failed retirement write, the fieldwise rollback publishes the merged session directly instead of routing through
setLocalWorkspaceSession/setHostWorkspaceSession, whose runtime-authored-field rebasing would re-apply the retirement the rollback is undoing. The merged object derives from the live session, so newer edits are preserved. - Refactor is behavior-preserving —
isRecordis imported fromprofile-state-document-validation.ts(identical body) andreadAgentHookSettingsFromJsonruns both branches through the sharedreadAgentHookSettingsFromSettingsValuecoercion. - Regression coverage —
profile-state-pty-retirement-finalization.test.ts(18) pins retirement admission across running/maintenance/freeze/final on local and SSH, a failed-write rollback that keeps a neweractiveTabId, and phase reset after throwing callbacks.
Verified locally: reverting the local admission change fails 3 cases (maintenance/freeze/final); all 18 pass with it. The three previously opened threads remain resolved.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
9622ea0 to
1b2e701
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — re-reviewed the two commits added since the prior pullfrog review at 60cc397e89 (both rewritten by a later rebase onto main@bf40d35b0b; the earlier docs commit and the behavior-preserving deployment refactor have no behavioral surface): ba791bb4cf (profile maintenance recovery + shutdown compatibility) and 1b2e70166d (durable automation writes). Read both commit diffs end to end, traced the maintenance/durability call sites, and ran the new suites: automation-run-writer (7), automation-worker-durability (18), headless-dispatch-durability (4), profile-state-maintenance-recovery (7), profile-state-maintenance-compatibility (3), profile-state-worker-coordination (14), profile-state-backup-temporary-files (2) and profile-state-access (26) — all pass.
- Recoverable profile maintenance —
beginProfileStateMaintenancenow wraps the pause in acanResumeFailedMaintenancecatch that re-proves the authority writable and unfreezes on a known write failure, and freezes/closes on an indeterminate or already-frozen state;pauseProfileStatedrains backup work, flushes without the caller's signal so an already-dispatched commit keeps a known outcome, publishes the JSON compatibility export, then freezes. - Owner identity beyond hostname — new
profile-state-access-identity.tsrecords kernel boot identity and process-start identity, soownerExitedreclaims a reused PID only when the boot matches and the start identity differs, and treats an unavailable identity as unverifiable. - Orphaned backup cleanup + cancellation — backup temp files carry a boot/namespace owner scope;
removeAbandonedProfileStateBackupFilesremoves only old files whose owner PID is proven exited, andrunProfileStateBackupWorkeraccepts an abort signal and removes its temp files after the worker exits. - Fatal mutation latch — a throwing
mutate/rollbackcallback latchesfatalMutationError, freezes writes and closes the authority; every later sync/async write rethrows it instead of persisting a partial edit. - Shutdown compatibility — normal quit runs
flushFinalOrThrowAsync({ exportJsonCompatibility: true })and releases profile admission only after the writer closes; orcad keeps admission when runtime teardown fails; the update-quit cleanup budget for required exports is 90s. - Durable automation writes — every automation run/definition write awaits
flushPendingOrThrowAsyncbefore announcing or returning, andrequestAutomationDispatchrechecks the definition, destination and run status after the acknowledgement wait, cancelling on stop or removal.
ℹ️ Every normal quit now serializes the full profile to JSON
main-process-quit.ts previously gated exportJsonCompatibility on an in-progress update; it now passes true unconditionally, so a migrated (SQLite-only) profile writes a whole-profile JSON compatibility export on every quit. That is a deliberate downgrade-compatibility choice, pinned by the renamed exports a normal quit for an older build after sessions and settings changed test, but it is a new per-quit cost that scales with profile size and narrows the "migrated profiles write only to SQLite" framing in the description. Worth confirming the tradeoff is intended for large profiles.
Technical details
# Per-quit full JSON export
## Affected sites
- `src/main/startup/main-process-quit.ts:203-216` — `flushFinalOrThrowAsync({ exportJsonCompatibility: true })` on every `will-quit`.
- `src/main/startup/main-window-core-services.ts:129-132` — the update-quit hook now relies on the compatibility export to carry the recovery export too, so the per-quit and per-update paths both serialize the whole profile.
## Required outcome
- Confirm (or gate) that a whole-profile JSON serialization on every ordinary quit is intended; if the compatibility window only matters around updates, the prior `updateQuitInProgress` gate kept normal quits JSON-free.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — reviewed the one commit added since the prior pullfrog review at 1b2e70166d: 799dd38db0 (reconcile manual automation requests interrupted before launch). Read the commit diff and the reconciliation flow, and ran run-completion-watcher (10) and retained-run-reconciliation (5) — both pass.
- Stranded pending manual runs are closed out —
reconcileRetainedRunsnow also stagespendingruns whosetrigger === 'manual', anddescribeStrandedAutomationRungained apendingbranch returning "Orca stopped before this manual run could launch." A pending manual run left by a dead process cannot be re-dispatched in a new session, andresolveRunTerminalreturnsnullwithout aterminalPaneKey, so the run is staged and stranded after the surface-settle grace. - Scheduled pending runs stay retryable — the filter excludes scheduled
pendingruns, and the test pins thatpendingScheduledremainspendingwhilependingManualbecomesdispatch_failed.
The change matches the existing dispatching handling: the stale captured run object never resolves a pane, so the reconciler correctly waits for the terminal surface to report ready before stranding. No concerns.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — reviewed 04ba64fce1 (the only commit since the prior pullfrog review at 799dd38db0), traced both terminal-close refusal paths through runDurableMutation, and confirmed the two new regression cases fail against the pre-fix source.
- Expected refusals no longer freeze profile persistence —
commitHeadlessTerminalTabRetirement(terminal_pane_owner_changed,workspace_session_unavailable,terminal_tab_pinned,tab_not_found) andclearWorktreeTerminalResumeRecords(terminal_close_incomplete) now return{ value: new Error(...), persist: false }instead of throwing inside the mutation callback. A throw there runsstopAfterFailedPrimaryStateMutation, which latchesfatalMutationErrorand freezes every later write, so a merely refused tab close used to permanently stop profile saving. The returnedErroris re-thrown, so callers still observe the refusal. - Contract documented —
runDurableMutationnow states the rule: expected refusals returnpersist: false, thrown callbacks are treated as partial-state corruption. - Regression coverage — the pinned-close case and a new worktree-teardown case assert
flushPendingOrThrowAsync()resolves after the refusal. Both fail pre-fix withCannot flush while persistence is finalized; at headacknowledged-terminal-tab-retirement(13) andorca-runtime-terminal-retirement-host-partition(8) pass.
The change matches the refusal idiom already used by pty-binding-persistence.ts and ssh-pty-consumer-recovery.ts, and no other terminal-close refusal path still throws inside a durable mutation.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — reviewed the two commits added since the prior pullfrog review at 04ba64fce1: 9c87748d75 (remove compatibility exports after clean profile shutdown) and 3268a67bfe (observe SQLite authority in restart and startup journeys). Both are E2E-test-only; read the commit diffs end to end and checked every assertion they add or move.
- SQLite-authority reads in the parked-scrollback journey —
readOnDiskPartitionsnow reads committed state throughreadPersistedProfileState(opensprofile-state.dbread-only under a runtime admission) instead of globbing retainedorca-data.jsoncompatibility exports, so the load-bearingruntimePartitionHoldsCapture/localPartitionDidNotKeepCaptureassertions read the same authority production restores from. Runtime admissions are shared participants, so reading while the paired app is still live remains valid. - Per-profile seeding in the launch-budget journey — each baseline/populated sample now gets a fresh session and has plugins seeded before its first migration into SQLite, replacing the shared session that re-seeded an already-migrated profile (which would have had no
orca-data.jsonto edit); the inert-plugin marker assertion moved inside the loop so it runs per launch. - Clean-shutdown compatibility assertions — the terminal-restart journey now asserts the compatibility JSON contains the created automation after a clean close, and refreshes/deletes the JSON mirrors only after the clean-maintenance export, keeping the later
defaultJson/targetJson-absent assertions that prove a SQL-only launch.
No inline comments: the delta has no production code, and no assertion was loosened or made vacuous.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Important
The new snapshot coalescing can silently drop a getter-only in-memory edit while an awaiting durability flush reports success. Reproduced against e5f44ea87d; details inline.
Reviewed changes — reviewed the two commits since the prior pullfrog review at 3268a67bfe: fffcfdbbcf (coalesce queued durability snapshots) and e5f44ea87d (keep the writer usable after export preparation failures). Read the write/flush/worker paths around the change and ran the new and affected suites.
- Queued snapshot batching —
enqueueWritenow reuses an in-flightqueuedSnapshotbatch, folding inskipIfCleanand the latestpendingSnapshotFileWorkand returning that batch's completion;enqueuePrimaryStateOperationclears the queued batch so a durable mutation, export or checkpoint starts a new one, so concurrent flushes share a single worker capture. - Preparation failures stay recoverable — a new
ProfileStateExportPreparationErrormarks failures raised before SQLite acceptance or canonical JSON is touched, so the worker no longer latchesstoppingforexport-compatibility/closeon such a failure, while an indeterminate underlying cause still surfaces through the recursive outcome derivation.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — reviewed ca5ab03788 ("fix: preserve getter edits across coalesced profile flushes"), the only commit since the prior pullfrog review at e5f44ea87d. Traced the merge branch through writeProfileStateInWorker and prepareSelectiveProfileStateWrite, checked every enqueueWrite caller, and confirmed the new regression cases fail against the pre-fix source.
- Merged explicit flushes now force a full capture — the queued batch's capture carries a
fullCheckpointflag, andqueued.capture.fullCheckpoint ||= !queued.capture.skipIfCleanruns after the existingskipIfClean &&=upgrade. Any batch that absorbs a non-skipIfCleandurability waiter — explicit-joins-debounce or debounce-joins-explicit — nullsdirtyProfileStateDomainsimmediately before capture, so the untracked getter-only edit (getWorkspaceSession().activeTabId = …, which marks no domain dirty) is serialized instead of being dropped by a selective write. - Debounce-only batches stay selective — two debounced saves that coalesce keep
skipIfCleantrue, so the full-capture trigger does not fire; the new case assertswriteCompleteSerializedDomainsis never called. - The dirty-set reset reads the batch, not the call —
primary-state-writes.ts:205now consultscapture.fullCheckpoint, so a merge that lands after the batch was enqueued still upgrades the capture. Non-batchable writes (final checkpoints, signal-bearing flushes) are unaffected: they cannot merge and theircapture.fullCheckpointmirrorsoptions.fullCheckpoint. - Regression coverage — the batching suite adds both merge orderings for the getter-only edit, the explicit-then-debounce case, and the debounce-only selective check; the 21-waiter coordination regression now pins exactly one full serialization across two captures. Removing the
fullCheckpoint ||=line fails five cases (both getter orderings, explicit-then-debounce, the shared-failure test that moved towriteCompleteSerializedDomains, and the full-capture assertion), so the tests exercise the real fix.
Verified locally: profile-state-write-batching (11) and profile-state-worker-coordination (14) pass at head; pnpm tc is green.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — one narrow locking edge case inline.
Reviewed changes — re-reviewed the single commit added since the prior pullfrog review at ca5ab03788: 353afda6e3 (preserve profile saving through cancellation and recovery failures). Read the commit diff end to end, traced the durability/lifecycle call sites, and ran the new and changed suites (11 files, 134 tests pass).
- Caller cancellation stops only the waiter —
enqueueWritedrops thesignalabort listener that calledprofileStateAuthority.abort()and returnswaitForPromiseWithSignal(completion, signal); an abandoned waiter rejects while the admitted write keeps its place inruntime.pendingWrite, so the final checkpoint still joins it. - Quit survives a known maintenance failure —
flushFinalOrThrowAsyncawaitspendingProfileMaintenance, swallows a known failure only when the store was re-admitted, then drains and runs the final full checkpoint before closing;canResumeFailedMaintenanceno longer treatsquitFlushStartedas preventing resume. - Profile switch stays writable through relaunch — the switch handler uses
flushActiveProfileBeforeRelaunch(plain flush, no maintenance pause), so the live source writer lets SSH-detach and other cleanup writes reach the source profile's final checkpoint. - Cross-profile move journal — move intent types/validation move to
profile-project-move-record.ts; startup replays only intents involving the active profile, and offline rollback refuses while a move is unresolved. - Startup diagnostics — newer schemas raise
newer-schema(no rollback instructions), unsupported hard-link publication raisespublication-unavailablewith actionable text, and pre-ready desktop launch failures now show a native error dialog. - Owner reclamation — new machine identity plus directory fsyncs, and a published owner is removed when a later durable publish step fails.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
353afda to
7306dd2
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — re-reviewed the two commits added since the prior pullfrog review at 353afda6e3 (the branch was rebased, so that head is now 345e165fc8 with identical content): 29b06b3263 (keep cloned host identities from reclaiming live profile owners) and 7306dd23 (await durable state in the pane restart test harness). Read both commit diffs end to end, traced ownerExited against every reclamation case, and ran the affected suites.
- Cross-host machine-id collisions now fail closed —
ownerExitedgainssameHost = owner.host === hostname(); the foreign-host guard becomes!sameBoot && !sameHost, and the reboot shortcut now requiressameHost && sameMachineinstead ofsameMachinealone. A second host sharing a cloned machine id and a profile directory can no longer reclaim a live owner through a differing boot identity, while a same-host reboot with a matching machine identity still proves exit. This directly addresses the prior inline finding. - Placeholder Linux machine ids are rejected —
/etc/machine-idis only accepted when it matches^[a-f0-9]{32}$and is not all zeros, so the uninitialized placeholder value can no longer be treated as a stable machine identity. - Regression coverage — the new
profile-state-access-identity.test.tspins the Linux validation cases, and the new "does not reclaim another host with a cloned machine identity" case runs with and without a readable current boot identity. Both fail against the pre-fix shortcut (which returnedtruefrom the matching machine id). The wall-clock test now callsreclaimExitedOwnerdirectly so Linux platform emulation does not perturb host publication/fsync flags; it still assertsunverifiablewith the owner retained. - Test-only harness line —
pty-pane-restart-replace.test.tsadds arunDurableMutationfake that forwards to its callback. No production surface.
Verified locally: profile-state-access (32), profile-state-access-identity (5) and pty-pane-restart-replace (6) pass. All prior Pullfrog threads are resolved.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — re-reviewed 0ab0fc7c96 ("fix: show Linux startup failures after Electron is ready"), the only commit since the prior pullfrog review at 7306dd23. Read the commit diff end to end, traced the deferred-dialog branch against index.ts's preflight gating, and ran the affected suite.
- Linux startup failures now surface after ready — the inline failure path moved into a new
handleMainProcessPreflightFailure, which on Linux defersdialog.showErrorBox+app.exit(1)toapp.whenReady(), with a rejection handler that exits without a dialog. Other platforms show and exit immediately; background and serve launches stay console-only and immediate. - Admission release is unchanged in effect — the handler still clears
desktopActivationGate, releases the profile-state admission (warning rather than throwing) and exits;runMainProcessPreflightstill returnsfalse, soindex.tsinstalls no ready handlers and no window work races the dialog. - Coverage — the darwin case pins the platform so it keeps asserting the immediate dialog, and new cases cover Linux deferral, readiness rejection, and background/serve. The deferral and rejection cases fail against the pre-fix immediate-dialog code.
Local: browser-process-user-agent-ordering (9) passes.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — re-reviewed d1fd4b3cc0 ("fix: require live orphan evidence before adopting a terminal"), the only commit since the prior pullfrog review at 0ab0fc7c96. Read the commit diff end to end, traced the ownership verdict through the activation gate and adoption sweep, and reran the affected suites (including a check that the new regression case fails against the pre-fix guards).
- Explicit orphan evidence is now required to mint —
indexLiveTerminalSurfaceOwnersno longer dropsorphanedrows. It mapsorphaned === true && connected === trueto a new'unowned'verdict (a disconnected orphan staysnull), and only folds non-orphan rows throughtoSurfaceOwner. The conflict check compares the'unowned'/nullsentinels without apaneKey, so conflicting owned/orphan rows still collapse tonull. - Adoption mints only on
'unowned'—adoptLiveWorkspacePtySurfacesnow declines any other verdict (owned handled above,null, or absent) instead of treating absence from a readable census as unowned. That closes the case where a stale inventory named a retired predecessor PTY and the sweep forked a live agent onto a second empty surface. - Census reads require fresh liveness —
readWorktreeLiveTerminalSurfaceOwnersaddsrequireFreshPtyLiveness: true, so a row the host cannot confirm live is never adopted, and the doc comment now states that only'unowned'proves a live PTY has no surface. - Regression coverage — the new "does not adopt a predecessor after the relay restarts between activation inventories" case holds the session inventory pending, rebinds the pane to a replacement PTY, then resolves the old inventory and asserts nothing is minted and the replacement binding survives. New index cases cover disconnected orphans, legacy synthetic surfaces, and conflicting rows. Existing gate tests now pass explicit
surfaceOwnersto preserve their minting assertions.
Verified locally: worktree-agent-activation-gate (35) and worktree-live-terminal-surface-owners (16) pass. Reverting both adoption guards to the pre-fix form fails 7 gate cases, including the new predecessor case, so the tests exercise the real change. No open Pullfrog threads.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — reviewed cb78ca31a0 ("test: distinguish transient relay descriptors from accumulation"), the only commit since the prior pullfrog review at d1fd4b3cc0. It is test-only: one E2E spec, no production code.
- Extracted the per-relay fd probe —
readRelayFdCount(target, relayPid)wrapsset -o pipefail; ls /proc/<pid>/fd | wc -l, andsampleRemoteResourcesnow reduces the relay table through it. - Settles transient FDs before failing — when the last reconnect sample exceeds
first.relayFdCount + 4, the spec attachesls -l /proc/<pid>/fdpluspsdiagnostics and polls for up to 10s for the count to come back under budget, re-reading the relay table each tick. Real per-cycle accumulation never settles and still fails, so the bound was not weakened into a tautology.
The extracted helper drops the old inline 2>/dev/null and || '0' tolerance, so a vanished relay directory now throws instead of counting 0; every caller reads its pid from a freshly taken process snapshot, so that failure-mode change is sound. No prior open Pullfrog threads.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — reviewed 0c8599326e ("fix: withhold orphan claims until terminal spawn admission settles"), the only commit since the prior pullfrog review at cb78ca31a0. Read the commit diff end to end, traced the spawn lease through the worktree mutation lock and the coordinator census path, and confirmed the new regression tests fail against the pre-fix source.
- Orphan claims withheld during spawn admission —
buildPtyTerminalSummarynow throwsterminal_surface_ownership_unavailablewhen a PTY is orphaned and either its ptyId has a pending registration or its worktree has an active spawn (terminalMutationLock.hasActiveSpawns(runtimeWorktreeIdentityKey(pty.worktreeId))), so a live-but-unbound PTY can no longer be reported as an adoptable orphan while its durable binding write is in flight. The lock key matchesacquireWorktreeTerminalMutation's. - Coordinator defers instead of spawning —
listAvailableWorkerTerminalsreturnsnullon a failed census (was[]), anddispatchReadyTasksreturns early onnull, retrying the next tick rather than creating a replacement worker from an untrustworthy census. The early return leavesphaseat'dispatching', matching the existingslotsAvailable <= 0path. - Lock exposes active-spawn state — new
hasActiveSpawns(key)reads the entry (false when absent) without mutating it. - Regression coverage — new
terminal-list-pending-pty-registration(7; local/SSH × binding/provider admission, committed surface survives a competing spawn, unrelated workspace still reports orphan, recovery after cancel plus release) andcoordinator-terminal-census-unavailable(2; defer then reuse the existing worker for both ownership and liveness errors), plushasActiveSpawnsassertions. Removing the guard/null-check fails every terminal-list rejection case and both coordinator deferral cases.pnpm tc:nodegreen.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — re-reviewed the commits since the prior pullfrog review at 0c8599326e: 27bc199e63 (test-only terminal-mount wait, no production surface) and 747b8ed778 (route SSH reconnects after early connect replies). Read the commit diff end to end, traced the bridge's authority/routing paths, and confirmed the new routing suite fails against the pre-fix source.
- Bridge-local routed authority —
direct-ssh-state-ipc-bridgenow records the last authority it routed inroutedAuthorityByTargetand derivespreviousAuthorityfrom it instead of from the store. When a connect reply has already written the connected state into the store, the matching push is no longer misread as a same-authority wake, sorouteDirectSshConnectedStatetakes the changed-authority branch andrequestReconnectactually fires. - Cleanup kept in step — the routed entry is deleted when the target reaches a connectable status and when a removed target is reconciled, alongside the existing
reconnectAuthorityByTargetclears. - Regression coverage — the new
direct-ssh-connect-reply-routingsuite (10) exercises reply-first and push-first orderings, initial hydration, partial-authority reconciliation, disconnect/error cleanup, and per-target isolation. Reverting to the store-derivedpreviousAuthorityfails 5 of the 10 cases, and a duplicate same-authority push still routes exactly once. - E2E diagnostics — the reconnect-pane-restore spec now loops the reconnect three times and attaches renderer/PTY/remote-process observations on failure via the new helper. Test-only.
Locally verified: direct-ssh-connect-reply-routing.test.ts (10) passes at head; swapping in the 0c8599326e bridge fails 5 cases.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
8689831 to
6d91d31
Compare
|
Run failed. View the logs →
|
6d91d31 to
ca8620e
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — re-reviewed the four commits added since the prior Pullfrog review at 747b8ed778 (the branch was rebased, so that content is now 8cfb592832): 5f0ee154e3 (preserve profile saving and terminal ownership through recovery), 19057c7539 (test-only Bun-independent qualification), 7034db2f7f (preserve live terminals through failed binding saves) and ca8620eda4 (name flush policies / simplify store setup). Read the range diff end to end and the full PR diff, traced the persistence worker and terminal-lifecycle call sites, and dispatched two domain reviewers (persistence export-failure classification, terminal-lifecycle ownership) — both returned no confirmed issue.
- Failed binding saves keep the terminal and drop only the dead incarnation — reattach/adopted spawns now take ownership before the durable write (
admitPtyReattachOwnership) and are never shut down on a failed save; a fresh spawn is shut down only whileisCurrentPtyExit, and the shutdown carriesexpectedIncarnationId, so a replacement that lands during the save or during the shutdown survives. IPCcommitPtyIpcSpawnnow swallows a confirmedagent_session_exited_during_startand resolves the reservation so the renderer drains buffered output and exit, while the runtime/headless path still rejects. - Restored history is seeded before the first disk await — the spawn commit is split into
persistPtyIpcSpawnCommit(disk) andpublishPtyIpcSpawnCommit(in-memory publication), andseedHeadlessTerminalFromSpawnResultruns first so live output appends to the restored scrollback rather than replacing it. - Export failures stay recoverable only when the SQL outcome is known — the worker now encodes export/close failures with
forceIndeterminate = (command === 'close')andProfileStateExportPreparationErroris gone. Verified the SQLite write/read wrappers convert an ambiguous COMMIT or failed ROLLBACK intoProfileStateIndeterminateWriteError/ProfileStateReadRollbackError, both classifiedindeterminate, so a genuinely uncertain export still retires the writer; the new real-worker fault suite covers both the recoverable and indeterminate paths. - Ordinary flushes stop draining hourly backups —
flushCurrentStateAsyncnow drains backups only forfinal || profileMaintenancePending; the flush still settles its own admitted write, and final/maintenance paths still drain. - Retirement concurrency is fenced by a token —
pendingPtySurfaceRetirementsByPtyIdreplaces the lifecycle-generation check, and is cleared byonPtySpawned,invalidateAllHandlesForPtyandregisterPty, so a replacement invalidates an in-flight retirement. - Host reclamation hardening — macOS process identity is read in UTC and compared within
START_TIME_TOLERANCE_MS; owner publication reuses the sync Windows retry rename; the async durable-write path now has a bounded Windows retry that rechecksisCurrentbefore publishing. --current-jsonrecovery + stopped-saving signal — a new explicit CLI selector adopts the currentorca-data.json(revisionnull, both authorities archived), startup text explains it, and desktop users get a native "Saving stopped" dialog routed throughonPersistenceFailure.- Refactor is behavior-preserving — every
flushCurrentStateAsynccall site maps to the same effective flags, store construction keeps the authority-close-on-throw boundary, and the automation-run deletion drops an equivalent set.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — re-reviewed 80e8a8669a (the only commit since the prior pullfrog review at ca8620eda4), which is test-only: it broadens the E2E main-process evaluation retry predicate and parameterizes its unit test. No production code changed. Read the commit diff end to end, verified the new message against Playwright 1.63.0's Chromium error rewrite, and ran the suite.
- Collected evaluation promises now retry —
isTransientMainEvaluateErroralso matches'Resulting promise was garbage collected'alongside'Execution context was destroyed'. Confirmed innode_modules/playwright-core/lib/coreBundle.js(Playwright 1.63.0) that Chromium'srewriteErroremits exactly that string when the underlying CDP error is"Promise was collected", and that the already-matched string is its sibling fallback for any other non-JS, non-session-closed CDP failure. Both matched messages are therefore the transient startup artifacts, while a genuinely closed session throws a distincthas been closedmessage and still propagates on the first attempt. - Both messages now covered by parametrized tests —
transient()became atransientMessagesarray; the retry and bounded-retry (calls === 5) cases run overExecution context was destroyedand the collected-promise message viait.each, and a new case pinscalls === 1for a closed application. Local:electron-main-evaluate-retry.unit.test.ts(7) passes.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…acking Dormant foundation for the T2 SSH core port of #16741 (design D9.3). No production module imports it yet; only tests do, so SSH behavior is unchanged. The next T2 slice wires SshConnection.exec/sftp/channel opens and forwarded sockets through it. Adds: - SshConnectionWorkLedger: tracks local operation and channel lifetimes per connection. fenceForReset closes admission (except work nested under an already-admitted operation and one exactly-identified control channel) and drain() waits for the rest, failing sticky on any failure or unverifiable opening observed after the fence. Channel closure is local lifetime evidence only, never proof that a remote process exited. - trackSshConnectionChannelLifetime / openTrackedSshSocket: bind an opened channel or socket to its ledger entry and settle it only on 'close' ('end', 'error' and the destroyed flag are not closure). Porting note (source: #16741 head a68b6f3, merge-base 277c289; T2 per the #24137 track manifest): - Taken verbatim: ssh-connection-work-ledger behavior and tests, ssh-forward-socket-admission.test.ts, openTrackedSshSocket. - Adapted: the ledger no longer calls assertProfileLifetimeAdmission on every admit. That module is an opt-in native-addon profile lock (addon dropped in T0) that overlaps the SQLite authority from #22612; callers inject their own admission check through the existing constructor argument instead (SshConnection will pass its disposed check). The broad `object` resource type became SshConnectionWorkChannel (on/once/ removeListener), and trackSshConnectionChannelLifetime uses a type guard instead of a cast, so a value without removeListener is now reported unverifiable rather than tracked. Added ssh-connection-channel-lifetime tests, since #16741 covered it only through SshConnection. - Dropped: none in these files. - Not in this slice: SshConnection wiring (ssh-connection.ts), forwarded channel lifetime (T4), upload session lifetime (T6), profile lifetime admission/lock/participation (needs a D9.4 decision against #22612). No wire change: nothing is sent to relays or clients.
…acking Dormant foundation for the T2 SSH core port of #16741 (design D9.3). No production module imports it yet; only tests do, so SSH behavior is unchanged. The next T2 slice wires SshConnection.exec/sftp/channel opens and forwarded sockets through it. Adds: - SshConnectionWorkLedger: tracks local operation and channel lifetimes per connection. fenceForReset closes admission (except work nested under an already-admitted operation and one exactly-identified control channel) and drain() waits for the rest, failing sticky on any failure or unverifiable opening observed after the fence. Channel closure is local lifetime evidence only, never proof that a remote process exited. - trackSshConnectionChannelLifetime / openTrackedSshSocket: bind an opened channel or socket to its ledger entry and settle it only on 'close' ('end', 'error' and the destroyed flag are not closure). Porting note (source: #16741 head a68b6f3, merge-base 277c289; T2 per the #24137 track manifest): - Taken verbatim: ssh-connection-work-ledger behavior and tests, ssh-forward-socket-admission.test.ts, openTrackedSshSocket. - Adapted: the ledger no longer calls assertProfileLifetimeAdmission on every admit. That module is an opt-in native-addon profile lock (addon dropped in T0) that overlaps the SQLite authority from #22612; callers inject their own admission check through the existing constructor argument instead (SshConnection will pass its disposed check). The broad `object` resource type became SshConnectionWorkChannel (on/once/ removeListener), and trackSshConnectionChannelLifetime uses a type guard instead of a cast, so a value without removeListener is now reported unverifiable rather than tracked. Added ssh-connection-channel-lifetime tests, since #16741 covered it only through SshConnection. - Dropped: none in these files. - Not in this slice: SshConnection wiring (ssh-connection.ts), forwarded channel lifetime (T4), upload session lifetime (T6), profile lifetime admission/lock/participation (needs a D9.4 decision against #22612). No wire change: nothing is sent to relays or clients.
…dger (#16741 T2) (#24210) * feat(ssh): add the SSH connection work ledger and channel lifetime tracking Dormant foundation for the T2 SSH core port of #16741 (design D9.3). No production module imports it yet; only tests do, so SSH behavior is unchanged. The next T2 slice wires SshConnection.exec/sftp/channel opens and forwarded sockets through it. Adds: - SshConnectionWorkLedger: tracks local operation and channel lifetimes per connection. fenceForReset closes admission (except work nested under an already-admitted operation and one exactly-identified control channel) and drain() waits for the rest, failing sticky on any failure or unverifiable opening observed after the fence. Channel closure is local lifetime evidence only, never proof that a remote process exited. - trackSshConnectionChannelLifetime / openTrackedSshSocket: bind an opened channel or socket to its ledger entry and settle it only on 'close' ('end', 'error' and the destroyed flag are not closure). Porting note (source: #16741 head a68b6f3, merge-base 277c289; T2 per the #24137 track manifest): - Taken verbatim: ssh-connection-work-ledger behavior and tests, ssh-forward-socket-admission.test.ts, openTrackedSshSocket. - Adapted: the ledger no longer calls assertProfileLifetimeAdmission on every admit. That module is an opt-in native-addon profile lock (addon dropped in T0) that overlaps the SQLite authority from #22612; callers inject their own admission check through the existing constructor argument instead (SshConnection will pass its disposed check). The broad `object` resource type became SshConnectionWorkChannel (on/once/ removeListener), and trackSshConnectionChannelLifetime uses a type guard instead of a cast, so a value without removeListener is now reported unverifiable rather than tracked. Added ssh-connection-channel-lifetime tests, since #16741 covered it only through SshConnection. - Dropped: none in these files. - Not in this slice: SshConnection wiring (ssh-connection.ts), forwarded channel lifetime (T4), upload session lifetime (T6), profile lifetime admission/lock/participation (needs a D9.4 decision against #22612). No wire change: nothing is sent to relays or clients. * feat(ssh): add SSH transport close ledger and close observation Dormant foundation for the T2 SSH core port of #16741. No production module imports it yet, so SSH behavior is unchanged; the next T2 slice has SshConnection track every ssh2 client it allocates and gate its transport-closure subscribers on this ledger plus the work ledger. Adds: - SshTransportCloseLedger: remembers every allocated client (including ones whose authentication failed) until it emits 'close'. drain() waits for the snapshot and fails with ssh_client_close_allocations_changed if a client was allocated after the caller should have fenced allocation. Authentication settlement, 'end' and 'error' are not physical closure. - observeSshTransportClose: registers 'close' listeners on a set of transport resources before close is initiated; wait() is cancelable without dropping the evidence, dispose() removes the listeners. Porting note (source: #16741 head a68b6f3, merge-base 277c289; T2 per the #24137 track manifest): - Taken verbatim: both modules and ssh-transport-close-ledger.test.ts. - Adapted: the ledger test no longer casts EventEmitter to ssh2 Client, since track() already accepts an EventEmitter. Added ssh-transport-close-observation tests, since #16741 covered it only through SshConnection.dispose. - Dropped: none. No wire change. Loss of transport is still reported as unverifiable, never as remote process exit. --------- Co-authored-by: m4air <[email protected]>
The stage the staged plan existed for. Measured from the post-stage-2 main this cost 78 commits and 14 conflicts (13 in the PTY delivery subsystem) instead of 881 commits and 32 conflicts from the original base. **The PTY wall was not what the 월드맵 feared.** It recorded `pty-project-window-stream-routing` as a ~1,500-line feature-scale re-implantation and deferred it twice. In fact all 14 conflicts come from three upstream commits: - `9700030689` refactor(pty): make renderer delivery optional for headless runtimes (stablyai#23117) — `session.mainWindow` becomes optional and every `isDestroyed()` guard gains a null check. - `82412dab8b` Persist profile state in SQLite with background writes (stablyai#22612). - `d443320af2` refactor(native-chat): remove the unused terminal handoff (stablyai#22783). On the same lines the fork had already replaced the main-window guard with owner-window routing (`resolvePtyOwnerWindow`, `sendToPtyOwner`, `ownerFlowStateForPty`). The fork's guard is strictly finer: in headless mode no window is registered with the router, the owner resolves to null, and the fork takes the same early-return upstream's null check adds — while upstream's coarser guard would drop or misroute project-window delivery when the main window is gone. So most of the cluster resolves to ours, and nothing had to be reimplanted. Conflicts resolved (14) - `pty/delivery/{accept,accounting,exit,flush}.ts`, `pty/provider/bind-listeners.ts`: ours. Verified mechanically — resolving every hunk to ours produced a file byte-identical to main, so upstream has no other change in them. - `pty/delivery/payload.ts`, `pty/runtime/operations.ts`: per hunk, never whole-file. A whole-file ours on operations.ts would have restored imports of two modules `d443320af2` deleted and a 3-arg `writePtyFromRuntimeController` while the merged `runtime/controller.ts` calls the 2-arg form. - `pty/ipc/{resize-visibility,serialize-buffer,spawn-commit-persist,write-input,write}.ts`, `pty/register-handlers.ts`: combined, preserving every per-window router injection. A previous attempt at this merge failed its gates by dropping them. - `persistence/loading-store/store.ts`: combined for `82412dab8b`'s SQLite authority. Edits outside the 14 conflicted files (6) Each one is a defect the conflict list could not show, because the file merged cleanly while the meaning did not. 1. `pty/session.ts` + `pty/delivery/window-flow-state.ts`: `session.ts` merged cleanly into a crash. `mainWindow` is now optional, upstream's `register-headless-runtime.ts` passes `undefined` where it used to pass a fake destroyed window, and the fork's `createWindowFlowState(session, args.mainWindow.webContents)` therefore threw on every `orca serve` and orcad registration. Fixed by narrowing a flow state's `webContents` to `Pick<WebContents, 'id' | 'isDestroyed' | 'send'>` and passing a destroyed stand-in, with no cast. `window-flow-state.ts` stays at 297 of its 300 permitted code lines. 2. `persistence/loading-store/store-domain-composition.ts`: added `SatelliteWindowSessionPersistence &` to `StoreDomainOperations`, without which four satellite-session methods disappear from the `Store` type. 3. `pty/register-without-renderer.test.ts`: two `registerPtyHandlers(renderer as never, …)` casts, matching the shape 274 existing calls in this repo use. This is an upstream-owned file, so the next sync touching it will conflict here. 4. Three usage test fixtures (`usage-custom-range-filters.test.ts`, `UsageNumberFormatToggle.test.tsx`, `usage-pane-test-state.ts`): added the fields upstream `297cfe0cf3` (stablyai#22073) made required. **These were already broken on main**: a fresh worktree at `e0686816e8` reports exactly these 4 type errors. Stage 2's gate missed them because a warm `composite` `.tsbuildinfo` cache under-reported. Typecheck cold before trusting a pass. 5. `pty/register-handlers.ts` + the window-affinity router: `setMainWindowForRouting` widened to `BrowserWindow | null` and called unconditionally as `setMainWindowForRouting(mainWindow ?? null)`. Skipping it when `mainWindow` is undefined left a previously routed live window routed, so a desktop → headless re-registration would send `pty:exit`, `pty:spawned`, `pty:writeUnavailable`, `pty:clearBuffer:request`, `pty:serializeBuffer:request` and `pty:modelRestoreNeeded` to a stale window. Current call order prevents it in production; that is not a guarantee worth depending on. Restores parity with main. Gates (each captured from the command's own exit code) - typecheck, run cold after deleting `config/*.tsbuildinfo`: 0 errors. The same command on a main worktree reports its 4 pre-existing errors. - oxlint: exit 0 on the full tree and on the touched files. - verify-orcinus-identity: OK, upstreamRefs=0. - electron-builder smoke: unsigned, update signature checks disabled. - fork contract tests: 3 files / 24 tests. - `register-without-renderer.test.ts` (upstream's new 231-line headless test): 4/4. - router-referencing tests: 3 files / 70 tests. - Broad conflict-area suite: 122 failures, none attributable. 121 fail identically on a main worktree; the remaining one, upstream's own `profile-state-crash-recovery.test.ts`, times out identically on a `da6d483ab9` worktree. Per-test JSON diff: 0 failures unique to main. Reviewed by an independent critic: APPROVE, no blocking defects, every gate re-measured, every fork-only and upstream-only file confirmed equal to its parent apart from the six edits above, no IPC channel dropped. Non-blocking and deliberately not addressed: `hasUnpricedModels: false` does not match its own fixture's data (behaviour-neutral); the upstream-owned test file will re-conflict; plan-B's satellite-session durability question is still open. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

ELI5
Orca saves migrated profiles to SQLite in a background worker. Terminal creation, removal and automation changes wait for a confirmed save, so reported success survives a restart. Existing JSON profiles migrate automatically on capable runtimes; JSON remains available for import, export, recovery and admitted legacy runtimes.
Stack: #22612 → #22635 (bundled Bun) → ordinary JSON-backend retirement.
What Changed
Store validated profile domains in transactions. Ordinary edits update changed domains; checkpoints, exports and backups use a consistent revision. Preserve unknown fields and sealed secrets.
Move writes and backups off the main thread. Batch compatible saves while preserving mutation and export order. Ordinary flushes settle their admitted work without waiting for hourly backups or chasing later edits.
Keep saving after canceled caller waits and known export failures. Retry transient Windows publication locks and recheck export freshness. Unknown commit outcomes still stop the writer; desktop users receive an error instead of silently losing subsequent edits.
Acknowledge terminal bindings, SSH leases, retirement and automations after durable saves. Seed restored history before live output can arrive during the disk wait. Fast desktop-spawn exits retain their output and exit status; headless requests for a live terminal still fail.
Keep host-proven reattachments routable when their binding save fails. Defer fresh-spawn publication until registration succeeds. Failure cleanup checks the process incarnation before shutdown and after its await, and passes the existing incarnation fence to the host, so delayed predecessor work cannot kill or erase a replacement.
Publish mobile retirement after saving with a separate in-flight token. Preview reads cannot invalidate it; replacement admission can. Bind new terminal handles before pending-mobile publication without recreating stale renderer records for an existing replacement handle.
Preserve final saving through profile switches, relaunch and known maintenance failures. Export current compatibility JSON on clean final shutdown and maintenance. Recover damaged legacy JSON from its backup ring; explicit
orca profile state rollback --current-jsoncan select JSON edited by an older build while preserving SQLite and recovery files in quarantine.Use revision checks and recovery records for migration, restore and cross-profile moves. Replay moves involving the active profile; refuse rollback while a relevant move is unresolved. Release and durably publish profile-access records, show startup errors, and distinguish a newer schema from corruption.
Load offline recovery dependencies only when the agent-hooks fallback needs them. Log post-removal account-ledger cleanup failures without reporting an already-removed account as still present.
Simplify Store construction and automation-row deletion, and name the flush policies at each call site. This removes duplicate bookkeeping while keeping recovery ownership and acknowledgement boundaries explicit.
Why
Whole-profile JSON rewriting scales with the entire profile on each save. SQLite transactions let ordinary writes scale with changed domains, while workers move disk work off the main thread. Explicit acknowledgements preserve correctness across crashes and delayed operations.
The existing database interface already isolates the driver. An ORM would add another representation without replacing the revision checks and recovery protocols spanning databases and files, so those protocols remain explicit.
Linked Issue
No linked issue. Runtime portability is stacked separately in #22635.
Visual Proof
N/A — no rendered layout changes. Startup and stopped-saving errors are tested at the native-dialog boundary without showing test windows.
Testing
Current head:
80e8a8669a; production code is unchanged fromca8620eda4, rebased on main02a5594434. Independent Codex and Claude Code Opus reviews found no P0/P1 defects in the previous full review and no P0/P1/P2 findings in the final cleanup and rebase integration. All 42 SQLite patches were preserved by the rebase. The merged SSH split-layout fix #22991 is included through main.Resulting promise was garbage collected), before recovery assertions. The same-head rerun repeated that single startup failure (51 passed / 2 skipped). Playwright 1.63 gives the already-retried inspector collected-promise failure a new message;80e8a8669arecognizes it within the existing bounded, idempotent retry policy. All seven helper tests pass, including before-fix failures and immediate propagation of closed-app/real errors. Targeted Linux recovery verification passed both unchanged Node/Electron recovery scenarios on80e8a8669a. Codex and Claude Opus found no blocking issue in the retry correction; the aggregate verify check alone is not treated as a full pass.Historical SQLite CI passed 89,961 unit tests and recorded 99 E2E passes / 2 skips / 1 extra-PTY failure during rapid SSH reconnects. The same-head dedicated Docker lane passed. The cause remains unproven; #22991 fixed a separately reproduced split-layout issue and is not claimed to explain the extra allocation.
Fresh combined installers published successfully from exact source
f8df2844ad, including both PRs and merged SSH fix #22991. Build 36215785431 passed both Mac and Windows jobs. Mac ARM/Intel packages are signed/notarized; Windows is unsigned. Source identity, manifest hashes, referenced asset sizes and blockmaps were verified; binaries were not downloaded or launched.ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/persistence/profile-state src/main/persistence/loading-store src/main/orca-profiles src/main/automations pnpm tc pnpm run check:code-quality:changedBuild CLI before Electron because both write to
out/main. Agent-launched application checks use background mode.80e8a8669a.80e8a8669acompleted; run 36221445236 remains in progress.Review
Merge preparation: clean integration with main
f0a3610928. The combined integration through58d1ff3b6apassed full typecheck and 29 targeted integration tests, with independent Codex/Opus reviews. Later main changes are a reviewed, disjoint mobile label fix and a terminal hook-count test correction. No production code changed during merge preparation.Suggested order: authority admission/migration; worker and Store ordering; terminal/SSH/automation durability; maintenance/recovery; fault-injection tests.
Parallel review and regression tests confirmed and fixed the reachable export, flush, fast-exit, restore-history and mobile-retirement findings. Subsequent review fixed failed-reattach routing, replacement shutdown/cleanup and stale-handle publication; independent cross-review found no further confirmed issue in those changes.
Two reported failures do not follow from the code: a split queued behind close is rejected by serialized source-binding admission, and an indeterminate writer cannot perform the later checkpoint claimed to resurrect a stale binding. Both boundaries have focused coverage. Moves involving only inactive profiles do not block startup; unresolved moves involving the active profile remain protected.
Agent skill upstream boundary
Notes
rollback --current-jsonexplicitly selects one state, preserves the other, and refuses unresolved cross-profile moves.Checklist