Skip to content

feat(foreground): recognize renamed agent binaries via executable image + SSH foreground confirmation parity - #9434

Closed
bbingz wants to merge 13 commits into
stablyai:mainfrom
bbingz:bbingz/structured-foreground-resolution
Closed

bbingz wants to merge 13 commits into
stablyai:mainfrom
bbingz:bbingz/structured-foreground-resolution

Conversation

@bbingz

@bbingz bbingz commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Recognize renamed/forked agent binaries + SSH confirmForegroundProcess parity

Part of #9414. Stacked on #9415 — review the commits after its tip
(15aa992f14); this PR adds the following commits on top:

  1. feat(foreground): recognize renamed/forked agent binaries via executable image
  2. feat(ssh): add confirmForegroundProcess parity for SSH panes
  3. fix(foreground): preserve command-aware guards in executable-image recognition
  4. fix(foreground): quote-aware argv0 strip + bounded exe-path cache

Open as a draft until #9415 merges.

Problem

Foreground-process recognition collapsed to recognized-or-null:
resolveAgentForegroundProcessFromPs returned only whitelist matches, so an
unrecognized live process became the shell fallback. Two gaps followed:

  • Renamed/forked agent binaries were never identified. An argv0-renamed
    real binary, or a native fork installed at a non-standard path (e.g.
    ~/.local/bin/grok), shows an unrecognized command line, so the agent went
    unrecognized and the pane looked like a bare shell.
  • SSH panes trusted stale foreground reads. orca-runtime
    (terminalHasShellForegroundProcess) had no way to confirm a foreground
    read on SSH: the SSH provider didn't implement confirmForegroundProcess, so
    a possibly-stale relay read of an idle-looking shell (that still fronts a live
    agent) was trusted as-is.

Evidence model

Recognition still returns a recognized agent name or falls back to the raw
node-pty process name (the existing string | null contract is preserved end to
end). The new executable-image evidence is an additional, lazy resolution
step layered under the existing command-line recognition: when the command line
doesn't recognize, the process's real executable image basename gets a second
chance at recognition.

  • New shared module src/shared/process-executable-recognition.ts:
    resolveProcessExecutablePath(pid) reads the real image
    (Linux /proc/PID/exe, macOS lsof -a -p PID -d txt -Fn), and
    recognizeAgentFromExecutablePath(pid, command) re-runs agent recognition on
    it. Recognition substitutes the resolved image as argv0 while preserving the
    process's original arguments
    and re-runs the command-line recognizer, so the
    command-aware guards still apply — basename-only recognition would have
    mislabeled a renamed claude --print (headless one-shot) or a bare orca
    (without the claude-teams subcommand) as an interactive agent.
  • The macOS reader copies resolveProcessCwd's same-uid per-PID lsof pattern
    (-a ANDs -p/-d so only the target pid's entries return) and takes the
    first txt entry as the executable image (mapped dylibs follow it);
    multi-entry output is handled defensively by ignoring later entries.
  • Wired into the three foreground resolvers, unrecognized-and-non-shell
    foreground (+) candidates only:
    • POSIX agent-foreground-process.ts (local/daemon path).
    • Relay pty-shell-utils.ts getRecognizedForegroundDescendant.
    • Windows windows-agent-foreground-process.ts feeds the already-captured
      CIM ExecutablePath (no extra probe — it is free) into recognition instead
      of using it only for context matching.

Reachability limit (direct unknown-non-shell foreground)

Executable-image evidence fires from the descendant scan, so it recognizes a
renamed binary when the reported foreground is a shell or interpreter wrapper
(the common shape) and, on the local/daemon POSIX path, when node-pty reports
an unknown non-shell name directly (the daemon's async wrapper refresh always
inspects POSIX candidates). It does not fire when node-pty reports the
renamed binary's own name directly on the SSH relay (getForegroundProcessName
returns a clear non-shell/non-wrapper fallback without a remote process-table
scan — a deliberate SSH cost optimization) or on single Windows reads
(shouldInspectWindowsAgentForeground skips unknown non-shell names to avoid a
per-read CIM scan). In those cases the pane still reports its raw name and stays
busy via #9415's unrecognized-non-shell logic; only the agent identity is
not upgraded. Closing that gap would trade the SSH/Windows per-read scan cost the
optimizations deliberately avoid, so it is left as a known limitation.

Executable-resolution limits (script CLIs)

A node/python script fork resolves to the interpreter (/usr/local/bin/node,
/usr/bin/python3), which is intentionally not recognized as an agent — this
never fabricates an engine. Script-based CLIs remain covered by the existing
argv/entrypoint recognition (agent-process-recognition.ts,
node_modules/@openai/codex/… markers, python -m …), which this change does
not touch. Executable-image evidence adds coverage only for renamed real
binaries and native forks
.

Cost-guard proof

Executable resolution is lazy, unrecognized-non-shell-foreground-only, and
per-PID cached
(5s TTL). The cache key is PID-only (process start-time is not
cheaply available cross-platform), so a recycled PID — or the same PID after an
exec — can be briefly mislabeled (the cached path is re-recognized, not
re-resolved) for at most one TTL window. The short TTL bounds the window;
key-by-generation is a spec-accepted deferred hardening. Crucially, resolution
forks lsof/readlink, never ps, so the whole-process-table scan volume
is untouched:

  • agent-foreground-process-ps-scan-volume.test.ts — green (the guard's codex
    candidate recognizes on the command line, so no lsof fires).
  • windows-agent-foreground-process-scan-volume.test.ts — green (drives the
    descendant reader directly; ExecutablePath recognition adds no scan).

Both guards stay green with zero extra ps scans. Tests also assert lsof
does not fire when a candidate is recognized by command line, and is not
run for suspended (non-foreground) candidates.

SSH confirmForegroundProcess parity

  • Relay pty.confirmForegroundProcess handler forces a fresh post-boundary
    process-table scan (new fresh option threaded through
    getForegroundProcessName → getRecognizedForegroundDescendant, using
    getFreshProcessTableSnapshot; Windows uses { fresh, forceProcessScan }).
  • SshPtyProvider.confirmForegroundProcess requests it. orca-runtime already
    feature-detects the optional controller method, so no runtime change is
    needed — the SSH provider gaining the method is what activates confirmation.

Relay version-skew story

The relay is a separately-versioned deployed binary. Tolerance is
bidirectional and non-breaking:

  • New client / old relay: an old relay 404s the method
    (JSON-RPC -32601 "Method not found"). The provider feature-detects this,
    latches confirmForegroundUnsupported, and degrades to today's trusting
    getForegroundProcess read — no error, and later confirms skip the failing
    round-trip.
  • New relay / old client: the added getForegroundProcess/relay handler
    wire contract is unchanged (still string | null); the new method is
    additive, so old clients that never call it are unaffected.

Non--32601 relay errors are rethrown unchanged.

Tests

  • process-executable-recognition.test.ts — Linux /proc exe recognized
    (both via injected reader and the default readlinkSync('/proc/PID/exe')
    path with mocked node:fs, including null-on-readlink-failure); macOS lsof
    executable image recognized (first txt entry, dylibs ignored); per-PID cache
    (second call skips the reader); TTL expiry re-reads; the cache stays
    bounded — distinct never-reused PIDs are swept once past the soft cap;
    interpreter image (node) does not fake an engine; a renamed headless
    one-shot
    (claude --print) and a generic orca (no claude-teams) stay
    unrecognized while a genuine orca claude-teams is recognized (command-aware
    guards preserved) — including when argv0 is a quoted path with an internal
    space
    ("C:\Program Files\...\x.exe" --print), which a naive first-whitespace
    split would have mislabeled; unsupported platform returns null without invoking
    a reader.
  • agent-foreground-process.test.ts — renamed/forked binary recognized via
    executable image; no lsof when a candidate is recognized by command line;
    interpreter image does not fabricate an agent; suspended (non-+) candidates
    are not probed; renamed Windows binary recognized from ExecutablePath; a
    generic orca ExecutablePath without the claude-teams subcommand is not
    mislabeled.
  • pty-shell-utils.test.ts — renamed SSH-relay binary recognized via
    executable image; no lsof for a command-line-recognized descendant;
    confirmation reads bypass the cached process table with a fresh scan.
  • pty-handler.test.ts — pty.confirmForegroundProcess registered; forces a
    fresh post-boundary foreground read; returns null for an unknown pty.
  • ssh-pty-provider.test.ts — confirm requests a fresh relay read; old-relay
    -32601 degrades to getForegroundProcess and latches; non-method-not-found
    errors rethrow.
  • Both ps-scan-volume guards green.

Review fixes (post adversarial review)

An adversarial review confirmed two real defects in the shipped code, both now
fixed with regression tests:

  • Quote-aware argv0 strip. recognizeAgentFromExecutableImage stripped the
    original argv0 by first-whitespace, which broke a quoted path containing an
    internal space and left a dangling quote that swallowed the following tokens —
    burying --print (so a headless one-shot was mislabeled as an interactive
    agent) or claude-teams (so a genuine Orca agent launch failed recognition).
    Now stripped quote-aware. Verified by executing the exact scenario.
  • Bounded exe-path cache. The per-PID cache was never evicted, so every
    distinct non-shell foreground command (vim, git, node…) accumulated an entry
    forever in a long-lived daemon. Expired entries are now swept once the map
    crosses a soft cap, keeping it bounded to the active TTL window.

The review also flagged the two descoped spec items below as spec gaps. They
remain deliberately deferred (see the scope note); they are a large, coupled,
separable feature, not a defect in what this PR ships. The descope is a scoping
decision for the reviewer to ratify — it is not silently omitted.

Scope note (deferred to the next PR in the stack)

The #9414 umbrella also envisioned a structured ForegroundProcessResolution
{ engine, rawProcessName, isShell }
carried through the daemon cache and
runtime record and a neutral "unknown-but-alive" tab-icon presence in
use-tab-agent. Those two are a coupled feature — the structured rawProcessName
/ isShell fields have no in-tree consumer until the neutral-presence UI exists.
The tab-icon path already carries the raw foreground name to the renderer:
pty.getForegroundProcess returns string | null (an unrecognized non-shell
name flows straight through — daemon getForegroundProcess returns the raw
fallbackProcess, it is not dropped), and the renderer tracker runs its own
recognizeAgentProcess. So the neutral-presence feature is renderer-scoped, and
threading a structured type through the daemon cache / runtime record buys nothing
until that UI lands (the sidebar/busy/keep-awake path stays frozen per #9415).
The UI change itself extends the tab-icon identity from TuiAgent | null across the
pane-foreground store entry, the foreground-agent tracker's publish contract,
use-tab-agent, TerminalTabLeadingIcon, and the drag overlay. That is a large,
separable UI surface with meaningful regression risk against #9415's just-shipped
busy/keep-awake logic, so it is intentionally deferred to the next stacked PR
rather than bundled here. This PR ships the two changes that produce observable,
well-tested behavior with contained diffs: executable-image recognition and SSH
confirmation parity. The busy predicate + keep-awake stay exactly as #9415
shipped them.

ELI5

Orca can recognize renamed or forked agent binaries by looking at the real executable image, not only the process name. SSH panes get the same foreground-process confirmation local panes already had.

@bbingz

bbingz commented Jul 19, 2026

Copy link
Copy Markdown
Contributor Author

The two deferred scope-note items (structured ForegroundProcessResolution + neutral unknown-alive presence) are implemented in #9435, stacked directly on this PR.

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebase status: HARD (draft, not pushed) — conflicts with latest origin/main; lower-priority draft stack left for a follow-up session.

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebase status (2026-07-22)

Attempted restack onto current main; this draft stack still has large multi-file conflicts (sidebar/worktree-status / lifecycle / hook-service) against recent main landings.

Leaving draft until base PRs (#8872 close-intent, #9415 unknown-busy) land, then restack. Not closing — work is still intended, just blocked on a clean base.

@bbingz
bbingz force-pushed the bbingz/structured-foreground-resolution branch from fb0560b to 5825c78 Compare July 22, 2026 02:25
@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Restack onto current origin/main

Rebased all 8 commits onto origin/main (96df5f5715) and force-with-lease pushed to bbingz/structured-foreground-resolution.

New head: 5825c7893308704ac086e3b1641c5d3f7bbf25b1

Conflicts resolved

  1. sidebar rows / worktree-status — kept main’s launchAgent spinner fallback (Codex status hooks are dead in SSH worktrees — CODEX_HOME is injected only by the local PTY provider, while orca agent hooks status still reports codex: installed #8711) and this PR’s TTL-gated paneForegroundAgent process-identity attribution; both test suites retained.
  2. agent-foreground-process / Windows / relay — kept main’s OMP outer-wrapper resolution ([Bug] Pasting images into an agent CLI not working using Remote Host #6364) while adding executable-image recognition for renamed/forked agent binaries + command-aware image recognition guards.
  3. SSH confirmForegroundProcess — kept main’s relay timeout/getAppliedSize plumbing; added old-relay method-not-found latch + fresh process-table scan path.

Still draft. No origin/main push. Note: may conceptually stack under #9435.

@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Restack note

Rebased onto latest main (force-with-lease).

  • Kept renamed/forked agent binary recognition via executable image
  • SSH pty.confirmForegroundProcess parity with old-relay -32601 degrade latch
  • Merged with main’s SSH agent-session capabilities / spawn-exit race / getCapabilities (kept both sides)

Tests: process-executable-recognition + pty-shell-utils + ssh-pty-provider + pty-handler — 206 passed.

@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Restack + review guide (community, awaiting maintainer)

Draft. Restacked onto rebased #9415 tip (force-with-lease). Stack base matches #9415. +4 unique commits (9 total including #9415).

Unique vs main

Main has no process-executable-recognition:

  • Recognize renamed/forked agent binaries via real executable image
  • SSH pty.confirmForegroundProcess parity + old-relay -32601 degrade latch
  • Command-aware guards + quote-aware argv0 strip + bounded exe-path cache

Stack / depends

#9415 → #9434 (this) → #9435

Tests (local)

  • process-executable-recognition + ssh-pty + pty-shell-utils — 94 passed

Community author cannot merge.

@bbingz
bbingz force-pushed the bbingz/structured-foreground-resolution branch 2 times, most recently from 190f310 to 2b95896 Compare July 26, 2026 14:06
@nwparker nwparker added the enhancement New feature or request label Jul 27, 2026
@bbingz
bbingz force-pushed the bbingz/structured-foreground-resolution branch 2 times, most recently from b51bb4e to 6e5150e Compare July 31, 2026 09:54
bbingz and others added 13 commits August 6, 2026 07:39
…-status gate

A confirmed foreground that is neither a shell nor a recognized agent
(wrapper/fork agent binaries) previously counted as "shell only", which
suppressed fresh hook state and reported the pane idle. Only a confirmed
real shell (or an unavailable confirmation, matching the fail-closed catch
path) may now suppress explicit hook status.
…L + revalidation

Hook 'working' statuses were the only wake evidence, so wrapper-launched or
manually-run recognized agents (resolved by the existing foreground scans)
let the machine sleep mid-run. The runtime now reports each completed scan's
recognized-agent-or-null result; AgentAwakeService holds wake eligibility per
PTY while that evidence is fresh (5 min TTL), renews it at expiry via a
cache-only revalidation callback (never a new scan, 2h hard cap), and drops
it on a null report or PTY stop. Arbitrary non-shell processes never grant
wake. No new scans or cadences are added.
…rocess identity

Wrapper-launched claude (a shell function exec'ing the real binary) emits
Claude activity titles without the literal 'claude' token, so the row builder
and worktree ring rejected the pane as unattributable — invisible while
working. The paneForegroundAgent slice already resolves the recognized
foreground process; surface it as identity attribution:

- Slice entries now carry observedAt (stamped centrally) and the publishing
  PTY; resolveFreshPaneForegroundAgent gates consumers on a 30s TTL plus
  pane/tab PTY liveness so stale evidence after agent exit cannot fake a
  working state. The completion coordinator's existing inspections re-arm
  the observation (no new scans, no new cadence).
- resolveTitleDerivedAgentType/resolveAgentTypeFromTerminalTitle accept the
  process agent so a token-less Claude title yields a Claude row and an
  attributable working ring. State still comes from title activity or hooks;
  process identity alone never invents 'working'. Hook rows keep precedence.
- worktree-agent-activity-summary narrows the slice per worktree with stable
  references; card status, agent rows, and section activity consume it.
…to PTY, expire attribution on wall clock

Review fixes for the busy/visibility PR:

- agent-awake-foreground-evidence: enforce the 2h reportedAt cap
  unconditionally in pruneAndCount and align boundary comparisons with
  nextExpiry, so a stale timer firing at the cap (or exactly at the TTL)
  can no longer keep the power-save blocker held forever with no timer
  rescheduled. New test drives revalidation-renewed evidence to the cap
  and asserts the blocker stops with no timer left.
- onForegroundAgentInspected now carries the PTY the inspection ran
  against; pty-connection only accepts it while the pane still owns that
  PTY, and refreshPaneForegroundAgentObservation stamps it on created
  entries and rebinds (identity-only) evidence held for a previous PTY
  instead of keeping it fresh across a respawn.
- new usePaneForegroundAgentEvidenceExpiryTick schedules a one-shot
  re-render at the earliest evidence expiry for the worktree ring and
  agent rows, so a past-TTL working ring/row drops without unrelated
  store churn.
- restore the Claude-glyph regression fixture alongside the braille
  variant (it.each) in worktree-title-derived-agent-rows.test.
- update terminal-pane-detach-agent-identity.test for the central
  observedAt stamping introduced by this branch (was failing).
Known launch agents skip runtime foreground probes, so feed existing renderer inspections into runtime identity and wake evidence. Keep the review-driven rationale comments concise.
UNION rebase kept PR's ptyId stamping on setPaneForegroundAgent
publishes; two main-era expectations lagged. Align them with the
PR field and nearby tests. Cosmetic indent fix on the revoke path.
…ble image

Foreground-process recognition collapsed unrecognized live processes to
the shell fallback, so an argv0-renamed real binary or a native fork at a
non-standard path (e.g. ~/.local/bin/grok) was never identified.

Add a lazy executable-image evidence pass that runs ONLY for still-
unrecognized non-shell foreground ('+') candidates: resolve the real
executable (Linux /proc/PID/exe, macOS lsof -d txt, Windows the already-
captured CIM ExecutablePath) and re-run agent recognition on its basename.
Per-PID cached behind a short TTL; no extra ps scan, so both ps-scan-volume
guards stay green. Interpreter forks resolve to node/python and stay
unrecognized (script CLIs remain covered by argv/entrypoint recognition).
On SSH, orca-runtime had no way to confirm a foreground read, so it
trusted a possibly-stale relay getForegroundProcess result (an idle-looking
shell that still fronts a live agent).

Add pty.confirmForegroundProcess: the relay handler forces a fresh
post-boundary process-table scan (new fresh option threaded through
getForegroundProcessName), and SshPtyProvider.confirmForegroundProcess
requests it. Old-relay tolerant: a missing method (JSON-RPC -32601) is
feature-detected and latched, degrading to today's trusting
getForegroundProcess read instead of erroring.
…cognition

Executable-image evidence recognized a renamed binary by its basename alone
(recognizeAgentProcess on the resolved path), bypassing the command-line
recognizer's guards: the headless one-shot filter and the generic `orca` vs
`orca claude-teams` subcommand rule. A renamed `claude --print` or a bare
`orca` was therefore mislabeled as an interactive agent.

Recognize the resolved image WITH the process's original arguments: substitute
the real executable as argv0 and re-run recognizeAgentProcessFromCommandLine so
those guards still apply. Applies to the POSIX (local + relay) and Windows
ExecutablePath paths. Also corrects the per-PID cache comment: a recycled/exec'd
PID can be briefly mislabeled (stale path is re-recognized), not merely missed.

Adds headless, generic-orca, and genuine-claude-teams recognition tests plus a
Windows generic-orca ExecutablePath negative test.
Adversarial review found two defects in executable-image recognition:

- recognizeAgentFromExecutableImage stripped the original argv0 by the
  first whitespace, which breaks a quoted path with an internal space
  (Windows "C:\Program Files\...\x.exe"): the dangling quote swallowed
  following tokens, burying --print (headless one-shot mislabeled as an
  interactive agent) or claude-teams (genuine orca launch failed
  recognition). Strip argv0 quote-aware instead.
- The per-PID executable-path cache was never evicted; every distinct
  non-shell foreground command accumulated an entry forever in a
  long-lived daemon. Sweep expired entries once the map crosses a soft
  cap so it stays bounded to the active TTL window.

Tests: quoted spaced-path headless/interactive/orca-claude-teams cases,
bounded-cache eviction, and the default Linux readlink('/proc/PID/exe')
reader (success + null-on-failure).
@bbingz
bbingz force-pushed the bbingz/structured-foreground-resolution branch from 6e5150e to 1a1d174 Compare August 6, 2026 02:07
@bbingz

bbingz commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Closing as part of fork PR backlog cleanup.

This draft is long-conflicted (DIRTY) against current main and is not being actively rebased. Feel free to reopen or open a fresh PR if the work is still wanted.

@bbingz bbingz closed this Aug 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants