Skip to content

Persist profile state in SQLite with a durable background writer - #22612

Merged
OrcaWin merged 43 commits into
mainfrom
OrcaWin/np-async-profile-persistence
Sep 26, 2026
Merged

OrcaWin merged 43 commits into
mainfrom
OrcaWin/np-async-profile-persistence

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 242 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​26938 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1340 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​25598
Prod 248 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​14346 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2139 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​12207

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-json can 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 from ca8620eda4, rebased on main 02a5594434. 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.

Coverage Evidence
Final cleanup 267/267 focused tests across 22 files on the combined stack, including 195 persistence/flush tests. No tests or assertions removed or changed.
Built Bun artifact 906 passed / 16 skipped across 84 passed / 2 skipped files on macOS ARM, using Bun 1.4.2 and SQLite 3.51.0.
Static verification Full Node, CLI and renderer typecheck; changed-code quality across 630 files; all eight cleanup files linted/formatted; clean whitespace check.
New-head PR CI Run 36215766539: all unit/static/type/package gates passed. Changed E2E: 51 passed / 2 skipped / 1 failed during the initial Playwright main-process evaluation (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; 80e8a8669a recognizes 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 on 80e8a8669a. Codex and Claude Opus found no blocking issue in the retry correction; the aggregate verify check alone is not treated as a full pass.
Prior broad coverage The pre-cleanup SQLite branch passed 1,347 tests / 8 skips across 151 files. Terminal/runtime validation passed 9,552 tests / 33 skips, with the subsequently corrected shutdown-fence assertion passing its entire file. Recovery/current-JSON, real-worker commit/export faults, worker death, delayed binding saves and replacement ownership races have focused regressions.

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:changed

Build CLI before Electron because both write to out/main. Agent-launched application checks use background mode.

  • Local behavior and automated regressions exercised.
  • Migration, transactions, worker faults, shutdown, backup/recovery and rollback covered.
  • All unit/static/type/package gates passed on the unchanged production head; both full E2E attempts passed the other 51 cases / 2 skips, and the corrected startup/recovery gate passes on 80e8a8669a.
  • Fresh full PR workflow on 80e8a8669a completed; run 36221445236 remains in progress.

Review

Merge preparation: clean integration with main f0a3610928. The combined integration through 58d1ff3b6a passed 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

  • Not applicable; no upstream skill-installer resources copied or translated.

Notes

  • Filesystems without hard links remain unsupported for atomic database publication; startup explains the limitation and preserves recovery data.
  • Windows reused PIDs and unverifiable legacy/shared-profile owners remain conservatively protected, with manual remediation. A cloned machine ID alone cannot authorize reclaiming another host's record.
  • Forced or timed-out shutdown cannot guarantee current downgrade JSON. Unknown commit outcomes require restart/recovery; known export failures and caller cancellation do not disable future saving.
  • Divergent JSON and SQLite are never merged automatically. rollback --current-json explicitly selects one state, preserves the other, and refuses unresolved cross-profile moves.
  • Schema versions 1/2 were unreleased intermediates. A future released schema change needs its own startup upgrade admission.
  • Managed SSH deployment has no production callers; legacy launcher migration and stronger ownership proof remain prerequisites before connecting it.
  • JSON import/export/recovery remains. Run headless Orca with bundled Bun and preserve SQLite durability #22635 supplies a capable headless runtime without requiring a user-installed Node 24. No required public RPC fields or stream opcodes are added.
  • Tracking, design, research and measurement documents remain local.

Checklist

  • Small PR — intentionally substantial: persistence cutover and durability callers.
  • Explained behavior, mechanism and alternatives.
  • Visual proof is N/A with reason.
  • Independently reviewed for correctness and performance.
  • macOS/Linux/Windows, SSH, folder workspaces and mixed versions considered.
  • Production coverage plus focused verification of the final test-harness correction reviewed before merge.
  • Fresh full workflow completed on this exact head (still in progress at merge preparation).

@OrcaWin
OrcaWin marked this pull request as ready for review September 24, 2026 06:49

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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.db per profile behind the existing Store interface; 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 direct copyFileSync to 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/ipc/pty/pane/stable-owner.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 — logStartupMilestone now accepts () => details and snapshots t before invoking it; the loading store drops its duplicate logPersistenceStartupMilestone helper 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) on RuntimeClientError.data.
  • Background-launch policy — startup recovery-dialog suppression now routes through isBackgroundLaunch() rather than a raw ORCA_BACKGROUND_LAUNCH comparison.
  • Schema cleanup — automation-runs table SQL is inlined into profile-state-database-schema.ts and the createProfileStateAutomationRunsTablesSql helper is removed, with no dangling references.
  • Bundle-parity guard — the CLI/main bundle parity test moves to config/scripts and reads the exported electronViteConfig input 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 onPtyExit awaited, launchUntilExit captures 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).

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — quarantineReattachData now owns the livePassthrough case and streams the frame when ownsPtyRecoveryAttempt(payload.id, pending) holds, instead of the provider onData handler short-circuiting to acceptPtyData while recovery-transfer frames were queued into pending.liveData and never drained.
  • Regression coverage — the new keeps source output contiguous while the recovered pane binding waits for disk case drives a frame through the source-activation transferToRecovery sink while persistPtyBinding is deferred, asserting acceptOutputData receives [4, 8, 12] and the recovery lease commits only after the binding resolves. Reverting the livePassthrough branch makes it fail ([4]), so it exercises the real fix.
  • Test tidy-up — emitSourceFrame gained data/sink parameters 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 registerPersistedPtySpawn wraps runtime.registerPty(...); when registration throws agent_session_exited_during_start and the runtime holds an earned exited verdict, it awaits retirePersistedStablePaneOwner(...) before rethrowing, so a terminal that dies during the durable persistPtyBinding write no longer leaves a persisted binding that would resurrect the closed pane.
  • Both spawn commit paths now use it — commitRuntimePtySpawn and commitPtyIpcSpawn await the helper in place of a direct registerPty call; the runtime path also destructures ctx.hostSessionBinding into 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — registerPersistedPtySpawn is no longer async; on success it calls runtime.registerPty(...) and returns undefined synchronously, so callers no longer yield a microtask before the remaining spawn publication. The confirmed-exit retirement path returns retirePersistedStablePaneOwner(...).then(() => { throw error }) (Promise<never>), while the non-retire throw paths still throw synchronously.
  • Callers updated — commitPtyIpcSpawn and both commitRuntimePtySpawn sites now await only the returned rejection promise, which is behaviorally equivalent to the old await on the retirement path and removes the success-path yield.
  • Telemetry extraction — the spawn agent_started block moved verbatim into recordPtySpawnTelemetry (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 async version).

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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — applyPtyBinding now appends the binding's worktree to session.activeWorktreeIdsOnShutdown when 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 — evaluatePtyBindingFastLane adds an inactive_worktree miss 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.ts pins that activity lands only after the SQLite transaction commits and that a same-binding reattach repairs the list exactly once; the new terminal-binding-crash-hydration.test.ts drives applyPtyBinding → hydrate → reconnectPersistedTerminals for 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).

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@OrcaWin

OrcaWin commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator Author

Reviewed the additional observations from the initial review as well:

  • SQLite files or orphaned sidecars remain authority evidence even when legacy JSON exists. Automatically using that JSON could discard newer acknowledged data. Startup preserves the evidence and requires explicit recovery. The selected JSON-export rollback validates its input before quarantining database/WAL files and replacing the live JSON; bootstrap and CLI recovery tests pass (40 tests).
  • Recovery copy targets are staging files. Both callers already own validation, fsync and publication; the copy API now states that contract directly. Adding another atomic-copy layer would duplicate the existing publication boundary.
  • Retained read-only admission and integrity checks. Earlier local measurements put the repeated scan at roughly 3–13 ms and schema verification around 0.2 ms. The steady writer reuses its connection, and backup validation runs in a worker. Earlier writable/query-only admission experiments could recover a hot journal before validation, violating preservation of damaged-state evidence. These checks also do not replace the separate payload-hash validation.

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — retirePersistedStablePaneOwner now returns persist: 'if-dirty' when the pane is already absent in memory, and runDurableMutation skips the write only when lastDurableWriteGeneration >= 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, codex and keychain entries now share one exported CLI_MAIN_ENTRY_NAMES list used by both the Rollup inputs and the guard; a parity test asserts every src/main/* module the CLI imports is in GUARDED_ENTRY_NAMES, and a per-entry test drives direct, static and dynamic Electron requires.
  • Tightened backup-rotation idleness — assertIdle() now checks the whole pending operation instead of the copying flag, so synchronous quarantine is fail-fast across queueing, snapshot copy and retention pruning.
  • Added regression coverage — pty-retirement-async-durability.test.ts uses 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — runDurableMutation now sets a durableMutationPhase for the duration of its synchronous mutate/rollback callbacks, and setWorkspaceSession treats 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), writesFrozen still throws unconditionally, and the before-unload stage path still passes false, 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 — isRecord is imported from profile-state-document-validation.ts (identical body) and readAgentHookSettingsFromJson runs both branches through the shared readAgentHookSettingsFromSettingsValue coercion.
  • 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 newer activeTabId, 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@OrcaWin
OrcaWin force-pushed the OrcaWin/np-async-profile-persistence branch 2 times, most recently from 9622ea0 to 1b2e701 Compare September 25, 2026 02:50

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — beginProfileStateMaintenance now wraps the pause in a canResumeFailedMaintenance catch that re-proves the authority writable and unfreezes on a known write failure, and freezes/closes on an indeterminate or already-frozen state; pauseProfileState drains 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.ts records kernel boot identity and process-start identity, so ownerExited reclaims 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; removeAbandonedProfileStateBackupFiles removes only old files whose owner PID is proven exited, and runProfileStateBackupWorker accepts an abort signal and removes its temp files after the worker exits.
  • Fatal mutation latch — a throwing mutate/rollback callback latches fatalMutationError, 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 flushPendingOrThrowAsync before announcing or returning, and requestAutomationDispatch rechecks 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — reconcileRetainedRuns now also stages pending runs whose trigger === 'manual', and describeStrandedAutomationRun gained a pending branch 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, and resolveRunTerminal returns null without a terminalPaneKey, so the run is staged and stranded after the surface-settle grace.
  • Scheduled pending runs stay retryable — the filter excludes scheduled pending runs, and the test pins that pendingScheduled remains pending while pendingManual becomes dispatch_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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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) and clearWorktreeTerminalResumeRecords (terminal_close_incomplete) now return { value: new Error(...), persist: false } instead of throwing inside the mutation callback. A throw there runs stopAfterFailedPrimaryStateMutation, which latches fatalMutationError and freezes every later write, so a merely refused tab close used to permanently stop profile saving. The returned Error is re-thrown, so callers still observe the refusal.
  • Contract documented — runDurableMutation now states the rule: expected refusals return persist: 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 with Cannot flush while persistence is finalized; at head acknowledged-terminal-tab-retirement (13) and orca-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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — readOnDiskPartitions now reads committed state through readPersistedProfileState (opens profile-state.db read-only under a runtime admission) instead of globbing retained orca-data.json compatibility exports, so the load-bearing runtimePartitionHoldsCapture / localPartitionDidNotKeepCapture assertions 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.json to 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 — enqueueWrite now reuses an in-flight queuedSnapshot batch, folding in skipIfClean and the latest pendingSnapshotFileWork and returning that batch's completion; enqueuePrimaryStateOperation clears 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 ProfileStateExportPreparationError marks failures raised before SQLite acceptance or canonical JSON is touched, so the worker no longer latches stopping for export-compatibility/close on such a failure, while an indeterminate underlying cause still surfaces through the recursive outcome derivation.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 fullCheckpoint flag, and queued.capture.fullCheckpoint ||= !queued.capture.skipIfClean runs after the existing skipIfClean &&= upgrade. Any batch that absorbs a non-skipIfClean durability waiter — explicit-joins-debounce or debounce-joins-explicit — nulls dirtyProfileStateDomains immediately 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 skipIfClean true, so the full-capture trigger does not fire; the new case asserts writeCompleteSerializedDomains is never called.
  • The dirty-set reset reads the batch, not the call — primary-state-writes.ts:205 now consults capture.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 their capture.fullCheckpoint mirrors options.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 to writeCompleteSerializedDomains, 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 — enqueueWrite drops the signal abort listener that called profileStateAuthority.abort() and returns waitForPromiseWithSignal(completion, signal); an abandoned waiter rejects while the admitted write keeps its place in runtime.pendingWrite, so the final checkpoint still joins it.
  • Quit survives a known maintenance failure — flushFinalOrThrowAsync awaits pendingProfileMaintenance, swallows a known failure only when the store was re-admitted, then drains and runs the final full checkpoint before closing; canResumeFailedMaintenance no longer treats quitFlushStarted as 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 raises publication-unavailable with 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@OrcaWin
OrcaWin force-pushed the OrcaWin/np-async-profile-persistence branch from 353afda to 7306dd2 Compare September 25, 2026 07:37

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — ownerExited gains sameHost = owner.host === hostname(); the foreign-host guard becomes !sameBoot && !sameHost, and the reboot shortcut now requires sameHost && sameMachine instead of sameMachine alone. 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-id is 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.ts pins 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 returned true from the matching machine id). The wall-clock test now calls reclaimExitedOwner directly so Linux platform emulation does not perturb host publication/fsync flags; it still asserts unverifiable with the owner retained.
  • Test-only harness line — pty-pane-restart-replace.test.ts adds a runDurableMutation fake 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 defers dialog.showErrorBox + app.exit(1) to app.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; runMainProcessPreflight still returns false, so index.ts installs 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — indexLiveTerminalSurfaceOwners no longer drops orphaned rows. It maps orphaned === true && connected === true to a new 'unowned' verdict (a disconnected orphan stays null), and only folds non-orphan rows through toSurfaceOwner. The conflict check compares the 'unowned'/null sentinels without a paneKey, so conflicting owned/orphan rows still collapse to null.
  • Adoption mints only on 'unowned' — adoptLiveWorkspacePtySurfaces now 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 — readWorktreeLiveTerminalSurfaceOwners adds requireFreshPtyLiveness: 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 surfaceOwners to 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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) wraps set -o pipefail; ls /proc/<pid>/fd | wc -l, and sampleRemoteResources now reduces the relay table through it.
  • Settles transient FDs before failing — when the last reconnect sample exceeds first.relayFdCount + 4, the spec attaches ls -l /proc/<pid>/fd plus ps diagnostics 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — buildPtyTerminalSummary now throws terminal_surface_ownership_unavailable when 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 matches acquireWorktreeTerminalMutation's.
  • Coordinator defers instead of spawning — listAvailableWorkerTerminals returns null on a failed census (was []), and dispatchReadyTasks returns early on null, retrying the next tick rather than creating a replacement worker from an untrustworthy census. The early return leaves phase at 'dispatching', matching the existing slotsAvailable <= 0 path.
  • 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) and coordinator-terminal-census-unavailable (2; defer then reuse the existing worker for both ownership and liveness errors), plus hasActiveSpawns assertions. Removing the guard/null-check fails every terminal-list rejection case and both coordinator deferral cases. pnpm tc:node green.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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-bridge now records the last authority it routed in routedAuthorityByTarget and derives previousAuthority from 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, so routeDirectSshConnectedState takes the changed-authority branch and requestReconnect actually 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 reconnectAuthorityByTarget clears.
  • Regression coverage — the new direct-ssh-connect-reply-routing suite (10) exercises reply-first and push-first orderings, initial hydration, partial-authority reconciliation, disconnect/error cleanup, and per-target isolation. Reverting to the store-derived previousAuthority fails 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@OrcaWin
OrcaWin force-pushed the OrcaWin/np-async-profile-persistence branch from 8689831 to 6d91d31 Compare September 25, 2026 22:13
@pullfrog

pullfrog Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

Run failed. View the logs →

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@OrcaWin
OrcaWin force-pushed the OrcaWin/np-async-profile-persistence branch from 6d91d31 to ca8620e Compare September 26, 2026 03:45

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 while isCurrentPtyExit, and the shutdown carries expectedIncarnationId, so a replacement that lands during the save or during the shutdown survives. IPC commitPtyIpcSpawn now swallows a confirmed agent_session_exited_during_start and 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) and publishPtyIpcSpawnCommit (in-memory publication), and seedHeadlessTerminalFromSpawnResult runs 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') and ProfileStateExportPreparationError is gone. Verified the SQLite write/read wrappers convert an ambiguous COMMIT or failed ROLLBACK into ProfileStateIndeterminateWriteError / ProfileStateReadRollbackError, both classified indeterminate, 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 — flushCurrentStateAsync now drains backups only for final || profileMaintenancePending; the flush still settles its own admitted write, and final/maintenance paths still drain.
  • Retirement concurrency is fenced by a token — pendingPtySurfaceRetirementsByPtyId replaces the lifecycle-generation check, and is cleared by onPtySpawned, invalidateAllHandlesForPty and registerPty, 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 rechecks isCurrent before publishing.
  • --current-json recovery + stopped-saving signal — a new explicit CLI selector adopts the current orca-data.json (revision null, both authorities archived), startup text explains it, and desktop users get a native "Saving stopped" dialog routed through onPersistenceFailure.
  • Refactor is behavior-preserving — every flushCurrentStateAsync call 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — isTransientMainEvaluateError also matches 'Resulting promise was garbage collected' alongside 'Execution context was destroyed'. Confirmed in node_modules/playwright-core/lib/coreBundle.js (Playwright 1.63.0) that Chromium's rewriteError emits 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 distinct has been closed message and still propagates on the first attempt.
  • Both messages now covered by parametrized tests — transient() became a transientMessages array; the retry and bounded-retry (calls === 5) cases run over Execution context was destroyed and the collected-promise message via it.each, and a new case pins calls === 1 for a closed application. Local: electron-main-evaluate-retry.unit.test.ts (7) passes.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@OrcaWin
OrcaWin merged commit 82412da into main Sep 26, 2026
52 of 54 checks passed
OrcaWin pushed a commit that referenced this pull request Oct 1, 2026
…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.
OrcaWin pushed a commit that referenced this pull request Oct 1, 2026
…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.
OrcaWin added a commit that referenced this pull request Oct 1, 2026
…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]>
@nwparker nwparker mentioned this pull request Oct 5, 2026
14 tasks done
sj900211 added a commit to sj900211/orcinus that referenced this pull request Oct 12, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant