Repository navigation
fix(orchestration): reap leaked worker terminals via process-incarnation fallback — stops an unbounded PTY/process leak on Remote Server (OOM / cgroup PID exhaustion) - #18790
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe runtime adds exact process-incarnation matching and host-scoped terminal-handle reminting. Terminal observation returns the effective handle, which worker read and stop operations use. Release completion revalidates identity, settles exited workers, closes reminted terminals, and classifies close failures. New unit, RPC, and functional tests cover reminting, fencing, recovery, epoch changes, and host-scope mismatches. Merge Risk: 🟡 Moderate · up to Worker release now recovers stale terminal handles for normal release, stop, and read flows, but structured-worker close failures may not be retryable and exited-worker settlement may incorrectly finalize a release. These cases can leave workers running or produce inaccurate release state, so they should be resolved before merge. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 0e2b2d72-7a31-43e5-9a25-0092c26197e2
📥 Commits
Reviewing files that changed from the base of the PR and between 436ef82 and 3cc7438e0b708fa214e53015303975e1d71ed867.
📒 Files selected for processing (9)
src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.tssrc/main/runtime/orca-runtime-terminal-handle-incarnation.test.tssrc/main/runtime/orchestration/worker-terminal-process-liveness.tssrc/main/runtime/rpc/methods/orchestration-worker-control.tssrc/main/runtime/rpc/methods/orchestration-worker-observation.tssrc/main/runtime/rpc/methods/orchestration-worker-release-completion.tssrc/main/runtime/rpc/methods/orchestration-worker-release-incarnation-fallback.test.tssrc/main/runtime/rpc/methods/orchestration-worker-release-reap-fixed.func.test.tssrc/main/runtime/rpc/methods/orchestration-worker-stop.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — a runtime worker-terminal reap fix: when a worker's durable handle goes stale after a renderer graph epoch bump, the release/stop/read paths now fall back to the persisted process_incarnation, fenced on an exact incarnation + host-scope match, and close the live PTY instead of leaking it.
resolveTerminalHandleByProcessIncarnation— new fence primitive scanningptysByIdfor the exact recorded incarnation, gated onJSON.stringify(hostScope) === serializedHostScope, reminting a live handle viaissuePtyHandle; fail-closed on a missing incarnationId or host scope.matchesProcessIncarnation— shared colon-immune matcher extracted fromclassifyWorkerTerminalProcessIncarnation(behavior-preserving refactor).inspectWorkerTerminal— re-mints a live handle on resolution failure and now returnsterminalHandle(the handle that actually resolved) across every branch.- Release completion,
workerStop, andworkerReadall act onobservation.terminalHandle ?? <durable>; the release path also settlesreleasedwhen the incarnation is provablyexited.
The fence is sound: incarnationId is a per-spawn string, so a reused ptyId can never collide, and the downstream workerTerminalLeaseIsCurrent (via getOrchestrationDispatchAuthority, which checks pty.connected) plus isDispatchProcessCurrent re-gate before any close. The reminted handle is a non-epoch-fenced pty: handle, so it resolves through showTerminal across the bump. Tests are layered (real-resolver fence tests, mocked wiring tests, and a functional two-plane reproduction) with exact assertions, and all pass locally.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: f30bbdfb-00f9-4762-b35a-b4e11e551d01
📥 Commits
Reviewing files that changed from the base of the PR and between 3cc7438e0b708fa214e53015303975e1d71ed867 and 143577657e3cab2bfa7d7da73fb5155bcb5b3153.
📒 Files selected for processing (10)
src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.tssrc/main/runtime/orca-runtime-terminal-handle-incarnation.test.tssrc/main/runtime/orchestration/worker-terminal-process-liveness.test.tssrc/main/runtime/orchestration/worker-terminal-process-liveness.tssrc/main/runtime/rpc/methods/orchestration-worker-control.tssrc/main/runtime/rpc/methods/orchestration-worker-observation.tssrc/main/runtime/rpc/methods/orchestration-worker-release-completion.tssrc/main/runtime/rpc/methods/orchestration-worker-release-incarnation-fallback.test.tssrc/main/runtime/rpc/methods/orchestration-worker-release-reap-fixed.func.test.tssrc/main/runtime/rpc/methods/orchestration-worker-stop.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts
- src/main/runtime/rpc/methods/orchestration-worker-observation.ts
- src/main/runtime/rpc/methods/orchestration-worker-control.ts
- src/main/runtime/rpc/methods/orchestration-worker-release-reap-fixed.func.test.ts
- src/main/runtime/orchestration/worker-terminal-process-liveness.ts
- src/main/runtime/rpc/methods/orchestration-worker-stop.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — the delta since the prior pullfrog review (3cc7438) is review hardening: the release-completion path now settles a provably-exited worker before the lease check and before the recovery defer, and the incarnation resolver keeps scanning past a host-scope mismatch instead of short-circuiting on a colon-ambiguous decoy.
- Reordered
completeWorkerTerminalReleaseOnceso themissing/unattachedbranch settles a provably-exitedworkerreleasedbeforeworkerTerminalLeaseIsCurrentand before the recovery defer — addressing the prior finding where the stale-handle lease check pre-empted the settle withretained. Skipping the lease check here is safe: the branch never acts on a live process (it only settlesreleasedon a provably-exited incarnation, defers in recovery, or concedesrelease_unknown), and the close path still re-checks the lease. - Changed
resolveTerminalHandleByProcessIncarnationtocontinueon a host-scope mismatch, so a colon-ambiguous decoy pty in another scope can no longer suppress the genuine same-scope match. - Added unit tests for the shared
matchesProcessIncarnationmatcher (exact, Windows drive-letter, colon-bearing relay incarnation, whitespace-dirty/empty/absent incarnationId, prefix-decoy) and for the settle-before-lease and recovery-defer ordering. - Converted new/edited comments to JSDoc to satisfy the docstring-coverage gate (no behavior change).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Review response — all feedback addressed and pushed; checks green.
Full |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — the delta since the prior pullfrog review (1435776) is a single test-only commit that tightens the direct-fence "colon-ambiguous decoy" test to prove the incarnation re-mint resolves to the genuine PTY, not a same-incarnation decoy.
- Pinned the re-mint to the genuine pane — extracted the decoy/genuine
tabId/leafIdinto named constants and addedmakePaneKeyassertions onruntime.getTerminalPaneKey(handle), so the test now fails ifresolveTerminalHandleByProcessIncarnationever mints the decoy's handle. Both pty ids (relay+conn:incarnation-1vsrelay:conn+incarnation-1) stringify to the samerelay:conn:incarnation-1, which the previous/^term_/truthiness assertion could not distinguish.
The new assertions are exact, not tautological: getTerminalPaneKey resolves through the live pty's recorded paneKey (set by registerPty via makePaneKey(tabId, leafId)), so the assertion fails on any resolver regression that skips the host-scope fence and returns the first-matching decoy. Test file passes (14/14).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Follow-up: filed #18803 for the federation control-plane twin of this leak — |
1114da2 to
50ef327
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts (1)
117-117: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winDerive
currentHostScopefromeffectiveHandle.Every other runtime read in this function moved to
effectiveHandle, but this line still passes the durableterminalHandle. When the remint path ran, the durable handle resolves nowhere, sogetOrchestrationDispatchAuthorityreturns undefined andcurrentHostScopeis always undefined. The SSH decision then depends only on the persisted scope. If the persistedhost_scopeis absent, an SSH worker with no liveness verdict is classified fromterminal.connectedinstead ofunverifiable.♻️ Proposed fix
- const currentHostScope = runtime.getOrchestrationDispatchAuthority?.(terminalHandle)?.hostScope + const currentHostScope = + runtime.getOrchestrationDispatchAuthority?.(effectiveHandle)?.hostScope
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 9b385c72-b3c8-45d6-afa7-109ac38f0bca
📥 Commits
Reviewing files that changed from the base of the PR and between fa5ef99 and 50ef327b512a1982a427665baa5acdcd34e16735.
📒 Files selected for processing (10)
src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.tssrc/main/runtime/orca-runtime-terminal-handle-incarnation.test.tssrc/main/runtime/orchestration/worker-terminal-process-liveness.test.tssrc/main/runtime/orchestration/worker-terminal-process-liveness.tssrc/main/runtime/rpc/methods/orchestration-worker-release-incarnation-fallback.test.tssrc/main/runtime/rpc/methods/orchestration-worker-release-reap-fixed.func.test.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-control.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-observation.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-release-completion.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- src/main/runtime/orchestration/worker-terminal-process-liveness.test.ts
- src/main/runtime/orchestration/worker-terminal-process-liveness.ts
- src/main/runtime/orca-runtime-terminal-handle-incarnation.test.ts
- src/main/runtime/rpc/methods/orchestration-worker-release-incarnation-fallback.test.ts
- src/main/runtime/rpc/methods/orchestration-worker-release-reap-fixed.func.test.ts
- src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
Caution
This PR no longer compiles. The squash-rebase onto main left worker-release-completion.ts in a broken state: pnpm tc:node fails with 11 errors (all in that file), and the structured-worker release path that main added is silently dropped. It cannot build or merge as-is.
Reviewed changes — the delta since the prior pullfrog review (1114da2) is a squash of the PR into a single commit (50ef327) rebased onto a much newer main, which had since added structured-worker orchestration and refactored worker-release-completion.ts into smaller modules.
- Squashed and rebased — folded the four prior commits into
50ef327on top of currentmain; the incarnation-fence primitive, shared matcher, and theworkerStop/workerRead/inspectWorkerTerminallive-handle wiring survive the rebase and still typecheck. worker-release-completion.tsmangled — the file keepsmain's imports and structured-worker host-install prefix but applies the pre-rebase flat-file body, so it references symbols that no longer exist and dropsmain's structured-worker stop path.
🚨 worker-release-completion.ts no longer compiles — 11 typecheck errors and a dropped structured-worker release path
The rebase reconciled this file incorrectly: main had extracted workerTerminalLeaseIsCurrent, classifyWorkerTerminalCloseError, and summarizeWorkerOutputArchive into separate modules and added a stopStructuredWorkerForRelease branch, but the squashed body still calls the pre-rebase local signatures and references a now-removed local helper. Beyond the compile failure, routing a structured worker through runtime.closeTerminal(terminalHandle) (instead of stopStructuredWorkerForRelease) would mis-handle structured sessions, which have no PTY to close.
Technical details
# Reconcile worker-release-completion.ts with main's refactored structure
## Affected sites
- worker-release-completion.ts:190,229 — `workerTerminalLeaseIsCurrent(..., terminalHandle)` called with 5 args; `main`'s extracted helper in `worker-terminal-release-lease.ts` takes 4 → TS2554.
- worker-release-completion.ts:209 — `summarizeStoredArchive` referenced but no longer defined (was a local fn in the pre-rebase flat file); `main`'s `summarizeWorkerOutputArchive` is imported but unused → TS2304 / TS6133.
- worker-release-completion.ts:205 — `capturedArchive` typed `'transcript_pin' | 'terminal_tail'`, but `main`'s `captureWorkerOutputArchive` also returns `'structured_journal'` → TS2322.
- worker-release-completion.ts:217 — `archiveSource` can be `null`, passed where `'transcript' | 'terminal'` is required → TS2322.
- worker-release-completion.ts:3,10,17,19,20 — unused `WorkerTerminalArchiveKind` + unused imports (`summarizeWorkerOutputArchive`, `classifyWorkerTerminalCloseError`, `resolveStructuredWorkerForDispatch`, `stopStructuredWorkerForRelease`) → TS6133/TS6196.
## Required outcome
- `pnpm tc:node` must pass (currently 11 errors, all in this file).
- Re-apply the reap change on top of `main`'s structure rather than overwriting it:
- Restore `main`'s `resolveStructuredWorkerForDispatch` + `stopStructuredWorkerForRelease` branch for structured workers.
- Use `main`'s `summarizeWorkerOutputArchive` (handles `structured_journal`) instead of the removed `summarizeStoredArchive`.
- Keep the incarnation fallback intent: close via `observation.terminalHandle ?? resource.terminal_handle`, and ensure the lease check probes the live (possibly re-minted) handle — `main`'s `workerTerminalLeaseIsCurrent` probes `resource.terminal_handle`, so the live handle must be threaded through or the local overload kept.
## Open questions for the human
- The PR description claims `pnpm typecheck ✅ (0)`; that is false at `50ef327`. Was the structured-worker release drop intentional, or a rebase artifact?DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
a9989e0 to
ef199e6
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/runtime/rpc/methods/orchestration/worker/worker-release-completion.ts (1)
246-246: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winUse fresh-request recovery guidance for structured workers.
stopStructuredWorkerForReleasereturns guidance that tells users to repeat the request with the same--retry-request.releaseUnknownRecoverystates that this replays the priorrelease_unknownreceipt. A structured-worker close failure therefore cannot be retried and can leave the worker open.Update
src/main/runtime/rpc/methods/orchestration/worker/structured-worker-release-stop.tsto use the same fresh-request guidance.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 786b4994-b1fb-402d-b867-6359323bbd62
📥 Commits
Reviewing files that changed from the base of the PR and between 50ef327b512a1982a427665baa5acdcd34e16735 and a9989e0cbfc2f7540a8309962911793a1175951b.
📒 Files selected for processing (1)
src/main/runtime/rpc/methods/orchestration/worker/worker-release-completion.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
ef199e6 to
e39736c
Compare
… a service restart no longer kills every live PTY Root cause: daemon-launched-child.ts forks the detached terminal daemon with detached: true, which escapes the POSIX process group (setsid) but never the systemd cgroup. Every PTY the daemon owns is itself an undetached direct child of the daemon (native-pty-spawn.ts). Under a combined systemd unit (Type=simple, KillMode=mixed, per docs/reference/headless-linux-server.md), a systemctl restart/stop SIGKILLs every process still in the cgroup at the stop timeout -- the daemon and every live terminal -- even though the codebase already has a fully-built adoption/reattachment path for a surviving daemon (orcad-entry.ts's refreshRestoredOrchestrationAuthority + reconcileLegacyWorkerTerminals, gated on daemonOwnsFreshPersistentPtys()). That path never fires today because the daemon never survives long enough. Fix: when systemd is actually supervising the process and the OS user has a reachable systemd --user manager (isDurableDaemonScopeSupported(), Linux only), launch the daemon via systemd-run --user --scope so it lands in a cgroup that is a sibling of the service unit's cgroup, not a descendant of it. A systemctl restart of the combined unit then never reaches it. Any failure of the scoped launch (no reachable bus, D-Bus policy rejection, etc.) falls back transparently to the existing plain fork() launch, so every platform/environment without this capability is unaffected. The daemon self-detects its own resulting cgroup scope via /proc/self/cgroup (detectOwnCgroupScopeUnit()) rather than trusting the launcher's intent, and publishes it as cgroupUnit in its pid record and orcad's health/readiness payload (health.terminalDaemon.cgroupUnit), so a running deployment can be observed to confirm the fix actually engaged. No new session registry is added: the existing daemon pid-record + adoption protocol (publishDaemonPidFile, daemon-pid-record-quarantine.ts's dead-record reclaim, refreshRestoredOrchestrationAuthority) already implements durable, crash-safe reattachment for a surviving daemon -- it was simply never exercised against a full unit restart before now. Proven via a systemd-in-Docker recovery test: a live PTY session's shell process, its daemon, and the daemon's cgroup scope were all confirmed unchanged across a real systemctl restart of a Type=simple/KillMode=mixed unit, while the main process pid changed (confirming the unit actually restarted) and the new process's health payload recognized the surviving daemon as adopted and live. A fresh write into the same PTY post-restart reached the same running shell. Ordinary terminal create/work/release and the stablyai#18789/stablyai#18790 worker-release reap-fix regression tests are unaffected. Fixes stablyai#19408
There was a problem hiding this comment.
ℹ️ No critical or must-address issues — the new commits are test-only typing cleanup; one cleanup nit inline.
Reviewed changes — since the prior Pullfrog review (2edb2a7, review 5272459804) the branch was rebased onto da982a4eb0 and three test-only commits landed; the production reap logic is unchanged from the previously reviewed state.
- Fixed the RPC-method overload typing — both worker-reap test files'
findMethodnow searcheraseRpcMethods(ORCHESTRATION_METHODS), so the now-precise handler params no longer tripTS2345. - Simplified fixture typing — dropped the redundant
as string | null | undefinedcasts from thematchesProcessIncarnationtable so the union infers naturally, and added JSDoc describing the fixture type boundaries. - Added line-scoped lint suppressions — a large number of
// oxlint-disable-next-line typescript/consistent-type-assertionsdirectives were added around the test fixtures.
The already-resolved threads (the two eraseRpcMethods typecheck fixes) stay resolved, and pnpm test for the five worker-reap suites passes 45/45. The worker-reap production files remain byte-equivalent to the previously approved state.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…rker release When a durable terminal handle goes stale (rendererGraphEpoch fence), inspectWorkerTerminal re-mints a live handle via resolveTerminalHandleByProcessIncarnation + matchesProcessIncarnation so release/stop/read act on the still-running PTY instead of reporting missing and leaking the agent process tree. - keep main shared host-scope re-exports; add matchesProcessIncarnation - wire observation.terminalHandle through control/stop/release - rebuild release-completion on main structured paths - on missing/unattached + provably exited: settleDead fence first, then same-incarnation settleWorker fall back (archive may block settleDead mid-request); settle before recovery defer
…euse fresh-request recovery guidance for structured workers Addresses two open CodeRabbit review comments on PR stablyai#18790. inspectWorkerTerminal read the dispatch authority with the stale durable terminalHandle, so after a remint the lookup resolved nowhere and currentHostScope was always undefined — an SSH worker with no liveness verdict and no persisted host_scope got classified from terminal.connected instead of unverifiable. It now reads the same effectiveHandle every other observation in the function uses. stopStructuredWorkerForRelease told the caller to repeat the release with the same --retry-request, which only replays the stale release_unknown receipt and made a structured-worker close failure permanently unretryable. It now sources releaseUnknownRecovery from worker-release-completion so the fresh-request-ID guidance lives in one place. Pre-commit lint-staged (oxlint + oxfmt) run manually: clean.
…d terminal The read scenario only asserted that the call resolved, so it documented nothing about which handle the read reached. Assert that the handle readTerminal received resolves to the registered pane and incarnation, so the scenario proves the read went through the reminted terminal instead of passing on the incarnation fence's throw.
…uire liveTerminalHandle
<!-- orca-pr-loc -->
<!-- Programmatic LoC summary. Do not edit by hand; rewritten on every
commit. -->
| | Files | Added | Deleted | Net |
| :--- | ---: | ---: | ---: | ---: |
| Test | 0 | 0 | 0 | 0 |
| Prod | 28 | $\color{#1a7f37}{\Huge{\mathbf{+}}}$37 | 0 |
$\color{#1a7f37}{\Huge{\mathbf{+}}}$37 |
<!-- /orca-pr-loc -->
## ELI5
Add Freebuff (`freebuff`) as a recognized first-class TUI coding agent
in Orca alongside Codebuff and other supported agents.
## What Changed
- Registered `freebuff` across shared TUI agent definitions,
configuration catalogs, display names, and telemetry schemas.
- Added agent icons, favicons, status mappings, and mobile asset
references for Freebuff.
- Added localization strings across supported language packs (`en`,
`es`, `fr`, `ja`, `ko`, `zh`) and updated locale translation policy.
- Documented Freebuff CLI in README agent table (`npm i -g freebuff`).
## Why
Freebuff is a CLI coding agent twin of Codebuff (`npm i -g freebuff`).
Adding it to the catalog enables users to launch worktrees, run
automated sessions, and pick Freebuff directly within Orca.
## Linked Issue
N/A
## Visual Proof
`N/A` - Catalog registration and metadata definition for CLI agent
launch; UI rendering uses existing TUI agent picker and status
components.
## Testing
- Verified TypeScript contracts, schemas, and catalog configurations.
- Tested CLI detection / agent picker integration locally on Linux
(`worktree create --agent freebuff`).
## AI Disclosure
Assisted by AI coding tooling.
## Checklist
- [x] This PR is small and focused
- [x] I explained what changed and why (including ELI5)
- [x] Before/after screenshots or videos attached for UI changes, or
`N/A` with reason
- [x] Self-reviewed for correctness, security, and performance
- [x] Cross-platform, SSH/remote, and path/shortcut impact considered
(or N/A)
---------
Co-authored-by: Lesley Murfin <[email protected]>
4997777 to
7e945e5
Compare
… a service restart no longer kills every live PTY (#19430) * fix(daemon): escape the terminal daemon into its own systemd scope so a service restart no longer kills every live PTY Root cause: daemon-launched-child.ts forks the detached terminal daemon with detached: true, which escapes the POSIX process group (setsid) but never the systemd cgroup. Every PTY the daemon owns is itself an undetached direct child of the daemon (native-pty-spawn.ts). Under a combined systemd unit (Type=simple, KillMode=mixed, per docs/reference/headless-linux-server.md), a systemctl restart/stop SIGKILLs every process still in the cgroup at the stop timeout -- the daemon and every live terminal -- even though the codebase already has a fully-built adoption/reattachment path for a surviving daemon (orcad-entry.ts's refreshRestoredOrchestrationAuthority + reconcileLegacyWorkerTerminals, gated on daemonOwnsFreshPersistentPtys()). That path never fires today because the daemon never survives long enough. Fix: when systemd is actually supervising the process and the OS user has a reachable systemd --user manager (isDurableDaemonScopeSupported(), Linux only), launch the daemon via systemd-run --user --scope so it lands in a cgroup that is a sibling of the service unit's cgroup, not a descendant of it. A systemctl restart of the combined unit then never reaches it. Any failure of the scoped launch (no reachable bus, D-Bus policy rejection, etc.) falls back transparently to the existing plain fork() launch, so every platform/environment without this capability is unaffected. The daemon self-detects its own resulting cgroup scope via /proc/self/cgroup (detectOwnCgroupScopeUnit()) rather than trusting the launcher's intent, and publishes it as cgroupUnit in its pid record and orcad's health/readiness payload (health.terminalDaemon.cgroupUnit), so a running deployment can be observed to confirm the fix actually engaged. No new session registry is added: the existing daemon pid-record + adoption protocol (publishDaemonPidFile, daemon-pid-record-quarantine.ts's dead-record reclaim, refreshRestoredOrchestrationAuthority) already implements durable, crash-safe reattachment for a surviving daemon -- it was simply never exercised against a full unit restart before now. Proven via a systemd-in-Docker recovery test: a live PTY session's shell process, its daemon, and the daemon's cgroup scope were all confirmed unchanged across a real systemctl restart of a Type=simple/KillMode=mixed unit, while the main process pid changed (confirming the unit actually restarted) and the new process's health payload recognized the surviving daemon as adopted and live. A fresh write into the same PTY post-restart reached the same running shell. Ordinary terminal create/work/release and the #18789/#18790 worker-release reap-fix regression tests are unaffected. Fixes #19408 * fix(daemon): probe the real per-UID XDG_RUNTIME_DIR before trusting the process's own env isDurableDaemonScopeSupported()/buildDurableDaemonScopeCommand() trusted the current process's own XDG_RUNTIME_DIR env var first, falling back to /run/user/<uid> only when that var was unset entirely. On mtl-02, [email protected]'s RuntimeDirectory= hardening directive makes systemd export XDG_RUNTIME_DIR=/run/orca_serve/factory into the unit's process -- a private scratch dir that shares the env var's name but has nothing to do with the user session bus. /proc/<pid>/environ on that host confirmed exactly that path plus DBUS_SESSION_BUS_ADDRESS=disabled:, while the real bus was reachable the whole time at /run/user/985 (confirmed via systemctl --user is-system-running with that dir exported by hand). The probe treated the hardened override as authoritative, found no bus socket there, and reported unsupported on every launch -- so the cgroup-escape fix from #19408/#19430 never actually engaged on real hardware, even though tonight's factory deployment picked it up. Fix: resolveUserRuntimeDir() now always tries the conventional /run/user/<uid> path first (computed independently via getuid(), never trusted from env), checking for a genuinely connectable bus socket via statSync(...).isSocket() rather than a bare existsSync. It falls back to the process's own XDG_RUNTIME_DIR only when that canonical path has no reachable bus -- covering hosts that legitimately have no /run/user/<uid> at all but do have a working bus wherever their own environment points. buildDurableDaemonScopeCommand() now explicitly sets XDG_RUNTIME_DIR to whichever path this resolution picked, rather than inheriting the spread env's (possibly hardened-wrong) value. Both isDurableDaemonScopeSupported() and buildDurableDaemonScopeCommand() gained an injectable canonicalRuntimeDir parameter (defaulting to the real computed path) so tests can exercise the hardened-override scenario deterministically with a real, connectable AF_UNIX socket fixture instead of the live host's actual runtime directory. Docker's stock jrei/systemd-ubuntu test container never had this hardening directive, so this gap was structurally invisible to the container-based verification in #19430 -- only caught against real mtl-02 hardware. * fix(daemon): report the daemon's own pid over the ready handshake, not systemd-run's The launcher used to infer the daemon's identity pid from the immediate spawned child (`child.pid`). On the durable-scope path that child is `systemd-run --user --scope`, not the daemon, so the launcher was asserting an identity it had no authority over. `DaemonReadyIdentity` now carries a required `pid` populated from `process.pid` inside the daemon itself, and `daemon-launched-child.ts` takes `launchedIdentity.pid` from that self-report. Both sides of the `holdDaemonAdoptionLease` pid comparison therefore originate inside the daemon process, which is the idiom this branch already uses for cgroup membership (`detectOwnCgroupScopeUnit` reads `/proc/self/cgroup` rather than trusting what the launcher intended). Note on the reported consequence: `systemd-run --scope` registers its *own* pid on the transient scope unit and then `execvpe()`s the target command -- same pid, no intermediate process -- so adoption did not in fact fail on systemd >= 206 (verified against systemd 255.4-1ubuntu8.17 and current main, `src/run/run.c` `start_transient_scope()`). The fix stands on its own merits: it removes a silent dependency on that exec-vs-fork implementation detail, which a `systemd-run` shim earlier in PATH or any future systemd change would have broken with no diagnostic. `terminateLaunchedDaemonChild` was audited and deliberately left on `child.pid`: for the same execve-preserves-pid reason that pid is either still systemd-run mid-scope-setup (killing it correctly aborts the launch) or already the daemon, so it targets the right process either way. Regression coverage: `daemon-launched-child-identity.test.ts` pins the identity source, and `daemon-ready-identity.test.ts` gains pid-validation cases. Ready-message fixtures across the `daemon-init-*` suites were updated for the now-mandatory field. Addresses: #19430 (comment) #19430 (comment) * test(daemon): assert cgroupUnit in the pid-file parse contract `parseDaemonPidFile` returns `cgroupUnit` on every branch as of the durable-scope commit on this branch, but five exhaustive `toEqual` assertions in daemon-health.test.ts still described the pre-scope shape, so they failed on the branch independently of any later change. Adds the field to those expectations. Deliberately not relaxed to `toMatchObject`: asserting the full parsed shape is what makes these tests catch a field silently dropped from the pid-file contract. * refactor(daemon): resolve the canonical user runtime dir at one point The per-UID path cannot change for a live process, so compute it once into a module const instead of threading the same default call through three signatures, and drop the try/catch around a getuid() that cannot throw once it exists. Trims the module prose to the non-obvious facts and corrects the pid-file record comment: an unscoped daemon writes null; only records no daemon wrote are absent. * test(daemon): clean up the cgroup-scope fixtures and assert a verdict The cgroup fixture tracked only the file it wrote, leaking one temp dir per case. Drains both fixture lists with splice so the pop-may-be-undefined guards go away, and replaces a not-throw/typeof-boolean pair with the verdict it was circling: no resolvable runtime dir means unsupported. * refactor(daemon): share the detached child options across both launch paths cwd, detached and stdio were repeated in the fork and systemd-run branches, which left the two comments explaining them hovering over the env block instead. Names them once so each branch carries only its own delta. * refactor(daemon): validate the ready pid like every other field typeof-first narrows the value, so the two 'as number' casts the isSafeInteger check needed disappear and the pid guard reads like the startedAtMs guard below it. * fix(daemon): don't retry the launch unscoped after losing the endpoint race A scoped attempt that lost the endpoint to another daemon was retried unscoped: a second doomed fork, a misleading 'cgroup-scope launch failed' warning, and the same DaemonEndpointUnavailableError the caller was already going to adopt on. Rethrows it instead, since no launch mode can win a race that is already lost. Also drops a private alias for DaemonChildSpawnOptions and the two 'as number' casts on child.pid in the startup-failure cleanup. * fix(daemon): unlink the pid record by the pid the daemon published The record holds the daemon's self-reported pid, so match on that rather than on the immediate child's, which is the systemd-run wrapper's until it execs. * fix(daemon): route the scope launch through the child-process chokepoint The two files this PR added imported `node:child_process` directly, which `child-process-import-boundary.test.ts` fails on deterministically: the offender count went 155 -> 157 against a pin of exactly 155. Raising the pin or listing the files is what that test explicitly forbids, and the allowlist's own note says a split "moved the import, it did not add one" -- so the fix is to get both new files off the module and put the count back at 155. - `daemon-cgroup-scope.ts`: the `systemd-run --version` probe now uses `runProcessSync` instead of `execFileSync`, so it gets the shared spawn decisions. Kept synchronous deliberately: `launchDaemonChild` attaches the readiness listener in the same tick it is called, and an await before the spawn moves the child past that tick. A non-zero exit is data rather than a throw here, so the verdict now checks `code === 0 && !timedOut`. - `daemon-launched-child-spawn.ts`: the scoped launch uses `spawnProcess`, and the long-standing unscoped launch keeps `fork` semantics through a new `forkProcess`. - `src/shared/child-process/fork-process.ts`: the fork arm of the chokepoint. `spawnProcess` cannot express a Node child with an IPC channel started from a module path under an overridden `execPath`, and the existing launch tests are written against `fork`'s contract, so a spawn rewrite would have changed module resolution, `execPath` and `execArgv` at once. It passes `windowsHide: true` -- the flag every other call site in that directory sets, reachable via an assertion because `ForkOptions` omits it -- which keeps `windows-console-visibility.test.ts` at its pin of 65 too. Both ratchets pass with both pins and both allowlists untouched. Docs: `orcad-operations.md` and `headless-linux-server.md` still described the limitation this PR removes as permanent. Both now describe the durable-scope survival path and its preconditions (systemd as PID 1, a reachable user bus / `loginctl enable-linger`, `systemd-run` on PATH), and scope the old text to the unscoped-fallback case, pointing at `health.terminalDaemon.cgroupUnit` as the way to tell the two apart on a running host. * fix(daemon): seal the cgroup capability probe from the host and correct KillMode=mixed docs The capability probe consulted the host's own /run/systemd/system marker and spawned the real systemd-run binary, so the hermetic unit tests could only pass on a systemd host (and fail closed otherwise, even with faked bus sockets). - Thread systemdBootPath and runVersionProbe as test seams through isDurableDaemonScopeSupported, defaulting to the real boot marker and systemd-run --version probe in production. - Narrow the injected probe to the ProcessResult slice it consumes. - Cover: no-systemd-boot, non-zero probe exit, and probe-timeout cases. - Correct KillMode=mixed semantics in the docs: the cgroup-wide SIGKILL fires the instant the main process exits, not after TimeoutStopSec; document the Docker-container caveat and add KillMode=mixed to the multi-service template. * fix(daemon): satisfy assertion checks in scoped launch * fix(daemon): satisfy anti-slop and console guards * test(serve): update shutdown docs assertions for daemon scope * fix(daemon): migrate adopted legacy scopes * docs: qualify restart safety by daemon scope * docs(daemon): qualify Upgrade restart prose with durable scope caveat Align the Upgrade section in docs/reference/headless-linux-server.md with the earlier preservation section and docs/reference/orcad-operations.md: a service restart terminates live processes only when running under the unscoped fallback, and stops should be treated as destructive unless health.terminalDaemon.cgroupUnit names an orca-daemon-*.scope. Update the shutdown workflow test assertion in config/scripts/headless-serve-shutdown-workflow.test.mjs to match. * fix(daemon): harden legacy scope migration --------- Co-authored-by: Lesley Murfin <[email protected]> Co-authored-by: m4air <[email protected]>
Review changes addressed (head
|
…ached it (#22119) #18790 added the freebuff agent icon to mobile-agent-icon-assets.ts, which the session page reaches. It merged between #22114's closure measurement (4,332) and its merge, so main pins one module short. Measured on main's tip 059ee59 and named by diffing the closure at 226f4a0 against it. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…reebuff agent) This reverts commit 0677271. #18790 was merged as one squash commit that carried two unrelated changes: a process-incarnation fallback for reaping leaked orchestration worker terminals, and an unannounced "Freebuff" third-party agent (catalog entry, icon, locale strings, README rows). The Freebuff agent was never meant to ship, so the whole PR is reverted; the reap fix should be re-submitted on its own. Until that re-land, a worker whose durable terminal handle goes stale is again reported missing on release/stop instead of being re-found through its process incarnation, so its terminal can leak on Remote Server. The mobile session page closure pin moves 4207 -> 4206: the revert drops the freebuff icon #22119 pinned (-1), measured on this branch.
…reebuff agent) (#22601) This reverts commit 0677271. #18790 was merged as one squash commit that carried two unrelated changes: a process-incarnation fallback for reaping leaked orchestration worker terminals, and an unannounced "Freebuff" third-party agent (catalog entry, icon, locale strings, README rows). The Freebuff agent was never meant to ship, so the whole PR is reverted; the reap fix should be re-submitted on its own. Until that re-land, a worker whose durable terminal handle goes stale is again reported missing on release/stop instead of being re-found through its process incarnation, so its terminal can leak on Remote Server. The mobile session page closure pin moves 4218 -> 4219: the revert drops the freebuff icon #22119 pinned (-1), and #22452 had already added two src/shared modules without re-pinning (+2).
Brings main's re-pin of the mobile session route closure (4219) with its revert of #18790; no conflicts.
…undled Freebuff agent) (stablyai#22601) This reverts commit 0677271. a process-incarnation fallback for reaping leaked orchestration worker terminals, and an unannounced "Freebuff" third-party agent (catalog entry, icon, locale strings, README rows). The Freebuff agent was never meant to ship, so the whole PR is reverted; the reap fix should be re-submitted on its own. Until that re-land, a worker whose durable terminal handle goes stale is again reported missing on release/stop instead of being re-found through its process incarnation, so its terminal can leak on Remote Server. The mobile session page closure pin moves 4218 -> 4219: the revert drops the freebuff icon stablyai#22119 pinned (-1), and stablyai#22452 had already added two src/shared modules without re-pinning (+2). (cherry picked from commit 7a4f080)
…terminal handles (#23583) * fix(orchestration): reland process-incarnation reap for stale worker terminal handles Relands the orchestration part of #18790, which #22601 reverted in full because that squash commit also bundled an unannounced agent. Only the worker terminal-reap fix returns; no agent catalog changes. When a worker's saved terminal handle stops resolving while its process is still running, worker-show/read, worker-stop and worker-release now re-mint a live handle from the recorded process incarnation (exact pty id + incarnation id, same host scope) and act on it, instead of reporting the terminal missing and leaving the process running on the host. Fixes STA-8493 * test(orchestration): spy on the public incarnation methods instead of casting the runtime
Add Freebuff launch support and execution-host status reporting for the sidebar, including running, question, blocked, and settled states. Validate against captured CLI transcripts and real rendered sidebar evidence. Cross-referenced community implementations #17065, #20839, and the Freebuff portion of #18790. Preserve their agent/catalog/mobile/documentation coverage and add canonical status publication and regression tests. Co-authored-by: Harkaran Brar <[email protected]> Co-authored-by: Prarambha369 <[email protected]> Co-authored-by: Lesley Murfin <[email protected]>

ELI5
Orca saves which worker process owns a terminal. Sometimes its saved terminal address stops working while that process is still running. This change uses the saved process identity and machine identity to find the same terminal again, so reading and stopping the worker still works. It refuses to act when the identity cannot be proved.
Behavior
When the recorded terminal handle no longer resolves, worker observation looks up the recorded process incarnation on the recorded host and obtains a current handle. Worker read, stop, and release use that handle. Release still checks ownership and process identity before archiving and closing; a reused PTY with another incarnation is excluded.
If no handle resolves, positive host evidence of process exit may settle release only when the archive requirements are satisfied. Loss of contact remains
unverifiable. Structured workers retain their separate release path.Direct CLI PTY handles already survive ordinary graph reload on current main. This change covers the remaining unresolvable-handle case; the tests below do not establish that every reconnect leaks a worker process.
Fixes #18737
Fixes #18789
Validation
Reviewed contributor head:
2e026a64e00b9d6c4390d6fe092855b60f128f44.Additional runtime-composition test commit:
0e3a94773758d17eff1dc0dfb05dd696139452f0.Current head:
7b3f8b31ebe56a02252ef7db066b3328d7845e69— latest verified head, after the two follow-up commits noted below.pnpm tc:node, new-test lint/format, andgit diff --checkpassed. No claim is made here that the full application build or full repository suite was rerun at this head.8e839ade1b(test(orchestration): pin the incarnation read scenario to the reminted terminal) strengthens the previously-weak read-scenario assertion, per an independent review finding: the test now pins the read to the reminted terminal instead of accepting either handle. Verified failing under a targeted mutation of the resolution path and passing otherwise.7b3f8b31ebapplies two nits from an independent adversarial code review: a logically-redundant prefix guard was dropped frommatchesProcessIncarnation, andworkerTerminalLeaseIsCurrent'sliveTerminalHandleparameter became required instead of optional, removing a stale-handle fallback path. Verified:tscclean, 296/296 targeted tests passed, lint/format clean, no behavior change.Every test ran with
ORCA_BACKGROUND_LAUNCH=1. No application window was launched or focused. Windows runtime execution remains unverified; drive-letter PTY identifiers and SSH/relay colon-bearing identifiers have unit coverage.Visual proof
N/A: no rendered UI surface changes. The behavioral tests above cover terminal recovery and identity fencing. The separate Linux native PTY exercise confirms OS-process termination; it does not simulate a full transport reconnect.
Compatibility and performance
No persisted schema, RPC frame, pairing, or mobile-client contract changes. The new observation handle is internal. Existing local/SSH host identity and folder-workspace behavior are preserved. No git-provider-specific behavior or platform-dependent command is added.
Fallback is a linear scan of tracked PTYs. It adds no polling, subprocesses, or cache. Worker read/show can repeat this scan while the durable handle is unresolved, so it is not limited to release alone.
AI disclosure
The contributor used an Anthropic Claude coding agent for investigation, implementation, and tests, with human review. Additional review and runtime-composition tests were produced with Codex.
Author
@LesleyMurfin
Linked Issue
Architectural Context (RFC #21556)
term_*references upon release, but never send SIGKILL to the underlying OS process tree, stranding slave PTY descriptors in systemd cgroups.hostId, pid, startTime), stopping unbounded memory leaks (44.9 GB RAM / 70 dead PTYs / EAGAIN thread exhaustion).Rebase verification update (2026-09-21)
Rebased onto the current
mainand fixed the two test-only overload errors caused by the newer typed RPC method registry by using the repository'seraseRpcMethodstest adapter. Verified withpnpm tc:nodeand the three worker-reap suites: 19/19 tests passed. The production worker-reap logic is unchanged.