Repository navigation
Daemon terminal-host inspection: a degraded read is unverifiable, never an agent exit - #17003
brennanb2025 wants to merge 15 commits into
Conversation
577fc12 to
4146f8e
Compare
7702a7d to
a8c7202
Compare
4146f8e to
69d6db9
Compare
a8c7202 to
82e2fde
Compare
69d6db9 to
1b5b9b4
Compare
82e2fde to
abb7f33
Compare
1b5b9b4 to
5dfbe98
Compare
5dfbe98 to
912a20d
Compare
…eads into exit evidence
…agent exit
The daemon terminal-host's inspectProcess collapsed every foreground read into
`{ foregroundProcess, hasChildProcesses }`, so a read that observed nothing —
node-pty's POSIX title read silently falling back to the spawned shell, or a
degraded/failed `ps` identity scan letting the cached agent identity go stale —
produced the same payload as a genuinely idle shell. The agent-completion
monitor reads that payload as positive exit evidence and reports a still-running
agent as finished.
The host now reports per-probe live/unverifiable/exited evidence beside
byte-identical legacy fields (docs/reference/ssh-execution-boundary.md), the
same additive `processEvidence` contract the relay and local-provider legs use.
A shell-shaped title is an observation only while a completed scan corroborates
it; a scan that could not answer — unavailable, table missing the pane, or
thrown — settles as unverifiable and withdraws that corroboration.
`SubprocessHandle.observeForegroundProcess` is optional and a handle that omits
it reads as `unverifiable`, so the unknown case falls toward the conservative
arm rather than toward a synthesized observation.
Ablation on the refreshed composed tree showed the constant itself was unpinned: widening SHELL_TITLE_SCAN_CORROBORATION_MAX_AGE_MS to Infinity left the whole matrix green. A wedged `ps` is the trade-off this PR accepts deliberately, so the bound that scopes it is load-bearing.
…s on Deepens the terminal-host evidence coverage the gate audit found thinnest. Each arm below goes red with that arm reverted alone: - an empty node-pty title read is a failed read, not an observed exit - a title read that throws is unverifiable - a corroborating scan followed by an unavailable one retires the corroboration rather than inheriting it (the settlement has to be recorded on unavailable scans too, or the last successful one stands forever) - the pty's own exit stays a positive observation, so the conservative arms cannot swallow a real completion - the children verdict never outranks a non-observed foreground The Windows unverifiable-job hold gains the read the existing assertion could not reach: a read returns before the scan it schedules settles, so the hold has to outlive that scan too. Ablating the hold with only the pre-existing assertion present stays green; it goes red with the added one.
912a20d to
7eefcda
Compare
…nnanb2025/coercion-daemon-inspect-r2
Greptile SummaryThe PR adds evidence-aware daemon process inspection so degraded foreground reads remain unverifiable rather than being interpreted as agent exits.
Confidence Score: 4/5The PR is not yet safe to merge because cached Windows process-table results can still retire a live agent using a timestamp newer than the table they represent. The POSIX provenance fix is preserved through the shared snapshot cache, but Windows foreground resolutions omit equivalent provenance while consuming cached process tables; the refresh path consequently substitutes the later request time and leaves the previously reported false-completion race reachable. Files Needing Attention: src/main/daemon/pty-subprocess/foreground-identity-refresh.ts, src/main/providers/agent-foreground-process.ts, src/main/windows/windows-process-table.ts
|
| Filename | Overview |
|---|---|
| src/main/daemon/pty-subprocess/foreground-identity-refresh.ts | Adds scan settlements and provenance-aware corroboration, but Windows cached scans still lack their originating timestamp. |
| src/shared/process-table-snapshot.ts | Adds scan-start provenance while preserving it across cached, in-flight, and queued fresh POSIX snapshot reads. |
| src/main/providers/agent-foreground-process.ts | Propagates POSIX process-table provenance, while the Windows resolution remains provenance-free. |
| src/main/daemon/pty-subprocess/foreground-process-tracker.ts | Introduces evidence-bearing foreground observations and guards confirmation-driven identity retirement using scan provenance. |
| src/main/daemon/terminal-host-process-evidence.ts | Conservatively derives child-process verdicts from foreground evidence without flattening unverifiable reads into exits. |
| src/main/daemon/terminal-host.ts | Publishes evidence-aware process inspection while retaining legacy foreground behavior. |
| src/main/daemon/session-subprocess-handle.ts | Adds an optional evidence channel whose absence conservatively resolves to unverifiable. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Daemon inspects PTY] --> B[Read foreground title]
B --> C{Title identifies a live agent?}
C -->|Yes| D[Publish observed/live evidence]
C -->|No, shell-shaped| E[Consult latest process scan settlement]
E --> F{Available, agent-free, and sufficiently current?}
F -->|Yes| G[Publish observed/exited evidence]
F -->|No| H[Publish unverifiable evidence]
H --> I[Completion monitor re-arms]
G --> J[Completion monitor may complete]
Reviews (11): Last reviewed commit: "Merge commit 'a7ce56571ee14cbb0f99ae3f7b..." | Re-trigger Greptile
…ment The synchronous title fast path stamps a recognized agent without running a scan, so the last agent-free settlement can still sit inside the 30s window while an agent is live. When node-pty's title read then falls back to the spawned shell file, that stale settlement corroborated the shell title and the tracker published `observed(shell)` for a running agent — which the completion monitor reads as the agent having exited. Corroboration now also requires the settlement to be no older than the most recent positive agent observation, which `cachedAgentForeground.refreshedAt` already records for both the scan and the fast path. An idle pane holds no cached identity, so healthy corroboration is unchanged. Verified against the checks skipped by --no-verify (no node_modules in the throwaway worktree): oxlint, oxfmt and the full src/main/daemon suite were run on byte-identical file contents in the stack tip's worktree.
…settled The settlement was stamped when the scan settled, but its process table was read when the scan started. An agent that appears in between is invisible to that snapshot, so a pre-agent scan settling after the title fast path recognized the agent still had the newer timestamp and went on corroborating the shell title — the same false completion the previous commit set out to close, one ordering over. Carry `startedAt` on the settlement and order against that. The 30s staleness bound still runs off `at`, which is the right clock for "how old is this answer".
Dating corroboration by the scan's snapshot closed the direct path but not the one through retirement. A scan whose process table predates the agent still settles "no agent", and when the title has already degraded back to the shell, retireStaleForegroundIdentity clears the cached identity on that answer. The corroboration guard's no-evidence arm then accepts the very same stale settlement, so the live agent reads as an observed idle shell again. Retirement now refuses an identity stamped after this scan sampled the table, which is the same ordering rule the corroboration check already applies. Ordinary retirement is untouched: an agent that exits was stamped before the scan that finds it gone.
…n it asked The two ordering guards on the shell-title corroboration path both compare against `now` — the moment this pane's refresh started. But the POSIX process table is a process-wide 500ms cache shared by every pane (process-table-snapshot.ts), so a refresh is routinely answered from a scan another pane started earlier. `now` then claims the table is more current than it is, and an agent that began in that window is missing from rows the guards treat as newer than it. The whole chain follows from there: the settlement is dated by the ask, so retirement clears an identity the scan never sampled, and the corroboration guard's no-evidence arm accepts the same stale settlement — a live agent publishes as an observed idle shell, which the completion monitor reads as `exited`. The reader now stamps when each scan began, alongside the capture time TTL reuse already needs, and carries it out through the resolver as `tableScanStartedAtMs`. Ordering uses the measured scan; `now` remains the fallback for answers that read no table (Windows job evidence, early returns).
…s proof Both ordering guards on the shell-title corroboration path accepted the ambiguous equal case. At millisecond resolution a table captured in the agent's own millisecond is unordered against it, not simultaneous — it may never have sampled the agent. Read as "at least as new", a pre-agent scan retired the live identity and then corroborated the degraded shell title, publishing `exited` for a running agent. Both comparisons now require the scan to be strictly newer, so the tie keeps the agent and an unknown order resolves to `unverifiable` rather than to an exit.
…r saw confirmForegroundProcess cleared the pane's agent identity on any answer that named no agent, without comparing the scan's provenance. A scan that starts before the agent is recognized and resolves after it read a process table that could not have contained the agent, so its silence retired a live one. The cost is not only the lost name: retirement nulls cachedAgentForeground, and the shell-title corroboration gate treats absent agent evidence as nothing to outrank, so the next degraded shell title is read as an observed idle pane. Guarded with the same comparison the refresh path already makes, now extracted as agentEvidenceOutdatesScan and shared by all three readers.
…nnanb2025/coercion-daemon-inspect-r2
| }) | ||
| .then<string | void>( | ||
| ({ processName, processId, available, anchorPidForeign, tableScanStartedAtMs }) => { | ||
| scanStartedAt = tableScanStartedAtMs ?? now |
There was a problem hiding this comment.
Windows snapshots lose provenance
When a Windows refresh consumes a cached agent-free process table captured before the agent was recognized, tableScanStartedAtMs is absent and this line substitutes the later request time. The stale scan can then retire the live-agent identity, allowing a degraded shell title to publish an exit and fire completion.
Knowledge Base Used:
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
ELI5
Orca watches each terminal to decide when an agent has finished. On macOS (and any daemon-hosted pane) it asks the terminal daemon two questions: what program is in the foreground? and does the shell have children?
The daemon answered those questions with a plain name and a plain boolean — and it gave the same answer when it failed to look as when it looked and genuinely saw an idle shell.
Two ways it failed to look:
psidentity scan behind the 1-second cache can be degraded (apsfork that times out, a snapshot that never contained the pane) so the cached agent identity quietly goes stale without ever being disproven.Either way the daemon published
{ foregroundProcess: 'zsh', hasChildProcesses: false }— the exact payload the agent-completion monitor reads as positive proof the agent exited. A live agent got reported as finished.docs/reference/ssh-execution-boundary.mdis explicit: loss of contact is never evidence of process death, and the vocabulary islive/unverifiable/exitedwith no synonyms. This is the daemon leg of that contract, and the only route left in this class that can turn a live agent into an exit verdict.User-facing before / after
psfork times out while codex is runningNothing changes for a healthy pane. The only behavior that changes is what happens when a probe fails.
The fix
TerminalHost.inspectProcessnow returns per-probe evidence beside byte-identical legacy fields, using the same additiveprocessEvidencecontract the relay leg (#16926) and local-provider leg (#16955) already publish. Perdocs/reference/remote-wire-compatibility.mdthis is a new optional field on an RPC result: a daemon that predates it omits the field and readers fall back to the legacy collapse, and an old client ignores it and sees exactly the content it saw before.The load-bearing rule: a shell-shaped title is an observation only while a completed scan corroborates it. A scan that could not answer — unavailable, table missing the pane, or thrown — settles as
unverifiableand withdraws that corroboration.Fall-through direction (the shape that bit #16900 / #16908 / #16926)
Every conditional added here falls toward the conservative arm:
deriveChildProcessesEvidenceguards onverdict !== 'observed'first and returnsunverifiable; only a positive observation can reachliveorexited.SubprocessHandle.observeForegroundProcessis optional, and a handle that omits it readsunverifiable— an unknown handle cannot synthesize an observation.catchreturnsunverifiable, notnull; the identity refresh'scatchrecords an unavailable settlement rather than leaving the previous corroborating one in place.There is no
switchin this change. Nocatchreturnsfalse, no?? nullis read downstream as an exit, and nounavailableis flattened into a boolean:unverifiabletravels all the way to the completion monitor, which already treats it as "re-arm, do not complete" (#16926).Failing-first proof
The repro is committed before the fix (
bc23b83752) so the failure is visible in history. Both runs under the project config (--config config/vitest.config.ts):Pre-fix (repro commit's
src/):Post-fix:
The three new unit suites also fail against pre-fix production code — two by assertion, one by missing module (
terminal-host-process-evidencedoes not exist yet):A missing-module failure is weak evidence on its own, so every hunk is additionally pinned by ablation below.
Ablation table
Each production hunk reverted alone, full matrix re-run under
--config config/vitest.config.ts. Baseline: 8 files / 152 tests passing.terminal-host.tsinspectProcesspublishes evidence (legacy fields held constant)terminal-host-process-evidence.tsverdict !== 'observed'→unverifiableguardterminal-host-process-evidence.tsobservednon-shell →livearmsession-subprocess-handle.tsunverifiable(→ synthesizedobserved)pty-subprocess/subprocess-handle.tsforeground-process-tracker.tsforeground-identity-refresh.tsforeground-identity-refresh.tsforeground-identity-refresh.tsSHELL_TITLE_SCAN_CORROBORATION_MAX_AGE_MS)Two remaining hunks are type-only and structurally unpinnable by a runtime test, stated rather than hidden:
session-subprocess-handle.ts— theForegroundProcessObservationtype and the optional-method signature. Making the method required again is caught bypnpm tc, not by a test.daemon-pty-process-inspection.ts—processEvidence?on theclient.request<…>generic. The daemon socket returns parsed JSON and the generic is a cast, so the field crosses the wire identically with or without the annotation. It is documentation-grade typing; the wire test proves the runtime behavior it describes.Test coverage added
tests/e2e/daemon-completion-evidence/daemon-inspection-unverifiable-completion.unit.test.ts— the realTerminalHost+ real subprocess handle + real foreground tracker + realDaemonPtyAdapter+ real renderer completion coordinator, over a scriptedps. Proves the monitor consequence, not just the payload.tests/e2e/daemon-completion-evidence/daemon-inspection-evidence-wire.unit.test.ts— the same evidence over the real daemon socket (DaemonServer → request router → JSON socket → adapter), so the additive field is proven to actually cross the protocol.src/main/daemon/terminal-host-process-evidence.test.ts— every arm of the collapse, asserted withtoBeon the verdict.src/main/daemon/terminal-host-inspection-degraded-handle.test.ts— a handle with no evidence channel.src/main/daemon/pty-subprocess-foreground-observation-evidence.test.ts— each scan outcome (resolved-available, resolved-unavailable, rejected) and its effect on corroboration.Also brackets the 30s corroboration window from both sides against a permanently wedged
ps(a scan that starts and never settles), so the availability trade-off below is bounded by a test rather than only by a constant.Parent suites were run, not just the new files.
Gates
pnpm tc(node + web)oxlint(changed files +src/main/daemon)max-linesdisable or bumpgit diff --checkOK — 87 grandfathered suppression(s), no new bypasseschild-process-import-boundary+port-scan-command-import-boundarynode:child_processimportsrc/main/daemon(149 files / 1691 tests)src/renderer/src/components/terminal-pane(406 files / 3921 tests)tests/e2e/daemon-completion-evidencesession.tssits at exactly 300/300 effective lines (it was already at 299 before this change; the fallback body lives insession-subprocess-handle.tsprecisely to stay under the cap).Pre-existing failures, not introduced here
These fail identically on
origin/main— verified by checking outorigin/main'ssrc/into this tree and re-running the same files:src/main/ipc/pty-spawn-env-agent-overlays.test.ts,pty-spawn-env-codex-home-routing.test.ts,pty-login-shell-startup-commands.test.ts,pty-serializer-settlement-mapping.test.ts— 10 testssrc/main/providers/provider-dispatch.test.ts,local-pty-provider-windows-shell-launch.test.ts— 3 tests (AppEnvironment not initialized)Provenance: rescued WIP vs. written and defended here
This lane resumed a stalled one. Being explicit about which is which:
Kept from the WIP (reviewed, and I stand behind it):
terminal-host-process-evidence.tsand theTerminalHost.inspectProcessrewrite.foreground-process-tracker.ts→foreground-identity-refresh.tssplit. I diffed the movedscheduleRefreshbody line-by-line against the pre-split original: it is a faithful move plus the settlement recording. The split is required, not cosmetic — a merged file is ~446 raw lines against a 300-line cap.isShellTitleCorroboratedand the 30s window.Discarded from the WIP:
observeForegroundProcessrequired onSubprocessHandleand mechanically added a hardcodedobserved(null)double to 38 test files. That is a landmine — a constant "positive exit evidence" stub in every daemon suite — and it had already brokendaemon-pty-adapter-session-adoption.test.ts, which mocksgetForegroundProcessand was silently no longer consulted (2 failures). I reverted all 38 files and made the method optional with a conservativeunverifiablefallback, which fixes the failures, removes the churn, and makes the unknown case fall the safe way by construction.Session.getForegroundProcessremoval, and itssession.tsshape, which pushed the file overmax-lines.Written here: the optional-handle contract and
observeSubprocessForeground, all three unit suites, the ablation matrix, and every verification claim in this PR.What I did NOT verify
Stated plainly rather than implied:
judgeCachedAgentJobEvidence, job-object membership) are carried over unchanged and were not exercised on a real Windows host. The corroboration window (30s) is sized against the Windows idle refresh cadence (15s) by reading the constants, not by measuring on Windows.confirmForegroundProcessstill has acatch { return null }on both the daemon and adapter legs. It feeds the tab-bar agent identity (pane-foreground-agent-tracker), not the exit verdict, so it is out of this route's scope — but it is an adjacent unaudited coercion and I am flagging it rather than leaving it implied.ps), corroboration expires after 30s and that pane stops producing process-exit completions until the scan recovers. The 30s bound is pinned by test (widening, narrowing, or removing it all fail). That is the correct reading of the contract — we genuinely cannot ask — and the hook-based completion channel is unaffected, but it is a real behavior change under sustained host distress, not a free win.Stacking
Based on
brennanb2025/local-inspection-unverifiable-r1(#16955), which is itself based onbrennanb2025/relay-completion-unverifiable-r1(#16926). This change depends on their code:src/shared/pty-process-inspection-evidence.ts, the completion monitor'sreadPtyProcessInspectionEvidence, andagent-foreground-process.ts's table-missing-pane availability fix. Retarget tomainonly after both parents land — not before.Refreshed onto the moved parent (2026-08-28)
#16955 was rebased onto #16926's full head, which left this branch on a superseded base and GitHub reporting
CONFLICTING. This branch is now rebased ontoa8c720296e(#16955's current head, itself on #16926's3ca44ad9b5).git range-diffreports both original commits as=— the refresh moved the base, it did not alter a line of the change.Re-verified on the composed tree, not assumed from a clean merge:
processEvidence?together with its import typechecks clean, so it remains documentation-grade typing rather than an enforced gate.readPtyProcessInspectionEvidence— including across real JSON socket serialization — for all six observation arms. None degrade tomalformed, and anunverifiableforeground never yields anexitedchildren verdict.