Skip to content

Keep relay completion evidence live/unverifiable/exited, never coerced - #16926

Closed
brennanb2025 wants to merge 14 commits into
mainfrom
brennanb2025/relay-completion-unverifiable-r1
Closed

brennanb2025 wants to merge 14 commits into
mainfrom
brennanb2025/relay-completion-unverifiable-r1

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1655 $\color{#cf222e}{\Huge{\mathbf{−}}}$​274 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1381
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​477 $\color{#cf222e}{\Huge{\mathbf{−}}}$​214 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​263

ELI5

Orca watches the processes inside an SSH relay terminal to notice when an agent (Codex, Claude Code, …) finishes. Those checks run small commands (pgrep, ps) on the remote machine. When a check itself failed — the box is overloaded, or the tool isn't installed — the failure was silently converted into "no agent, no children", which is exactly what a finished agent looks like. Two such polls in a row and Orca declared the agent done while it was still working. Now a failed check says "could not ask" and can never be read as "finished".

User-facing before/after

When you'd hit this: you run an agent in a terminal on an SSH remote and (a) the host comes under heavy load (probes exceed their 3s deadline — e.g. the agent itself is compiling or the box is swapping), or (b) the host is a minimal image without procps (pgrep missing), or (c) the host is Windows, where pgrep never exists.

  • Before: within ~2 poll cycles Orca could mark the agent's turn complete — completion notification fires, the pane reads idle, orchestration treats the worker as settled — while the agent is still running remotely. Anything keyed on completion (notifications, review dispatch, auto-actions) acts on work that isn't done.
  • After: a failed probe is unverifiable: Orca keeps polling (with the existing error backoff, so a struggling host is polled less), keeps the agent marked as running, and only concludes exited from a probe that ran and positively observed absence (pgrep exit 1, ps exit 1, or a Windows process table that observed the PTY root with no descendants). Real exits still complete: the repro suite proves completion fires once probes answer again.

What changed

  • src/relay/pty-process-probes.ts (split out of pty-shell-utils.ts, which was over the line cap): probeProcessChildren and observeForegroundProcess return exhaustive live / unverifiable / exited (children) and observed / unverifiable (foreground) verdicts. Exit-code discrimination separates "ran and matched nothing" (positive absence) from ENOENT/timeout/signal (could not ask). On Windows the children probe reads the native process table the relay already uses for foreground resolution (TTL-cached; replaces a per-poll doomed pgrep fork).
  • src/shared/pty-process-inspection-evidence.ts (new): the contract types, the wire builder that collapses legacy fields exactly as before, and the client-side reader that treats absent evidence as the legacy reading and malformed evidence as unverifiable. The unverifiable arms carry no processName/boolean payload, so an unverifiable result is not assignable where a confirmed observation is expected — no casts added.
  • src/relay/pty-handler.ts: pty.inspectProcess publishes processEvidence beside the unchanged legacy fields.
  • agent-completion-process-monitor.ts: an unverifiable probe re-arms the two-sample exit confirmation and counts as an inspection error (backoff), never as exit evidence. A recognized foreground observation still registers even when the child probe is unverifiable.
  • Type plumbing only: pty-process-inspection.ts, orca-runtime.ts, preload/index.ts, runtime-terminal-inspection.ts carry the optional field through IPC and runtime RPC.

Wire compatibility ruling

Two independent-update surfaces carry this result: the SSH relay mux RPC pty.inspectProcess and the paired-runtime RPC terminal.inspectProcess. Per docs/reference/remote-wire-compatibility.md this change is Rule 1 — a new optional JSON field on an existing frame. It is not a stream opcode (Rule 2 N/A). Rule 3 was audited:

  • Old client + new host: the legacy foregroundProcess/hasChildProcesses fields are computed by the same collapse the old code performed; the wire-contract test asserts byte-identical values under probe failure. The unknown key is ignored by the JSON readers on the old side.
    • One deliberate exception, called out explicitly: on Windows relay hosts the legacy hasChildProcesses was previously a constant false (a coerced pgrep ENOENT — itself an instance of this defect class). It now reports the native-table answer. This is strictly conservative for old clients — true can only block a premature completion, and exited still collapses to false so real exits complete — and it converges Windows semantics with POSIX.
  • New client + old host: processEvidence is absent; readPtyProcessInspectionEvidence returns the legacy interpretation, so behavior is exactly today's (the pre-existing coordinator tests, which build evidence-free results, pin this pairing). The client never requires the field.
  • No protocol version bump needed; tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts passes (5/5) — the terminal-stream surface is untouched.
  • The local daemon protocol has its own versioned inspectProcess and separate host implementation; it is untouched here (absent evidence ⇒ legacy reading) and remains a sibling site.

Pre-fix reproduction (fails on the base commit)

tests/e2e/relay-completion-evidence/relay-inspection-unverifiable-completion.unit.test.ts drives the real relay adapter and RPC handler (execFile failing with timeout kills, the swallowing adapter — not a throwing controller) into the real completion coordinator. On the base commit (3ed7796624) both behavioral tests fail with:

AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
  1st vi.fn() call: [ "codex", { "quietedHookDone": false, "source": "process-exit", "terminalIdleConfirmed": true } ]

— i.e. a coerced probe failure became a confirmed process-exit completion. Post-fix all pass, including the recovery case proving a genuine exit still completes.

Ablation (re-measured at head ad919dc212)

Evidence suite: 9 files, 72 tests, all green at head —
src/shared/pty-process-inspection-evidence.test.ts (6),
src/relay/pty-process-probes.test.ts (30), src/relay/pty-shell-utils.test.ts (12),
src/renderer/src/components/terminal-pane/agent-completion-unverifiable-evidence.test.ts (6),
…/agent-completion-legacy-foreground-agent.test.ts (4),
…/agent-completion-legacy-live-children.test.ts (3),
…/agent-completion-out-of-contract-verdict.test.ts (5),
…/agent-completion-positive-exit-requirement.test.ts (3),
tests/e2e/relay-completion-evidence/relay-inspection-unverifiable-completion.unit.test.ts (3).

Each production hunk reverted alone, tree restored between runs.

Hunk reverted Red
children-probe failure discrimination (catch → exited) 6
foreground ps failure discrimination (catch → observed null) 1
handler stops attaching processEvidence 3
monitor unverifiable / out-of-contract gate removed 4
evidence normalization removed (malformed passthrough) 5
Windows native-table branch removed 3
legacy wire collapse altered (unverifiable → true) 1
exit gate's legacy hasChildProcesses vote removed 3
exit gate's legacy foreground-name vote removed 4
both legacy votes removed together 7

Two corrections to the numbers this table used to carry. The monitor gate row said 5 and
reddens 4; the normalization row said 1 and reddens 5. Both were measured before the
two rows in bold existed, and both are re-measured above.

The two rows in bold were missing entirely

They are the last two commits on this branch, and neither had a row here.

Moving the exit gate onto the evidence union dropped two legacy reads it used to make.
if (result.hasChildProcesses) became a children-verdict test, and
recognizeAgentProcess(result.foregroundProcess) became evidence.foreground.processName.
Each is more conservative in one direction and less conservative in its mirror: a sample
carrying hasChildProcesses: true beside a published children: 'exited', or a legacy
foregroundProcess: 'codex' beside a union reporting {observed, processName: null}, is a
shape the old boolean-only lines refused and the verdict-only gate would have completed on.

Only each field's lossy pole is being removed by this batch — false conflates "no
children" with "could not ask", null conflates "no agent" with "could not ask". The other
pole is a positive observation on every producer, so it keeps its vote. Together the two
votes are worth 7 red tests, which is the coverage the table was silently omitting.

Reliability contract

  • Invariant (relay-completion.exit-evidence): a completion may only be concluded from probes that ran and positively observed absence; "could not ask" (unverifiable) never becomes a completion, on any client/host version pairing.
  • Failure source: pty-shell-utils caught pgrep/ps failures into false/null, and the completion monitor acted on the coerced values as confirmed idle evidence.
  • Oracle: the repro suite asserts the end-to-end derived behavior (no completion dispatch under probe failure; completion dispatch on positive absence), not internal flags.
  • Gate: deterministic focused tests (repro + probe units + monitor evidence suite) plus the cross-version wire harness.
  • Coverage: SSH relay POSIX and Windows hosts; old/new client × old/new host pairings reasoned and tested; local provider and daemon protocol out of scope (unchanged).
  • Performance budget: no new subprocess, poll, timer, listener, or unbounded state. POSIX per-poll work unchanged; Windows drops one doomed pgrep fork per poll and reuses the TTL-cached native table read; +~120 bytes JSON per inspection result; unverifiable results engage the existing bounded backoff (≤10s), reducing poll pressure on distressed hosts.
  • Diagnostics: unverifiable.reason names the probe and failure class (deadline vs could-not-run) for future surfacing; no user data included.
  • Residual gap: the distress scenario is exercised with injected exec failures, not a live overloaded host; the daemon-protocol and local-provider legacy collapses are sibling sites left for their own remediations.

Testing

  • The 9-file, 72-test evidence suite named in the ablation section: all pass at ad919dc212
  • Full src/relay/ (145 files) and src/renderer/src/components/terminal-pane/ + runtime inspection suites (404 files, 3941 tests): pass
  • tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts: 5/5
  • pnpm tc: clean; oxlint + oxfmt --check on all changed files: clean
  • No mobile-facing surface touched.

Author: @BrennanKB5

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Validation ran at exact SHA 7b32eed4b6dbebe25f3e72b87f26903bedf76bf6 (verified pushed via git ls-remote: refs/heads/brennanb2025/relay-completion-unverifiable-r1 = 7b32eed4b6dbebe25f3e72b87f26903bedf76bf6).

  • Pre-fix reproduction fails on base 3ed7796624 (coerced probe failure dispatched a confirmed process-exit completion for a live agent); passes at this SHA.
  • Ablation: all 7 production hunks individually reverted → evidence suite red (6/1/3/5/1/3/1 failures respectively); restored baseline 37/37 green.
  • pnpm tc clean, cross-version wire harness 5/5, full relay + terminal-pane suites green at this SHA.

@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 06c772ea-a074-4452-8d20-1e085974c337

📥 Commits

Reviewing files that changed from the base of the PR and between 66abb42 and 8d51973.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/agent-completion-legacy-live-children.test.ts
  • src/renderer/src/components/terminal-pane/agent-completion-positive-exit-requirement.test.ts
  • src/renderer/src/components/terminal-pane/agent-completion-process-monitor.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The change adds structured foreground and child-process evidence with observed, live, exited, and unverifiable verdicts. Relay process probes move into pty-process-probes.ts, with Linux and Windows handling plus wrapper-aware foreground resolution. Relay, runtime, preload, and renderer contracts carry optional evidence while preserving legacy fields. Completion monitoring uses normalized verdicts and defers completion during unverifiable probes. Unit and end-to-end tests cover probe failures, legacy compatibility, malformed evidence, and recovery.

Merge Risk: 🔵 Low · up to 8d519

The PR prevents current-version clients from treating failed process checks as confirmed agent exits, but mixed-version relay/client pairings may still interpret an unavailable check as no remaining process and trigger completion too early. The change is mergeable with explicit owner awareness and follow-up to negotiate structured-evidence support or disable completion-sensitive automation for unsupported peers.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 45 functions across 21 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description gives detailed context, implementation scope, compatibility analysis, failure reproduction, testing evidence, and reliability requirements. However, it omits the required Linked Issue … Add a linked issue using the required Fixes #... format. Add or explicitly complete the missing template sections, including Visual Proof with N/A and a reason if applicable, Review, Notes, and the applicable Checklist items.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: preserving live, unverifiable, and exited relay completion evidence without coercion.
Full details: Description check

Explanation

The description gives detailed context, implementation scope, compatibility analysis, failure reproduction, testing evidence, and reliability requirements. However, it omits the required Linked Issue section and does not fully follow the repository template for Visual Proof, Review, Notes, and Checklist.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f81fc278-5412-4704-81d0-e81484e92f7e

📥 Commits

Reviewing files that changed from the base of the PR and between ebe6b55 and 7b32eed.

📒 Files selected for processing (17)
  • src/main/providers/pty-process-inspection.ts
  • src/main/runtime/orca-runtime.ts
  • src/preload/index.ts
  • src/relay/pty-handler-attach-replay.test.ts
  • src/relay/pty-handler-spawn-admission.test.ts
  • src/relay/pty-handler-startup-command-delivery.test.ts
  • src/relay/pty-handler-test-harness.ts
  • src/relay/pty-handler.ts
  • src/relay/pty-process-probes.test.ts
  • src/relay/pty-process-probes.ts
  • src/relay/pty-shell-utils.test.ts
  • src/relay/pty-shell-utils.ts
  • src/renderer/src/components/terminal-pane/agent-completion-process-monitor.ts
  • src/renderer/src/components/terminal-pane/agent-completion-unverifiable-evidence.test.ts
  • src/renderer/src/runtime/runtime-terminal-inspection.ts
  • src/shared/pty-process-inspection-evidence.ts
  • tests/e2e/relay-completion-evidence/relay-inspection-unverifiable-completion.unit.test.ts
💤 Files with no reviewable changes (1)
  • src/relay/pty-shell-utils.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Adversarial review @ 7b32eed4b6dbebe25f3e72b87f26903bedf76bf6

Verdict: REVISE — not merge-ready at this SHA. CI is red and all red is caused by this PR (F1). Every behavioral claim in the PR body survived independent re-verification: I re-ran the ablation myself (7/7 counts match), re-proved the pre-fix repro on base 3ed7796624, traced processEvidence end to end with runtime proof, re-derived the wire ruling, and audited the win32 correction and the extraction. Once F1 is fixed and CI is green, this is behaviorally merge-ready.

F1 — merge-blocking: new direct child_process import trips the ratchet suite (4 CI shards + verify red)

src/relay/pty-process-probes.ts:1 imports execFile from node:child_process. src/relay/pty-shell-utils.ts is grandfathered in src/shared/child-process/__fixtures__/child-process-import-allowlist.txt:164; the new file is not, and the boundary test's contract is that the allowlist only shrinks. Reproduced locally at this SHA — the exact failures in CI jobs tests node 24/26 1/8 + 3/8:

  • src/shared/child-process/child-process-import-boundary.test.ts › has no direct importer outside the allowlist
  • src/shared/child-process/child-process-import-boundary.test.ts › never grows
  • src/shared/child-process/windows-console-visibility.test.ts › adds no new file that spawns without windowsHide

Sanctioned fix per AGENTS.md: route the two execFile calls through runProcess (src/shared/child-process/run-process.ts). That import is already proven inside the relay bundle (src/relay/git-handler.ts:107). The probe/repro tests mock child_process directly, so their mock target moves with it.

Ablation — re-run independently, all 7 match

I reverted each production hunk on this head myself and ran the 37-test evidence suite each time:

Hunk reverted (my patch) Mine Claimed
children-probe catch → exited 6 failed 6
foreground ps catch → observed null 1 failed 1
handler stops attaching processEvidence 3 failed 3
monitor unverifiable gate removed 5 failed 5
evidence normalization removed 1 failed 1
Windows native-table branch removed 3 failed 3
legacy collapse altered (unverifiable → true) 1 failed 1

No uncovered production hunk found. Note the ps-catch discrimination hangs on a single unit test (keeps a timed-out ps read unverifiable) — thin but real coverage.

Pre-fix repro on base 3ed7796624 — confirmed genuine

Ported only the repro test onto a clean worktree at the base commit (imports repointed at the pre-split pty-shell-utils; no production code carried). Both behavioral tests fail with exactly the claimed false completion — dispatchCompletion('codex', { source: 'process-exit', terminalIdleConfirmed: true, quietedHookDone: false }) — and the wire-shape test fails on the missing field. On this head: 37/37 green, including the recovery case proving a real exit still completes.

processEvidence end-to-end trace — arrives; one stale type at the true boundary (F2, P2)

Every hop checked for reconstruction/stripping: relay pty-handler.inspectProcess → SSH mux JSON-RPC (SshChannelMultiplexer.request resolves the raw result, no schema) → ssh-pty-provider.ts:263 (cast passthrough) → inspectPtyProviderProcess (passthrough) → ipcMain 'pty:inspectProcess' (passthrough) → preload arrow returns ipcRenderer.invoke directly (src/preload/index.ts:1232, no mapping) → renderer. Paired-runtime path: terminal.inspectProcess returns the runtime result wholesale; RpcSuccess.result is unknown and callRuntimeRpc<T> is a cast — so yes, results on this path are unvalidated casts: the type system could never have caught a drop, which is why runtime proof was required.

Runtime proof: the "handler stops attaching processEvidence" ablation flips the real renderer coordinator through the real RPC dispatch (3 tests red) — the renderer decision provably consumes the field as delivered — and a structuredClone assertion (the ipcRenderer.invoke result algorithm) confirms the payload survives the Electron hop. Web client: web-terminal-api.ts inspectProcess rejects by design; web uses only the runtime RPC path.

F2 (P2): the renderer-visible declaration of window.api.pty.inspectProcess is PtyApi in src/preload/api/pty-api.ts:110 (via api-types.ts → Window.api), and it was not updated — the +2 in src/preload/index.ts edits a redundant inline annotation only. The value flows regardless (width subtyping hides the gap), but the declared boundary contract is now stale and divergent. Add processEvidence to PtyApi.inspectProcess, or better, collapse the five structural copies (pty-api, preload/index, orca-runtime ×2, runtime-terminal-inspection) onto one shared type.

Wire ruling — Rule 1 confirmed; one Rule 3 content change, judged safe

  • New optional JSON field on two existing RPC results (pty.inspectProcess, terminal.inspectProcess). No new opcode anywhere in the diff → no capability negotiation needed. Cross-version wire harness 5/5 at this SHA.
  • Old client + new host (POSIX): legacy fields byte-identical — proven by the e2e toEqual assertions and by ablation 7 (altering the collapse turns the suite red).
  • New client + old host: field absent → readPtyProcessInspectionEvidence returns the legacy interpretation; the monitor test "still completes from legacy fields when the host predates evidence" pins it; no reader requires the field. Malformed/foreign shapes (null, unknown verdicts) normalize to unverifiable, never to an observation.

Win32 legacy correction — safe; conservative only in the completion-blocking direction

On Windows relay hosts, legacy hasChildProcesses was a constant false (swallowed pgrep ENOENT). Now probeProcessChildren reads the native process-table snapshot: descendants > 0 → live (legacy true), root observed with zero descendants → exited (legacy false), table unreadable or root missing from snapshot → unverifiable (legacy false). So the legacy bit can only change false → true, which can only block a premature completion. exited requires a successful table read that observed the PTY root (windows-foreground-process-rows.ts:72-74 returns null → unverifiable otherwise), and candidates is all descendants, unfiltered — a live non-agent child reads live. Residual: the 500 ms-TTL cached snapshot can miss a just-spawned child → exited for one poll — identical to the pre-fix constant-false reading, and the monitor's two-sample confirmation spans multiple polls, so no new false-completion window exists. It cannot make a live process look exited anywhere it didn't before; the change converges Windows with POSIX semantics and with the local Windows provider, which already answers from the same table. Native-module load is lazy and win32-gated — POSIX relays never touch it.

Extraction audit — move verified

Mechanical function-level diff base → head: processHasChildren, isProcessAlive, collectDescendants, candidateScore, processCommandToken, candidateMatchesFallbackWrapper, getRecognizedForegroundDescendant are byte-identical. Only getForegroundProcessName was reshaped (into observeForegroundProcess + a collapse wrapper); every branch's legacy output is equivalent — the wrapper collapses unverifiable to null exactly where the old catch returned null, so pty.getForegroundProcess and pane titles are unchanged. No stale importers of the moved symbols remain.

Performance (manual review; per-completion-check path)

POSIX per-poll subprocess profile unchanged: same single pgrep, same foreground fast paths (recognized fallback → zero subprocess), ps -axo snapshot behind the 500 ms single-flight TTL. Win32 drops a doomed per-poll pgrep fork for the TTL-cached native read (~16 ms fresh, shared with foreground resolution). Failure classification is pure CPU on error objects; ~150 B extra JSON per result; unverifiable feeds the existing bounded backoff (cap max(10s, base)), so a distressed host is polled less. No new subprocess, timer, listener, or unbounded state.

Other findings

  • F3 (out of scope, recorded): other renderer consumers of the same inspection still read only legacy fields — running-terminal-close-guard.ts:124, pane-serializer-settle.ts:153, agent-ready-wait.ts:94. Same coercion class, bytes unchanged here; they join the declared sibling sites (daemon protocol inspectProcess, local provider collapses, orca-runtime.ts hasChildProcesses?.catch(() => false)).
  • F4 (not PR-caused): pty-handler-startup-command-delivery.test.ts › "emits shell-ready markers for renderer-delivered Codex native prefill commands" fails on my machine identically at base 3ed7796624 and at this head (env-sensitive; green in CI).
  • Mobile: no mobile-facing surface touched (mobile/src has no inspectProcess/processEvidence consumer).
  • Security: no new dependencies, argv-array subprocess calls only, no shell strings, no network sinks.

Superseding bar

I would not rewrite this. Written from scratch, exactly two things differ — and they are the two findings: subprocess calls go through src/shared/child-process from day one (F1), and one shared inspection-result type instead of five inline structural copies (F2 is the realized cost of that duplication). The evidence contract shape (per-probe discriminated unions with no payload on the unverifiable arms), the monitor semantics (recognized foreground still registers past an unverifiable child probe), and the test architecture (real adapter → real coordinator repro) are what we would write.

Required before merge: fix F1 (route pty-process-probes.ts spawns through runProcess/spawnProcess), ideally fold in F2, re-run CI to green.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Fix for the two blocking findings — head 291040402098adb1ef200ee2e05456e688f4d2cb

Addresses the r1 review verdict (F1 ratchet trip, F2 stale renderer type). One commit on top of 7b32eed4b6db.

F1 — probes now go through runProcess (ratchets pass because the direct spawn is gone)

src/relay/pty-process-probes.ts no longer imports node:child_process at all (grep count: 0). Both probe calls (pgrep -P, ps -o comm=) route through runProcess from src/shared/child-process/run-process.ts, which pins windowsHide: true / shell: false — so the every-completion-check probe path can no longer flash console windows on Windows.

The failure classification was rewritten for the runProcess contract (it resolves non-zero exits as data and rejects only when the binary could not be spawned):

  • exit 0 → stdout answers (live/exited, observed name)
  • exit 1, no signal, not timed out → positive absence (exited / observed-null) — unchanged ruling
  • timeout or signal → unverifiable ("did not answer before its deadline")
  • other exit codes (e.g. pgrep fatal 3) → unverifiable
  • spawn rejection (ENOENT, fork pressure) → unverifiable (legacy boolean still collapses to false)

Neither allowlist nor any baseline was touched: git diff 7b32eed4b6db..HEAD -- src/shared/child-process/__fixtures__/ is empty, and no test expectation in child-process-import-boundary.test.ts / windows-console-visibility.test.ts changed. Both suites pass locally because pty-process-probes.ts stopped being an offender (relay/pty-shell-utils.ts legitimately remains listed — it still uses execFileSync for other duties, so its entries are not stale).

Test mocks moved with the code: the probes' unit test and the e2e repro now drive probe outcomes through a runProcess mock, while the ps -axo process-table read (an allowlisted direct execFile caller in process-table-snapshot.ts, unchanged by this PR) keeps its execFile mock.

F2 — processEvidence added to the renderer-visible PtyApi

src/preload/api/pty-api.ts inspectProcess now declares processEvidence?: PtyProcessInspectionEvidence. This is the type the renderer actually sees for the local leg (api-types.ts → Window.api.pty); previously width subtyping let the value flow while the declared contract silently dropped it.

Decision on "at least one renderer consumer": the consumer already exists in this PR — agent-completion-process-monitor.ts reads the evidence via readPtyProcessInspectionEvidence and treats any unverifiable sub-probe as "could not ask", re-arming instead of completing. What was missing was only the typed visibility on the local IPC leg. To pin that, a new test case in agent-completion-unverifiable-evidence.test.ts types its inspection result as Awaited<ReturnType<PtyApi['inspectProcess']>> and drives the monitor through it. Failing-first proven: with only the pty-api.ts hunk reverted, pnpm tc fails exactly there — TS2353: 'processEvidence' does not exist in type '{ foregroundProcess: string | null; hasChildProcesses: boolean; unavailable?: true }'. (The review's suggestion to collapse the five structural copies onto one shared type is left as follow-up; this PR stays scoped to the blocking findings.)

Ablation — re-run on this head after the changes, coverage not weakened

Same seven production-hunk reverts, run against the evidence suite (now 39 tests: the original 37 plus a legacy-boolean pgrep-exit-1 case and the preload-typed monitor case):

Hunk reverted r1 review This head
children-probe failure → exited 6 6 failed
foreground ps failure → observed null 1 1 failed
handler stops attaching processEvidence 3 3 failed
monitor unverifiable gate removed 5 6 failed (+1 = the new preload-typed case)
evidence normalization removed 1 1 failed
Windows native-table branch removed 3 3 failed
legacy collapse altered (unverifiable → true) 1 1 failed

Every hunk still has red coverage; the only delta is an increase from the added test.

Local verification at this head

  • 58/58 across the six suites: both ratchet suites, pty-process-probes.test.ts, pty-shell-utils.test.ts, the e2e relay repro, and the renderer evidence suite
  • pnpm tc exit 0

CI (including the real Windows shards) is running on this push; Windows-job confirmation to follow before any merge consideration.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Cross-PR audit follow-up @ exact SHA 7f002039b87ade44863336f010b5e6dd0c14b988

(git ls-remote verified: refs/heads/brennanb2025/relay-completion-unverifiable-r1 = 7f002039b87ade44863336f010b5e6dd0c14b988)

Closes the audit's monitor-polarity finding: the completion monitor entered the completion-dispatch path via children !== 'live' after the unverifiable early-return — a fall-through, not a positive exited match (the exact shape fixed in #16900/#16908). It was closed only incidentally by the 3-arm union + normalize funnel, so a fourth verdict arm added later would have re-opened it silently.

Change (production, agent-completion-process-monitor.ts only):

  • The could-not-verify early-return now covers anything outside the known vocabulary (foreground !== 'observed', children neither 'live' nor 'exited'), re-arming like a failed inspection.
  • The destructive branch now requires a positively matched 'exited' (!== 'exited' → clear pending, keep polling). No default arm added; behavior for all in-contract inputs is unchanged.

Tests:

  • agent-completion-out-of-contract-verdict.test.ts — feeds a fourth children verdict ('reparented') through the real monitor, modeling a future funnel that admits the arm; asserts NO completion is dispatched, and that a later genuine 'exited' still completes. Failing-first proven: both tests red on head 291040402098 (monitor fix reverted), green with the fix.
  • pty-process-inspection-evidence.test.ts — pins the normalize funnel at the contract level (malformed/out-of-contract → unverifiable), keeping the normalization hunk independently ablation-red now that the monitor also defends that route.

Full 7-hunk ablation re-run at this SHA (evidence suite, 45 tests baseline green): 6 / 1 / 3 / 8 / 3 / 3 / 1 vs previous 6/1/3/6/1/3/1 — every hunk still individually red; monitor-gate +2 (new pinning tests) and normalization +2 (new funnel unit tests); nothing weakened.

Gates: full pnpm tc exit 0; oxlint clean on changed files; full terminal-pane suite 403 files / 3893 tests green; git diff origin/main...HEAD -- config/oxlint-code-quality-type-aware.json is empty (lint rule untouched).

Inherited CI note: tests shard 8/8 (web-preload runtime-calls, #15420) and e2e ssh docker watcher isolation are red main-side and owned by a separate lane — not caused here.

A failed pgrep/ps probe on a relay host resolved as
{foregroundProcess: null|fallback, hasChildProcesses: false}, which the
agent-completion monitor read as positive exit evidence and turned into
a process-exit completion. Probes now return live/unverifiable/exited
verdicts, the relay publishes them in a new optional processEvidence
field beside byte-identical legacy fields, and the monitor refuses to
treat an unverifiable probe as exit evidence.
The monitor entered the completion path on children !== 'live' after the
unverifiable early-return — a fall-through, not a positive 'exited' match
(the polarity shape fixed in #16900/#16908). A fourth verdict arm admitted
by a future evidence funnel would have silently read as exit evidence.
Completion now requires children === 'exited'; anything outside the known
vocabulary re-arms like a failed inspection. Pinned by an out-of-contract
monitor test (fails on the previous head) and a funnel-level normalization
unit test that keeps the normalize hunk independently covered.
…spection-evidence reader

A foreign host can put any JSON in processEvidence. An observed verdict
carrying a non-string processName rode through normalization into
recognizeAgentProcess and counted toward the 'foreground is not a recognized
agent' leg of the positive-exited gate; non-string unverifiable reasons were
forwarded as-is. Out-of-type payloads now degrade to unverifiable
(malformed-evidence reason), and non-string reasons fall back to
'unspecified'.
…d gate

The two hardening arms added in 7f00203 were mutually redundant: reverting
either alone left the suite green, so either could have been deleted without
CI noticing. Three tests now isolate the vocabulary guard:

- a foreground verdict outside 'observed' paired with a positively matched
  'exited' children probe — the exit gate reads a legitimate exit here, so
  only the foreground arm can refuse it;
- the companion that the refusal does not wedge the monitor;
- an out-of-contract children verdict must take the inspection-error backoff,
  the guard's stated promise to re-arm "like any other failed inspection".

All three fail with the vocabulary guard reverted and pass with the exited
gate reverted, so they pin that arm alone.
…base

#17012 landed on main spying on ptyShellUtils.isProcessAlive while this branch
moved the probe into pty-process-probes. The rebase merges textually clean but
breaks 6 of the file's 9 tests and the node typecheck.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/relay-completion-unverifiable-r1 branch from 3ca44ad to 66abb42 Compare August 28, 2026 13:00
@coderabbitai

coderabbitai Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

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.

…cabulary guard

The two hardening arms were mutually redundant in coverage: reverting either
alone left the suite green. The out-of-vocabulary guard is now pinned on its
own; this pins the other half.

Given the vocabulary guard, every sample reaching the exit gate already carries
'live' or 'exited'. On a host that builds its wire result with
buildPtyProcessInspectionWireResult the legacy `hasChildProcesses` boolean is
exactly `children.verdict === 'live'`, so reading the boolean and requiring a
positive 'exited' agree — the arm is invisible there.

They part on the shape the reader is written to survive: a peer this client
cannot vouch for, whose two fields disagree. readPtyProcessInspectionEvidence
never cross-checks the legacy scalar against the evidence union, so
`hasChildProcesses: false` can arrive beside a positively observed
`children: 'live'`. That boolean's `false` is the lossy collapse conflating
"no children" with "could not tell" (#16900/#16908). The evidence union is
authoritative, so 'live' must refuse even though the legacy field waves it
through.

Reverting the positive-exited arm alone turns two of these red with a false
`process-exit` completion; reverting the vocabulary guard alone leaves all
three green.
…eld contradicts

The exit gate used to read `if (result.hasChildProcesses)` and refuse on
`true`. Moving it onto the evidence union dropped the legacy field, so the
gate now refuses only on a children verdict other than 'exited'. That is more
conservative in one direction — the direction the positive-exited arm pins —
and less conservative in its mirror: `hasChildProcesses: true` beside
`children: 'exited'` is a shape the boolean-only line refused and the
verdict-only gate dispatches a process-exit completion for.

Only the boolean's `false` pole is the lossy collapse this batch removes; it
conflates "no children" with "could not ask". Its `true` pole is a positive
observation on every producer — buildPtyProcessInspectionWireResult sets it
from `children.verdict === 'live'`, processHasChildren from a pgrep that
exited 0 with output, and the daemon host from an observed non-shell
foreground. Dropping a positive liveness observation to honour a disagreeing
'exited' is the #16900/#16908 polarity bug pointing the other way, so the gate
now refuses whenever either half reports live children.

No conforming host is affected: readPtyProcessInspectionEvidence's legacy
fallback maps `true` to 'live', which the verdict term already refuses, and
the wire builder never emits the disagreeing pair. Only a peer this client
cannot vouch for can, which is the same premise the mirror arm is pinned on.

Pinned by three monitor tests through the real reader with no mock (all three
fail on the previous head, each with a false process-exit completion). The
four-way ablation keeps the arms independent: reverting only this term reddens
its three tests and leaves the vocabulary-guard and positive-exited pins green.
The mirror of the children-axis rule, one axis over. Recognition used to read
`recognizeAgentProcess(result.foregroundProcess)`. Moving it onto the evidence
union made it read `evidence.foreground.processName`, so a sample whose union
reports `{observed, processName: null}` beside a legacy `foregroundProcess:
'codex'` no longer recognizes an agent. Its foreground verdict is still inside
the vocabulary, so the out-of-vocabulary guard cannot refuse it either, and the
sample falls through to the exit gate and dispatches a process-exit completion
for an agent the host still names in the foreground.

Only the `null` pole of the legacy scalar is the lossy collapse this batch
removes; it conflates "no agent in the foreground" with "could not ask". A
recognized non-null name is a positive observation on every producer:
buildPtyProcessInspectionWireResult copies it straight off an `observed`
foreground verdict, and the ps/pgrep probes only set it from a command line the
host actually read back. Discarding a positive liveness observation to honour a
union reporting no name is the #16900/#16908 polarity bug on the foreground
axis, so the gate now refuses whenever either half still names an agent.

The refusal is added at the exit gate rather than by widening recognition, so
the arm can only ever withhold a dispatch, never introduce one: reading the
legacy name into handleRecognizedProcess would fire a process-replacement
completion on a disagreeing name, which is less conservative, not more.

No conforming host is affected. To reach the gate the foreground verdict is
already 'observed', so buildPtyProcessInspectionWireResult's legacy scalar is
byte-identical to the union's processName the gate already found unrecognized,
and a host predating the field gets that same scalar through the reader's legacy
fallback. Only a peer this client cannot vouch for can disagree, the same
premise the children-axis arm is pinned on.

Pinned by four monitor tests through the real reader with no mock; all four fail
on the previous head, each with an actual false process-exit completion for
'codex'. The four-way ablation keeps the arms independent: reverting only this
term reddens its four tests and leaves the vocabulary-guard, positive-exited and
legacy-live-children pins green.
@greptile-apps

greptile-apps Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR adds explicit process-inspection evidence so failed relay probes remain unverifiable instead of being coerced into completion evidence.

  • Introduces live, unverifiable, and exited child-process verdicts plus observed and unverifiable foreground verdicts.
  • Carries optional evidence through relay, IPC, and runtime RPC boundaries while retaining legacy wire fields.
  • Requires positive exit evidence before agent completion and preserves recognized live-agent polling.
  • Adds focused POSIX, Windows, compatibility, monitor, and end-to-end tests.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
src/relay/pty-process-probes.ts Adds platform-aware foreground and child-process probes that distinguish positive absence from probe failure.
src/shared/pty-process-inspection-evidence.ts Defines and normalizes the optional evidence contract while preserving legacy wire-field behavior.
src/relay/pty-handler.ts Publishes foreground and child evidence alongside backward-compatible inspection fields.
src/renderer/src/components/terminal-pane/agent-completion-process-monitor.ts Prevents unverifiable evidence from advancing exit confirmation while preserving positive live-agent observations.
tests/e2e/relay-completion-evidence/relay-inspection-unverifiable-completion.unit.test.ts Exercises failed and recovered relay probes through the real inspection and completion path.

Sequence Diagram

sequenceDiagram
  participant M as Completion monitor
  participant H as Relay handler
  participant F as Foreground probe
  participant C as Children probe
  M->>H: inspectProcess
  H->>F: observe foreground
  H->>C: probe children
  F-->>H: observed or unverifiable
  C-->>H: live, exited, or unverifiable
  H-->>M: legacy fields plus optional evidence
  alt recognized foreground
    M->>M: Track live agent
  else unverifiable evidence
    M->>M: Re-arm exit confirmation
  else positive exited evidence
    M->>M: Confirm exit across samples
  end
Loading

Reviews (5): Last reviewed commit: "Merge commit '3031c2330cd7ea3772fe4ccf43..." | Re-trigger Greptile

@OrcaWin

OrcaWin commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

Thank you for this careful work. The SSH relay (and its pgrep/ps probes) has been removed (#27214, #27215); SSH hosts now run Orca's managed server, and process inspection on main already reports a failed check as unverifiable instead of "finished" (src/main/providers/pty-process-inspection.ts). Closing as no longer applicable.

@OrcaWin OrcaWin closed this Oct 11, 2026
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.

2 participants