Skip to content

Daemon terminal-host inspection: a degraded read is unverifiable, never an agent exit - #17003

Closed
brennanb2025 wants to merge 15 commits into
brennanb2025/local-inspection-unverifiable-r1from
brennanb2025/coercion-daemon-inspect-r2
Closed

brennanb2025 wants to merge 15 commits into
brennanb2025/local-inspection-unverifiable-r1from
brennanb2025/coercion-daemon-inspect-r2

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1415 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1411
Prod 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​547 $\color{#cf222e}{\Huge{\mathbf{−}}}$​231 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​316

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:

  • node-pty's POSIX foreground-title read silently falls back to the spawned shell's name when the native read fails. "zsh" can mean the shell really is in front, or we couldn't read the title.
  • the async ps identity scan behind the 1-second cache can be degraded (a ps fork 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.md is explicit: loss of contact is never evidence of process death, and the vocabulary is live / unverifiable / exited with 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

Before After
ps fork times out while codex is running pane reports "agent done", tab clears its working state, completion fires pane holds; the monitor re-arms and waits for a real answer
process table returns without the pane's subtree same false completion same hold
node-pty title degrades to the shell name mid-run same false completion same hold
the agent genuinely exits completion fires completion fires, unchanged
the reads recover after a degraded window (already mis-fired) completion fires on the first corroborated read

Nothing changes for a healthy pane. The only behavior that changes is what happens when a probe fails.

The fix

TerminalHost.inspectProcess now returns per-probe evidence beside byte-identical legacy fields, using the same additive processEvidence contract the relay leg (#16926) and local-provider leg (#16955) already publish. Per docs/reference/remote-wire-compatibility.md this 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 unverifiable and withdraws that corroboration.

Fall-through direction (the shape that bit #16900 / #16908 / #16926)

Every conditional added here falls toward the conservative arm:

  • deriveChildProcessesEvidence guards on verdict !== 'observed' first and returns unverifiable; only a positive observation can reach live or exited.
  • SubprocessHandle.observeForegroundProcess is optional, and a handle that omits it reads unverifiable — an unknown handle cannot synthesize an observation.
  • the tracker's catch returns unverifiable, not null; the identity refresh's catch records an unavailable settlement rather than leaving the previous corroborating one in place.

There is no switch in this change. No catch returns false, no ?? null is read downstream as an exit, and no unavailable is flattened into a boolean: unverifiable travels 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/):

 × does not conclude an agent finished when the daemon reads degrade
 × still confirms a real exit once the table answers again
 × publishes unchanged legacy fields beside the evidence
 Test Files  1 failed (1)
      Tests  3 failed (3)

Post-fix:

 Test Files  2 passed (2)
      Tests  4 passed (4)

The three new unit suites also fail against pre-fix production code — two by assertion, one by missing module (terminal-host-process-evidence does not exist yet):

 FAIL  src/main/daemon/terminal-host-process-evidence.test.ts
 Error: Cannot find module './terminal-host-process-evidence'
 FAIL  pty-subprocess-foreground-observation-evidence.test.ts › withholds observation from a shell title no scan has corroborated
 AssertionError: expected undefined to be 'zsh'
 ... 7 failed

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.

Hunk File What was reverted Tests failing
H1 terminal-host.ts inspectProcess publishes evidence (legacy fields held constant) 6
H2a terminal-host-process-evidence.ts the verdict !== 'observed' → unverifiable guard 6
H2b terminal-host-process-evidence.ts the observed non-shell → live arm 3
H3 session-subprocess-handle.ts evidenceless handle reads unverifiable (→ synthesized observed) 2
H4 pty-subprocess/subprocess-handle.ts wiring the tracker's observation onto the handle 8
H5 foreground-process-tracker.ts the shell-title corroboration gate 7
H6a foreground-identity-refresh.ts settlement recorded when a scan resolves 4
H6b foreground-identity-refresh.ts settlement recorded when a scan rejects 1
H6c foreground-identity-refresh.ts the 30s corroboration window itself (SHELL_TITLE_SCAN_CORROBORATION_MAX_AGE_MS) 1

Two remaining hunks are type-only and structurally unpinnable by a runtime test, stated rather than hidden:

  • session-subprocess-handle.ts — the ForegroundProcessObservation type and the optional-method signature. Making the method required again is caught by pnpm tc, not by a test.
  • daemon-pty-process-inspection.ts — processEvidence? on the client.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 real TerminalHost + real subprocess handle + real foreground tracker + real DaemonPtyAdapter + real renderer completion coordinator, over a scripted ps. 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 with toBe on 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

Gate Result
pnpm tc (node + web) clean
oxlint (changed files + src/main/daemon) clean — no suppressions, no max-lines disable or bump
git diff --check clean
max-lines ratchet OK — 87 grandfathered suppression(s), no new bypasses
child-process-import-boundary + port-scan-command-import-boundary pass — no allowlist or baseline edited; this change adds no node:child_process import
src/main/daemon (149 files / 1691 tests) pass
src/renderer/src/components/terminal-pane (406 files / 3921 tests) pass
tests/e2e/daemon-completion-evidence pass

session.ts sits at exactly 300/300 effective lines (it was already at 299 before this change; the fallback body lives in session-subprocess-handle.ts precisely to stay under the cap).

Pre-existing failures, not introduced here

These fail identically on origin/main — verified by checking out origin/main's src/ 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 tests
  • src/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.ts and the TerminalHost.inspectProcess rewrite.
  • The foreground-process-tracker.ts → foreground-identity-refresh.ts split. I diffed the moved scheduleRefresh body 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.
  • isShellTitleCorroborated and the 30s window.
  • Both e2e suites, after confirming the committed repro still fails.

Discarded from the WIP:

  • It made observeForegroundProcess required on SubprocessHandle and mechanically added a hardcoded observed(null) double to 38 test files. That is a landmine — a constant "positive exit evidence" stub in every daemon suite — and it had already broken daemon-pty-adapter-session-adoption.test.ts, which mocks getForegroundProcess and was silently no longer consulted (2 failures). I reverted all 38 files and made the method optional with a conservative unverifiable fallback, which fixes the failures, removes the churn, and makes the unknown case fall the safe way by construction.
  • Its Session.getForegroundProcess removal, and its session.ts shape, which pushed the file over max-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:

  • No live Electron / packaged-app run. Everything here is unit- and socket-level. The user-facing table above is derived from the code path, not observed in a running app.
  • macOS only. The Windows arms of the identity refresh (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.
  • No SSH/relay host run. The relay leg is Keep relay completion evidence live/unverifiable/exited, never coerced #16926's; this change does not touch it.
  • confirmForegroundProcess still has a catch { 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.
  • Availability trade-off, accepted deliberately: if the identity scan never settles (a permanently wedged 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 on brennanb2025/relay-completion-unverifiable-r1 (#16926). This change depends on their code: src/shared/pty-process-inspection-evidence.ts, the completion monitor's readPtyProcessInspectionEvidence, and agent-foreground-process.ts's table-missing-pane availability fix. Retarget to main only 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 onto a8c720296e (#16955's current head, itself on #16926's 3ca44ad9b5). git range-diff reports 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:

  • Every one of the 8 production hunks was reverted alone and re-run against a 29-file / 303-test matrix spanning both parents' consumers. All 6 runtime-bearing hunks still fail red. The 2 hunks the table above marks type-only were re-confirmed type-only: removing processEvidence? together with its import typechecks clean, so it remains documentation-grade typing rather than an enforced gate.
  • This PR's evidence shapes were round-tripped through Keep relay completion evidence live/unverifiable/exited, never coerced #16926's readPtyProcessInspectionEvidence — including across real JSON socket serialization — for all six observation arms. None degrade to malformed, and an unverifiable foreground never yields an exited children verdict.
  • A genuine exit still completes end-to-end through both parents' gates.

@brennanb2025
brennanb2025 force-pushed the brennanb2025/coercion-daemon-inspect-r2 branch from 577fc12 to 4146f8e Compare August 28, 2026 09:16
@brennanb2025
brennanb2025 force-pushed the brennanb2025/local-inspection-unverifiable-r1 branch from 7702a7d to a8c7202 Compare August 28, 2026 11:46
@brennanb2025
brennanb2025 force-pushed the brennanb2025/coercion-daemon-inspect-r2 branch from 4146f8e to 69d6db9 Compare August 28, 2026 12:56
@brennanb2025
brennanb2025 force-pushed the brennanb2025/local-inspection-unverifiable-r1 branch from a8c7202 to 82e2fde Compare August 28, 2026 13:20
@brennanb2025
brennanb2025 force-pushed the brennanb2025/coercion-daemon-inspect-r2 branch from 69d6db9 to 1b5b9b4 Compare August 28, 2026 13:20
@brennanb2025
brennanb2025 force-pushed the brennanb2025/local-inspection-unverifiable-r1 branch from 82e2fde to abb7f33 Compare August 28, 2026 14:04
@brennanb2025
brennanb2025 force-pushed the brennanb2025/coercion-daemon-inspect-r2 branch from 1b5b9b4 to 5dfbe98 Compare August 28, 2026 14:04
@brennanb2025
brennanb2025 force-pushed the brennanb2025/coercion-daemon-inspect-r2 branch from 5dfbe98 to 912a20d Compare August 28, 2026 14:50
…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.
@greptile-apps

greptile-apps Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR adds evidence-aware daemon process inspection so degraded foreground reads remain unverifiable rather than being interpreted as agent exits.

  • Publishes additive foreground and child-process evidence while preserving legacy RPC fields.
  • Corroborates shell-shaped titles with completed process scans and propagates POSIX snapshot provenance through cached reads.
  • Adds focused unit, socket, and completion-path regression coverage.

Confidence Score: 4/5

The 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

Important Files Changed

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]
Loading

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.
brennanb2025 and others added 4 commits August 28, 2026 19:19
…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.
})
.then<string | void>(
({ processName, processId, available, anchorPidForeign, tableScanStartedAtMs }) => {
scanStartedAt = tableScanStartedAtMs ?? now

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 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!

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Superseded by #18078 and #36342.

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