The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
chore(cli): remove the retired Herdr terminal backend (#404)
0xken158e6bd69168da
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5f091cee2..ca1cd4ead 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -97,7 +97,7 @@ jobs:- run: npx tsc --noEmit# 1,871 tests over 144 files, ~30s. The four `*.real.spec.ts` / `localE2e.spec.ts` suites that- # need a live tmux, Herdr or Cursor are gated behind RUN_* env vars and stay skipped here —+ # need a live tmux or Cursor are gated behind RUN_* env vars and stay skipped here —# `npm run test:tmux-real` and friends are how those are run, on a machine that has them.- run: npx vitest rundiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 9a86c1168..08ec17f15 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -193,11 +193,10 @@ fail, which is also why forgetting them is easy:```bashnpm run test:tmux-real # RUN_REAL_TMUX_DISCOVERY=1 — drives a real tmux server-npm run test:herdr-real # RUN_REAL_HERDR=1 — drives isolated Herdr sessions/workspacesnpm run test:cursor-e2e # RUN_CURSOR_E2E=1 — needs a real cursor-agent CLI```-If your change touches how agents are discovered or driven, run both real multiplexer suites for the+If your change touches how agents are discovered or driven, run the real multiplexer suite for thesoftware available on your machine and say exactly which versions and engine rows ran. A missingbinary, credential, or onboarding step is an unavailable row, not a passing one.@@ -211,20 +210,18 @@ into the tool feed — and each one passed its unit tests first.### Adding a multiplexer-Harness drives agents inside tmux and Herdr 0.8.x protocol 19, watching both by default with nothing to-configure. Another multiplexer is welcome, on one condition: it is **added alongside them, not swapped-in.** Existing registries contain tmux pane identity, so replacing the multiplexer orphans running+Harness drives agents inside tmux, with nothing to configure. Another multiplexer is welcome, on one+condition: it is **added alongside tmux, not swapped in.** Existing registries contain tmux pane identity, so replacing the multiplexer orphans runningagents on upgrade. Yours becomes another implementation behind the same interface instead of anotherrewrite.Four things decide how much work this is, and the first one is not in this repository at all:1. **Can a process running inside a pane tell which pane it is in — and with which of the values your- tool actually exports?** tmux exports `$TMUX_PANE`; Herdr exports `HERDR_PANE_ID`,- `HERDR_SOCKET_PATH`, `HERDR_ENV`, `HERDR_TAB_ID` and `HERDR_WORKSPACE_ID`. Read that list off a real- pane before you rely on any of it. Herdr 0.8.0 exports **no session name**, and matching endpoints by- name — a reasonable-looking assumption — silently rejected every hook it ever sent: no session bound,- resumed conversations opened blank, and turns typed in a pane produced no events at all. Identify the+ tool actually exports?** tmux exports `$TMUX_PANE`. Read that list off a real pane before you rely+ on any of it: a multiplexer that exports no session name, matched by name — a reasonable-looking+ assumption — silently rejects every hook it ever sends: no session bound, resumed conversations open+ blank, and turns typed in a pane produce no events at all. Identify theendpoint by something the tool really puts in the environment, accept more than one form of it, andtreat a hint that identifies nothing as matching nothing. The shell hooks in `cli/hook/notify.mjs`and the in-process plugins and extensions generated in `cli/src/lib/hooks.ts` read typed hints and@@ -238,8 +235,8 @@ Four things decide how much work this is, and the first one is not in this reposMiss the equivalent for yours and every recap spawns a phantom agent — silent, and thoroughlyunpleasant to trace.4. **Detection has to be free when your tool is absent.** Backends are auto-detected before every five- second reconcile, so presence is decided by a `PATH` walk (`herdrBinaryAvailable` in- `cli/src/lib/herdrSessions.ts`) and nothing is spawned until that succeeds. An installed-but-broken+ second reconcile, so presence is decided by a `PATH` walk (`binaryOnPath` in+ `cli/src/lib/binaryOnPath.ts`) and nothing is spawned until that succeeds. An installed-but-brokenversion must degrade to "nothing to adopt", never to a startup failure: only an operator who namedthe backend explicitly gets an error, because only they asked for it.diff --git a/cli/.env.example b/cli/.env.exampleindex c52cc4337..7962df2f3 100644--- a/cli/.env.example+++ b/cli/.env.example@@ -23,7 +23,6 @@ PORT=18473# tmux is the only supported terminal backend. Unset means auto, which resolves to tmux alone.# TERMINAL_BACKENDS=tmux # pin the set; `herdr` is retired and is dropped with a warning-# HERDR_SESSIONS / HERDR_BIN # retired with the Herdr backend: they still parse, select nothing# TERMINAL_RECONCILE_INTERVAL_MS=5000 # minimum 5000; neutral replacement for the legacy name below# One-release compatibility fallback when TERMINAL_RECONCILE_INTERVAL_MS is unset.diff --git a/cli/README.md b/cli/README.mdindex e7e712ca7..aff65e2ac 100644--- a/cli/README.md+++ b/cli/README.md@@ -97,10 +97,6 @@ on the backend link refreshes the SSO token and reconnects; only a refresh tokensigns the computer out. See [`RELEASE.md`](RELEASE.md) for publishing and the update internals.Disable with `ADAPTER_UPDATE_DISABLE=true`.-Custom Herdr-capable builds must keep self-update disabled or use a fork-owned signed-`ADAPTER_UPDATE_URL` until that build is available in the configured upstream manifest. Otherwise the-updater can legitimately replace the custom bundle with a release that lacks its terminal support.-**From source (dev):** `cd this package && npm install && npm run build && node dist/cli.js login`(or `npm run dev -- login` via tsx — always foreground; self-update is off in dev). `npm run bundle`produces the single-file release artifact.@@ -159,8 +155,8 @@ claude under a terminal backend ──writes──▶ ~/.claude/projects/**.jsonprofile agent comes back under its `CODEX_HOME` with its hooks installed. A grid row written beforethe launch was persisted is not relaunched; it is marked `GRID_CREDENTIAL_REQUIRED` instead. Anengine with no resume flag (devin) comes back fresh.-- **Hooks bind mutable engine sessions** to the process agent using authenticated tmux and/or Herdr- runtime hints plus verified caller ancestry. Hook socket paths are lookup hints only. They do not+- **Hooks bind mutable engine sessions** to the process agent using authenticated tmux+ runtime hints plus verified caller ancestry. They do notrequire `MACHINE_ID`. `SessionStart` and catch hooks attach transcript/store metadata; `SessionEnd` onlyrequests an immediate process reconciliation. `/clear`, `/new`, and resume move or rotate the bindingwithout changing the live process agent's UUID.@@ -199,43 +195,38 @@ claude under a terminal backend ──writes──▶ ~/.claude/projects/**.jsonauthoritative flags** (`compactEventFromRaw` in `lib/normalize.ts`) so the summary is never renderedas a fake user turn — an auto-compact firing mid-turn keeps the open turn open.- A web chat message arrives as a `message` frame and is submitted through one validated primary runtime.- Herdr prompt bytes use its bounded local socket API and never command-line arguments or environment.### Terminal backend behavior-- **tmux is the only supported backend.** Herdr was retired: nothing puts it in the backend list any- more, so none of its code paths are reached. `TERMINAL_BACKENDS=herdr` is not an error — it is- dropped with a warning and the daemon runs on tmux, because the CLI self-updates and a retired- setting must not stop an unattended machine from starting.-- **Unset means auto**, which now resolves to tmux alone. `TERMINAL_BACKENDS` survives only as a pin.-- `HERDR_SESSIONS` and `HERDR_BIN` still parse so an existing environment does not fail boot, but they- select nothing.+- **tmux is the only supported backend.** The retired Herdr backend has been removed.+ `TERMINAL_BACKENDS=herdr` is not an error — it is dropped with a warning and the daemon runs on tmux,+ because the CLI self-updates and a retired setting must not stop an unattended machine from starting.+ `HERDR_SESSIONS` and `HERDR_BIN` are no longer read.+- **Unset means auto**, which resolves to tmux alone. `TERMINAL_BACKENDS` survives only as a pin.- Harness never auto-starts a session.- `harness status` answers "is my pane being watched?" — `terminalSelection` says `auto` or `configured`,and `terminalTargets` lists what is live right now, not what was configured at boot.-- The shared backend contract can create and close a tmux session or Herdr workspace when explicitly+- The shared backend contract can create and close a tmux session when explicitlyinvoked. This is lifecycle capability, not automatic startup behavior; normal discovery observesuser-owned sessions, and agent deletion still terminates only the validated engine process.-- One process visible through nested/coexisting backends remains one Harness agent with multiple runtime- locators. A Herdr workspace move preserves its stable terminal identity; an engine process replacement does not.-- Backend and endpoint failures are independent. A failed probe is `unknown`, not proof of death. An+- One process visible through nested panes remains one Harness agent with multiple runtime locators;+ an engine process replacement does not.+- Backend failures are independent. A failed probe is `unknown`, not proof of death. Anagent with no verified runtime becomes dormant and is republished with the same id after recovery.- Existing `tmuxPane` registry rows migrate in place. tmux rows retain their legacy projection during- the compatibility window; Herdr-only rows never claim a tmux pane. For code rollback, stop the daemon,- archive the mixed registry, and give the old binary a copied tmux-only projection.+ the compatibility window. Runtimes an earlier build recorded for a Herdr pane are dropped on load, and+ an agent that lived only in one is removed.-For reproducible multiplexer verification, install dependencies and run both opt-in real suites from+For reproducible multiplexer verification, install dependencies and run the opt-in real suite from`cli/` under a normal umask:```bashumask 022npm cinpm run test:tmux-real-npm run test:herdr-real```-The Herdr suite requires Herdr 0.8.x protocol 19. Both suites use isolated, test-owned lifecycle-fixtures. Their engine matrix explicitly skips commands that are not installed; authentication or+The suite uses isolated, test-owned lifecycle fixtures. Its engine matrix explicitly skips commands that are not installed; authentication orfirst-run onboarding that prevents a proprietary CLI from running is unavailable evidence and must bereported as such, not described as exercised.@@ -251,8 +242,6 @@ reported as such, not described as exercised.| `ADAPTER_DATA_DIR` | `~/.harness/cli/data` | registry and daemon-local state (SSO session is always `~/.harness/auth/session.json`) || `DISABLE_HOOK_INSTALL` | `false` | skip auto-installing the claude hooks || `TERMINAL_BACKENDS` | *(auto)* | pin the set. `tmux` is the only supported value; a retired `herdr` is dropped with a warning |-| `HERDR_SESSIONS` | *(inert)* | retired with the Herdr backend; still parses, selects nothing |-| `HERDR_BIN` | *(inert)* | retired with the Herdr backend || `TERMINAL_RECONCILE_INTERVAL_MS` | `5000` | backend-neutral discovery interval; minimum 5000 ms || `TMUX_REAP_INTERVAL_MS` | `5000` | process discovery interval (removal requires two confirmed misses) || `ADAPTER_UPDATE_URL` | `…/adapter/metadata.json` | GCS release manifest the daemon polls for a newer build |diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex 284712df0..03e90784b 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -6,7 +6,7 @@* node_modules (it runs inside the user's `claude` process).** SessionStart: registers terminal hints plus session metadata with the adapter,- * but only from an authenticated tmux or configured Herdr context.+ * but only from an authenticated tmux context.* SessionEnd: asks the adapter to reconcile the terminal; process discovery remains* the authority for whether the agent exists.*@@ -17,7 +17,6 @@import http from 'node:http'import { execFile, execFileSync } from 'node:child_process'import { randomUUID } from 'node:crypto'-import { createConnection } from 'node:net'import {accessSync,closeSync,@@ -37,7 +36,7 @@ import {statSync,writeFileSync,} from 'node:fs'-import { basename, delimiter, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path'+import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'import { homedir, uptime } from 'node:os'const BOOT_TOLERANCE_SEC = 120@@ -348,12 +347,6 @@ function readHookCredential() {function terminalHookFields(tmuxPane) {const runtimeHints = []if (tmuxPane) runtimeHints.push({ backend: 'tmux', paneId: tmuxPane })- if (process.env.HERDR_PANE_ID) runtimeHints.push({- backend: 'herdr',- paneId: process.env.HERDR_PANE_ID,- sessionName: process.env.HERDR_SESSION,- socketPath: process.env.HERDR_SOCKET_PATH,- })return { tmuxPane, runtimeHints, callerPid: process.ppid }}@@ -658,119 +651,6 @@ async function rootEngineProcess(rootPid, engine) {} : { state: 'gone' }}-function safePathComponents(path) {- const root = parse(path).root- const result = [root]- for (const component of path.slice(root.length).split(sep).filter(Boolean)) {- result.push(resolve(result[result.length - 1], component))- }- return result-}--function readTerminalSnapshot(p) {- try {- const file = join(p.dataDir, 'terminal-config.json')- secureStateDirectory(p.dataDir, false)- const snapshot = JSON.parse(readPrivateStateFile(file, 64 * 1024))- if (snapshot?.version !== 1 || !Array.isArray(snapshot.backends) || !Array.isArray(snapshot.herdrEndpoints)) return null- return snapshot- } catch { return null }-}--function checkedHerdrEndpoint(endpoint) {- try {- if (!endpoint || typeof endpoint.socketPath !== 'string' || !isAbsolute(endpoint.socketPath)) return false- const uid = typeof process.getuid === 'function' ? process.getuid() : null- if (uid === null) return false- for (const component of safePathComponents(dirname(endpoint.socketPath))) {- const stat = lstatSync(component)- if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.uid !== uid && stat.uid !== 0)) return false- if ((stat.mode & 0o002) || (stat.uid === 0 && (stat.mode & 0o020))) return false- }- const parent = lstatSync(dirname(endpoint.socketPath))- const socket = lstatSync(endpoint.socketPath)- if (parent.uid !== uid || !socket.isSocket() || socket.isSymbolicLink() || socket.uid !== uid || (socket.mode & 0o777) !== 0o600) return false- if (realpathSync(endpoint.socketPath) !== resolve(endpoint.socketPath)) return false- return socket.dev === endpoint.generation?.device && socket.ino === endpoint.generation?.inode- } catch { return false }-}--function herdrRequest(endpoint, method, params) {- return new Promise((resolveRequest) => {- const budget = Math.min(1500, remainingBudget())- if (budget < 50 || !checkedHerdrEndpoint(endpoint)) { resolveRequest(null); return }- const id = randomUUID()- const frame = Buffer.from(`${JSON.stringify({ id, method, params })}\n`)- if (frame.byteLength > 1024 * 1024) { resolveRequest(null); return }- let response = Buffer.alloc(0)- let settled = false- let socket- const finish = (value) => {- if (settled) return- settled = true- clearTimeout(timer)- socket?.destroy()- resolveRequest(value)- }- const timer = setTimeout(() => finish(null), budget)- try { socket = createConnection({ path: endpoint.socketPath }) } catch { finish(null); return }- socket.once('connect', () => {- if (!checkedHerdrEndpoint(endpoint)) { finish(null); return }- try { socket.end(frame) } catch { finish(null) }- })- socket.on('data', (chunk) => {- response = Buffer.concat([response, chunk])- if (response.byteLength > 1024 * 1024) { finish(null); return }- const newline = response.indexOf(0x0a)- if (newline < 0) return- if (response.subarray(newline + 1).toString('utf8').trim()) { finish(null); return }- try {- const parsed = JSON.parse(response.subarray(0, newline).toString('utf8'))- finish(parsed?.id === id && parsed.result && !parsed.error ? parsed.result : null)- } catch { finish(null) }- })- socket.once('end', () => finish(null))- socket.once('error', () => finish(null))- })-}--async function herdrFallbackRuntime(engine) {- const hint = terminalHookFields(process.env.TMUX_PANE).runtimeHints.find((runtime) => runtime.backend === 'herdr')- if (!hint?.sessionName || !hint.socketPath || !hint.paneId) return null- const snapshot = readTerminalSnapshot(paths())- if (!snapshot?.backends.includes('herdr')) return null- const endpoint = snapshot.herdrEndpoints.find((candidate) =>- candidate?.sessionName === hint.sessionName && candidate?.socketPath === hint.socketPath)- if (!endpoint || !checkedHerdrEndpoint(endpoint)) return null- const pong = await herdrRequest(endpoint, 'ping', {})- if (pong?.type !== 'pong' || pong.protocol !== 19 || !/^0\.8\./.test(String(pong.version || ''))) return null- const [pane, info] = await Promise.all([- herdrRequest(endpoint, 'pane.get', { pane_id: hint.paneId }),- herdrRequest(endpoint, 'pane.process_info', { pane_id: hint.paneId }),- ])- if (pane?.type !== 'pane_info' || typeof pane.pane?.terminal_id !== 'string'- || info?.type !== 'pane_process_info' || !Number.isSafeInteger(info.process_info?.shell_pid)) return null- const owner = await rootEngineProcess(info.process_info.shell_pid, engine)- if (owner.state !== 'alive' || !owner.identity) return null- const rows = await processRows()- if (!rows) return null- const parents = new Map(rows.map((row) => [row.pid, row.parentPid]))- let caller = process.ppid- const visited = new Set()- while (caller > 0 && !visited.has(caller) && caller !== owner.identity.pid) {- visited.add(caller)- caller = parents.get(caller) || 0- }- if (caller !== owner.identity.pid) return null- return {- identity: owner.identity,- runtime: {- backend: 'herdr', endpointId: endpoint.endpointId, sessionName: endpoint.sessionName,- terminalId: pane.pane.terminal_id, paneId: pane.pane.pane_id,- },- }-}-/*** Hermes delegation children execute the same pane-scoped hook as the visible CLI session. During* daemon downtime the regular hook server cannot apply its source guard, so consult Hermes' own store@@ -1133,21 +1013,17 @@ async function clearCursorTasks(sessionId) {}function runtimeRouteKey(runtime) {- return runtime.backend === 'tmux'- ? `tmux\u0000${runtime.paneId}`- : `herdr\u0000${runtime.endpointId}\u0000${runtime.paneId}`+ return `tmux\u0000${runtime.paneId}`}function runtimePlacementKey(runtime) {- return runtime.backend === 'tmux'- ? runtimeRouteKey(runtime)- : `herdr\u0000${runtime.endpointId}\u0000${runtime.terminalId}`+ return runtimeRouteKey(runtime)}function mergeRuntimes(current, observed) {const merged = new Map()for (const runtime of [...(Array.isArray(current) ? current : []), ...observed]) {- if (runtime?.backend === 'tmux' || runtime?.backend === 'herdr') merged.set(runtimePlacementKey(runtime), runtime)+ if (runtime?.backend === 'tmux') merged.set(runtimePlacementKey(runtime), runtime)}return [...merged.values()].sort((a, b) => runtimePlacementKey(a).localeCompare(runtimePlacementKey(b)))}@@ -1162,13 +1038,8 @@ function validRegistryString(value, max = 4096) {}function validRegistryRuntime(runtime) {- if (!runtime || typeof runtime !== 'object') return false- if (runtime.backend === 'tmux') return typeof runtime.paneId === 'string' && /^%\d+$/.test(runtime.paneId)- return runtime.backend === 'herdr'- && validRegistryString(runtime.endpointId, 200) && runtime.endpointId.length > 0- && validRegistryString(runtime.sessionName, 64) && runtime.sessionName.length > 0- && validRegistryString(runtime.terminalId, 200) && runtime.terminalId.length > 0- && validRegistryString(runtime.paneId, 200) && runtime.paneId.length > 0+ return !!runtime && typeof runtime === 'object'+ && runtime.backend === 'tmux' && typeof runtime.paneId === 'string' && /^%\d+$/.test(runtime.paneId)}function validRegistryProcess(identity) {@@ -1260,8 +1131,6 @@ async function fallbackRegister(input, engine, tmuxPane) {observations.push({ identity: tmux.identity, runtime: { backend: 'tmux', paneId: tmuxPane } })}}- const herdr = await herdrFallbackRuntime(engine)- if (herdr) observations.push(herdr)if (!observations.length) returnconst process = observations[0]if (observations.some((observation) => observation.identity.pid !== process.identity.pid@@ -1379,7 +1248,7 @@ async function main() {const event = input.hook_event_name || input.hookEventNameconst tmuxPane = process.env.TMUX_PANE- if (!tmuxPane && !process.env.HERDR_PANE_ID) return+ if (!tmuxPane) returnconst mutationFields = { engine, ...terminalHookFields(tmuxPane) }if (engine === 'cursor' && input.is_background_agent === true) returnif (engine === 'codex' && isCodexSubagent(input, paths())) returndiff --git a/cli/package.json b/cli/package.jsonindex a47e3398f..61e59da2c 100644--- a/cli/package.json+++ b/cli/package.json@@ -20,7 +20,6 @@"test:remote-viewers": "vitest run --config vitest.viewer.config.ts","test:cursor-e2e": "RUN_CURSOR_E2E=1 vitest run src/engines/cursor/localE2e.spec.ts","test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts --reporter=verbose",- "test:herdr-real": "RUN_REAL_HERDR=1 vitest run src/lib/herdrBackend.real.spec.ts --reporter=verbose","test:resume": "vitest run src/lib/sessionRepair.spec.ts src/lib/captureResumeIdentity.spec.ts src/lib/resumeStoppedAgent.spec.ts src/lib/resumeAgentService.spec.ts src/lib/stoppedAgents.spec.ts src/lib/stopAgentService.spec.ts --coverage --coverage.include=src/lib/captureResumeIdentity.ts --coverage.include=src/lib/resumeStoppedAgent.ts --coverage.include=src/lib/resumeAgentService.ts --coverage.include=src/lib/stoppedAgents.ts --coverage.include=src/lib/stopAgentService.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/resume","test:resume-native": "tsx scripts/resume-native-e2e.ts","test:portability": "vitest run --config vitest.portability.config.ts"@@ -46,7 +45,7 @@"typescript": "^5.5.3","vitest": "^4.1.10"},- "description": "Run your own coding-agent CLIs (Claude Code, Codex, Cursor, OpenCode, Pi, Hermes, Command Code, Devin, Muse, Amp, Kilo, and Grok) in tmux, Herdr, or both and drive them from the web or a paired device.",+ "description": "Run your own coding-agent CLIs (Claude Code, Codex, Cursor, OpenCode, Pi, Hermes, Command Code, Devin, Muse, Amp, Kilo, and Grok) in tmux and drive them from the web or a paired device.","license": "MIT","repository": {"type": "git",diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 3dec67d14..c4fed14b5 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -134,14 +134,6 @@ import {checkSessionRuntime,tmuxPaneState,} from './lib/tmux.js'-import { HerdrBackend } from './lib/herdrBackend.js'-import {- discoverRunningHerdrSessions,- herdrHintSelects,- listInstalledHerdrSessions,- resolveConfiguredHerdrSessions,- type HerdrTargetResolution,-} from './lib/herdrSessions.js'import { ALL_TERMINAL_BACKENDS } from './config/terminalConfig.js'import { TerminalBackendCoordinator } from './lib/terminalBackendCoordinator.js'import { TerminalStreamManager } from './lib/terminalStreamManager.js'@@ -153,12 +145,10 @@ import { newCommand } from './lib/newCommand.js'import { WebSocket as NewCommandSocket } from 'ws'import {terminalActionNotStarted,- type HookTerminalHint,type TerminalActionResult,type TerminalRuntimeRef,type TmuxRuntimeRef,} from './lib/terminalTypes.js'-import { readTerminalConfigSnapshot, writeTerminalConfigSnapshot } from './lib/terminalConfigSnapshot.js'import { Watcher, type HistoryEvent, type LineEvent } from './watcher/watcher.js'import { chooseHookAgent, startHookServer } from './hookServer.js'import { isLocalSocketName, localSocketPath, type LocalSocketServer } from './lib/localSocket.js'@@ -1474,28 +1464,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {await registry.transaction(() => {for (const session of registry.list()) registry.setActive(session.agentId, false)})- // Unset means AUTO: watch every backend usable on this machine. Herdr is retired, so that set is- // tmux and only tmux (see config/terminalConfig.ts) — `parseTerminalBackends` drops a `herdr` still- // named in someone's environment rather than refusing to boot on it.- //- // NB this deliberately mirrors `parseTerminalConfig` instead of calling it, and the two must not- // drift: both read ALL_TERMINAL_BACKENDS for the AUTO case.+ // Unset means AUTO: watch every backend usable on this machine, which is tmux and only tmux (see+ // config/terminalConfig.ts). `parseTerminalBackends` drops a retired `herdr` still named in someone's+ // environment rather than refusing to boot on it.const backendsExplicit = env.TERMINAL_BACKENDS !== undefined- const herdrSessionsExplicit = env.HERDR_SESSIONS !== undefinedconst terminalConfig = {backends: env.TERMINAL_BACKENDS ?? ALL_TERMINAL_BACKENDS,- // Always empty: `backends` can no longer contain 'herdr', so every Herdr path below short-circuits- // and there is nothing left to name sessions for. HERDR_SESSIONS still parses so an existing- // environment does not fail boot; it simply selects nothing.- herdrSessions: [] as readonly string[],- }- /** The names in play right now: the operator's allowlist, or whatever Herdr currently reports. */- let activeHerdrSessions: readonly string[] = terminalConfig.herdrSessions- const resolveHerdrTargets = async (): Promise<HerdrTargetResolution[]> => {- if (!terminalConfig.backends.includes('herdr')) return []- return herdrSessionsExplicit- ? resolveConfiguredHerdrSessions(terminalConfig.herdrSessions, () => listInstalledHerdrSessions(env.HERDR_BIN))- : discoverRunningHerdrSessions(env.HERDR_BIN)}// Before ANY tmux call: a daemon that came up outside a terminal (the usual shape after a reboot)// has a minimal PATH, and every `execFile('tmux', …)` below would ENOENT. Ask the user's own login@@ -1526,114 +1500,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {// reaches sessions created after it without rebuilding the backend.let hostTheme: HostTheme = loadHostTheme() ?? DEFAULT_HOST_THEMEconst tmuxBackend = terminalConfig.backends.includes('tmux') && !tmuxUnavailable ? new TmuxBackend(() => hostTheme) : null- const herdrTargets = await resolveHerdrTargets()- activeHerdrSessions = herdrTargets.map((target) => target.sessionName)- const resolvedHerdrPaths = herdrTargets.flatMap((target) => target.state === 'available' ? [target.endpoint.socketPath] : [])- // Only an operator-named pair of aliases is a configuration error worth refusing to start over.- // Discovery cannot produce one — resolveConfiguredHerdrSessions already downgrades aliased sessions to- // unavailable — and a machine that never asked for Herdr must not fail to start because of it.- if (herdrSessionsExplicit && new Set(resolvedHerdrPaths).size !== resolvedHerdrPaths.length) {- throw new Error('two configured Herdr session names resolve to the same canonical endpoint')- }- const herdrStartup = await Promise.all(herdrTargets.map(async (target) => {- if (target.state === 'unavailable') return { sessionName: target.sessionName, state: 'unavailable' as const, reason: target.reason }- const backend = new HerdrBackend(target.endpoint)- const ping = await backend.client.ping()- if (ping.ok) return { sessionName: target.sessionName, state: 'available' as const, backend }- return {- sessionName: target.sessionName,- state: ping.code === 'protocol_mismatch' ? 'incompatible' as const : 'unavailable' as const,- reason: ping.reason,- }- }))- const herdrBackends = herdrStartup.flatMap((target) => target.state === 'available' ? [target.backend] : [])- const herdrTargetStates = new Map(herdrStartup.map((target) => [target.sessionName, {- state: target.state,- ...(target.state === 'available' ? {} : { reason: target.reason }),- }]))- // Fatal only when the operator asked for these backends. Auto-detection must never let a Herdr this- // build does not speak (a newer protocol, say) take down a daemon whose user never mentioned Herdr.- if (backendsExplicit && !tmuxBackend && herdrStartup.length > 0- && herdrStartup.every((target) => target.state === 'incompatible')) {- throw new Error('every enabled terminal backend is protocol-incompatible')- }- const terminalBackends = [...(tmuxBackend ? [tmuxBackend] : []), ...herdrBackends]+ const terminalBackends = tmuxBackend ? [tmuxBackend] : []const terminals = new TerminalBackendCoordinator(terminalBackends,terminalConfig.backends,- activeHerdrSessions,)- const refreshHerdrTargets = async (): Promise<void> => {- if (!terminalConfig.backends.includes('herdr')) return- const resolved = await resolveHerdrTargets()- // A session started after the daemon shows up here, on the next pass — which is the whole point:- // discovery, not configuration, decides what is watched.- activeHerdrSessions = resolved.map((target) => target.sessionName)- const available = resolved.filter((target): target is Extract<typeof target, { state: 'available' }> => target.state === 'available')- const aliased = new Set<string>()- const byPath = new Map<string, string>()- for (const target of available) {- const owner = byPath.get(target.endpoint.socketPath)- if (owner) { aliased.add(owner); aliased.add(target.sessionName) }- else byPath.set(target.endpoint.socketPath, target.sessionName)- }-- const recovered = new Map(herdrBackends.map((backend) => [backend.endpoint.sessionName, backend]))- for (const target of resolved) {- if (target.state === 'unavailable') {- herdrTargetStates.set(target.sessionName, { state: 'unavailable', reason: target.reason })- continue- }- if (aliased.has(target.sessionName)) {- recovered.delete(target.sessionName)- herdrTargetStates.set(target.sessionName, { state: 'incompatible', reason: 'configured Herdr sessions alias one endpoint' })- continue- }- const backend = new HerdrBackend(target.endpoint)- const ping = await backend.client.ping()- if (!ping.ok) {- if (ping.code === 'protocol_mismatch') recovered.delete(target.sessionName)- herdrTargetStates.set(target.sessionName, {- state: ping.code === 'protocol_mismatch' ? 'incompatible' : 'unavailable',- reason: ping.reason,- })- continue- }- recovered.set(target.sessionName, backend)- herdrTargetStates.set(target.sessionName, { state: 'available' })- }- herdrBackends.splice(0, herdrBackends.length, ...activeHerdrSessions.flatMap((name) => {- const backend = recovered.get(name)- return backend ? [backend] : []- }))- terminalBackends.splice(0, terminalBackends.length, ...(tmuxBackend ? [tmuxBackend] : []), ...herdrBackends)- terminals.replaceBackends(terminalBackends)- terminals.setHerdrSessionOrder(activeHerdrSessions)- if (herdrBackends.length === activeHerdrSessions.length) {- writeTerminalConfigSnapshot(env.ADAPTER_DATA_DIR, terminalConfig, herdrBackends.map((backend) => backend.endpoint))- }- }- const completeHerdrSnapshot = !terminalConfig.backends.includes('herdr')- || herdrBackends.length === activeHerdrSessions.length- if (completeHerdrSnapshot) {- writeTerminalConfigSnapshot(- env.ADAPTER_DATA_DIR,- terminalConfig,- herdrBackends.map((backend) => backend.endpoint),- )- } else {- const previous = readTerminalConfigSnapshot(env.ADAPTER_DATA_DIR)- const previousNames = previous?.herdrEndpoints.map((endpoint) => endpoint.sessionName) ?? []- if (JSON.stringify(previousNames) !== JSON.stringify(activeHerdrSessions)- || !previous?.backends.includes('herdr')) {- // The configured allowlist changed but cannot be resolved completely. Publish a fail-closed- // snapshot rather than leaving an old endpoint authorized for daemon-down hooks.- writeTerminalConfigSnapshot(env.ADAPTER_DATA_DIR, {- backends: terminalConfig.backends.filter((backend) => backend !== 'herdr'),- herdrSessions: [],- }, [])- }- }console.log(`[terminal] enabled backends: ${terminalConfig.backends.join(', ')}`)if (tmuxBackend) {// Before the first inventory: sessions a pre-prefix build named `<engine>-<ts>` are renamed to@@ -1667,11 +1538,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {: '[env] could not read a login shell environment — engine one-shots use the daemon environment only')})}- for (const target of herdrStartup) {- console.log(target.state === 'available'- ? `[terminal] Herdr session ${target.sessionName}: available`- : `[terminal] Herdr session ${target.sessionName}: ${target.state} (${target.reason})`)- }const terminalSession = (target: string): RegisteredSession | undefined => registry.resolve(target)const controlLeases = new Map<string, { lease: Awaited<ReturnType<typeof terminals.acquireLease>> & { state: 'succeeded' }; expiresAt: number }>()@@ -3387,8 +3253,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {current: () => registry.list(),backends: terminalBackends,backendOrder: terminalConfig.backends,- herdrSessionOrder: terminalConfig.herdrSessions,- beforeProbe: refreshHerdrTargets,transaction: (apply) => registry.transaction(apply),onDiscovered: async (observed) => {const launching = observed.runtimes@@ -3756,14 +3620,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (!callerPid) return nullconst resolved: TerminalRuntimeRef[] = []for (const hint of runtimeHints ?? []) {- if (hint.backend === 'tmux') {- if (tmuxBackend) resolved.push({ backend: 'tmux', paneId: hint.paneId })- continue- }- const backend = herdrBackends.find((candidate) => herdrHintSelects(candidate.endpoint, hint))- if (!backend) continue- const runtime = await backend.resolveRuntimeHint(hint.paneId)- if (runtime.state === 'succeeded') resolved.push(runtime.value)+ if (tmuxBackend) resolved.push({ backend: 'tmux', paneId: hint.paneId })}for (const runtime of resolved) await agentReconciler.triggerHint(runtime, engine)@@ -3789,8 +3646,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {* Caller ancestry is the strongest evidence and stays the first choice, but it assumes every engine* spawns its hook from inside its own process tree — and Cursor does not. Measured on both* backends: `agent` in a pane registers fine, then every one of its hooks is rejected because the- * process that POSTs is not a descendant of the pane's engine, so no session ever binds. It is not- * a Herdr problem; tmux fails identically.+ * process that POSTs is not a descendant of the pane's engine, so no session ever binds.** Keep that exception specific to Cursor. A delayed hook from an exited process can still name* a pane now owned by its replacement; the pane and hook credential alone cannot prove that a@@ -3803,21 +3659,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (callerBelongsTo(candidate)) candidates.set(candidate.agentId, candidate)else onHintedRuntime.set(candidate.agentId, candidate)}- // A moved Herdr pane may leave an inherited stale route. Caller/process correlation is the- // deterministic fallback, but only within a configured Herdr session named by the hook.- if (!candidates.size && runtimeHints?.some((hint) => hint.backend === 'herdr')) {- const configuredSessions = new Set(runtimeHints- .filter((hint): hint is Extract<HookTerminalHint, { backend: 'herdr' }> => hint.backend === 'herdr')- .flatMap((hint) => herdrBackends- .filter((backend) => herdrHintSelects(backend.endpoint, hint))- .map((backend) => backend.endpoint.sessionName)))- for (const candidate of registry.list()) {- if (candidate.engine !== engine || !callerBelongsTo(candidate)) continue- if (candidate.runtimes.some((runtime) => runtime.backend === 'herdr' && configuredSessions.has(runtime.sessionName))) {- candidates.set(candidate.agentId, candidate)- }- }- }const choice = chooseHookAgent([...candidates.values()], [...onHintedRuntime.values()], engine)if (choice.agent) {if (choice.reason === 'runtime') {@@ -4077,18 +3918,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {config: {watching: `${terminalConfig.backends.join(' + ')} terminals across all supported engines`,terminalBackends: terminalConfig.backends,- // What is watched NOW, not what was configured at boot: under auto-detection the session set is- // discovered per pass, so reporting the (empty) configured list would answer the wrong question- // for the one person most likely to ask it — someone checking why their pane is not showing up.- herdrSessions: activeHerdrSessions,terminalSelection: backendsExplicit ? 'configured' : 'auto',terminalTargets: [...(tmuxBackend ? [{ backend: 'tmux', instance: 'default', state: 'configured' }] : []),- ...activeHerdrSessions.map((sessionName) => ({- backend: 'herdr',- sessionName,- ...(herdrTargetStates.get(sessionName) ?? { state: 'unavailable', reason: 'not yet resolved' }),- })),],dormantAgents: registry.list().filter((session) => !session.active).length,dataDir: tildify(env.ADAPTER_DATA_DIR),@@ -5549,8 +5381,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const session = registry.resolve(agentId)if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }const pane = session.runtimes.find((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')- // Only tmux panes can be respawned. A Herdr-hosted agent has no equivalent, and saying so is better- // than a generic failure the user cannot act on.+ // Only tmux panes can be respawned. Saying so is better than a generic failure the user cannot act on.if (!pane) return { ok: false, error: 'RETARGET_UNSUPPORTED_BACKEND', detail: `${session.engine} is not running in a tmux pane` }// The swap kills a process it has validated by pid + start marker. Without one there is nothing to// validate, and respawning over a pane whose occupant we cannot identify is how you replacediff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex 1f0673ce6..e7f4f3de9 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -3,7 +3,7 @@ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync } from 'fs'import { homedir } from 'os'import { join } from 'path'import { z } from 'zod'-import { parseHerdrSessions, parseTerminalBackends } from './terminalConfig.js'+import { parseTerminalBackends } from './terminalConfig.js'import { adoptComputerId } from '../lib/computerIdentity.js'// Packaged files (cli.js/notify.mjs) live in ~/.harness/cli; mutable state in ~/.harness/cli/data.@@ -259,11 +259,8 @@ const envSchema = z.object({// `harness start` and `harness login` install the `grid` CLI when the machine has none (see// lib/gridInstall.ts). Off for tests and for a machine whose grid is managed some other way.DISABLE_GRID_INSTALL: z.string().default('false').transform((v) => v === 'true'),- // Additive terminal capability. Order controls deterministic primary-route tie breaking.- //- // UNSET MEANS AUTO — every backend that is actually usable here, which is what makes `herdr` then an- // engine behave like `tmux new` then an engine, with nothing to configure. Set it to pin: `tmux` is- // how you turn Herdr off. Validation is unchanged for a value that IS given.+ // Terminal backends to watch. UNSET MEANS AUTO — every backend usable here, which is tmux. A value+ // pins the set; a retired name still in someone's environment is dropped with a warning.TERMINAL_BACKENDS: z.string().optional().transform((value, context) => {if (value === undefined || value === '') return undefinedtry { return parseTerminalBackends(value) } catch (error) {@@ -271,16 +268,6 @@ const envSchema = z.object({return z.NEVER}}),- // Named Herdr sessions. UNSET means "adopt the sessions Herdr reports as running"; a value is a strict- // allowlist that discovery never widens, and hook-supplied socket paths never expand it either.- HERDR_SESSIONS: z.string().optional().transform((value, context) => {- if (value === undefined || value === '') return undefined- try { return parseHerdrSessions(value) } catch (error) {- context.addIssue({ code: 'custom', message: error instanceof Error ? error.message : 'invalid Herdr sessions' })- return z.NEVER- }- }),- HERDR_BIN: z.string().default('herdr'),// Neutral discovery interval. The legacy tmux name remains a one-release fallback.TERMINAL_RECONCILE_INTERVAL_MS: z.string().optional().transform((value) => value === undefined ? undefined : Number(value)),// How often (ms) the reaper checks tmux panes and drops dead sessions.diff --git a/cli/src/config/terminalConfig.spec.ts b/cli/src/config/terminalConfig.spec.tsindex f1adfde02..f02955ea7 100644--- a/cli/src/config/terminalConfig.spec.ts+++ b/cli/src/config/terminalConfig.spec.ts@@ -1,28 +1,19 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { parseHerdrSessions, parseTerminalBackends, parseTerminalConfig } from './terminalConfig.js'+import { ALL_TERMINAL_BACKENDS, parseTerminalBackends } from './terminalConfig.js'afterEach(() => vi.restoreAllMocks())describe('terminal backend configuration', () => {- it('watches every supported backend when nothing is configured — tmux, and only tmux', () => {- expect(parseTerminalConfig({})).toEqual({- backends: ['tmux'],- herdrSessions: [],- backendsExplicit: false,- herdrSessionsExplicit: false,- })+ it('watches tmux, and only tmux, when nothing is configured', () => {+ expect(ALL_TERMINAL_BACKENDS).toEqual(['tmux'])})it('treats an explicit value as a pin', () => {- expect(parseTerminalConfig({ TERMINAL_BACKENDS: 'tmux' })).toMatchObject({- backends: ['tmux'],- herdrSessions: [],- backendsExplicit: true,- })+ expect(parseTerminalBackends('tmux')).toEqual(['tmux'])})/**- * Herdr is retired, and a machine that still names it must keep running. The daemon SELF-UPDATES:+ * A machine that still names the retired herdr backend must keep running. The daemon SELF-UPDATES:* refusing to start on a retired name would take down an unattended computer at the moment it picked* up a new build, for a setting the user cannot be there to fix. So it is dropped, loudly, not fatal.*/@@ -40,21 +31,7 @@ describe('terminal backend configuration', () => {expect(warn).toHaveBeenCalledWith(expect.stringContaining('falling back to tmux'))})- it('never reports herdr sessions, even when HERDR_SESSIONS is set', () => {- // The variable still validates so an existing environment does not fail boot, but there is no- // backend left to name sessions for, so the resolved list is empty.- expect(parseTerminalConfig({ HERDR_SESSIONS: 'work,default' })).toMatchObject({- backends: ['tmux'],- herdrSessions: [],- herdrSessionsExplicit: true,- })- })-it.each(['', ' ', 'tmux,', 'tmux,,tmux', 'tmux,tmux', 'screen'])('rejects invalid TERMINAL_BACKENDS=%j', (value) => {expect(() => parseTerminalBackends(value)).toThrow(/TERMINAL_BACKENDS/)})-- it.each(['', 'default,', 'default,default', '../socket', '/tmp/socket', 'work space'])('rejects invalid HERDR_SESSIONS=%j', (value) => {- expect(() => parseHerdrSessions(value)).toThrow(/HERDR_SESSIONS/)- })})diff --git a/cli/src/config/terminalConfig.ts b/cli/src/config/terminalConfig.tsindex 5e267d6a5..540d64eb8 100644--- a/cli/src/config/terminalConfig.ts+++ b/cli/src/config/terminalConfig.ts@@ -1,38 +1,8 @@import type { TerminalBackendName } from '../lib/terminalTypes.js'-const HERDR_SESSION_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/--/**- * Every backend the daemon drives. tmux is the only one — Herdr was retired as a supported backend.- *- * The `herdr*` modules are still in the tree and `HerdrRuntimeRef` is still part of the runtime union,- * because both are reachable from state written by older builds; what changed is that nothing puts- * `herdr` in this list any more, and every Herdr code path in cli.ts is already gated on- * `backends.includes('herdr')`, so none of it is constructed or reached.- */+/** Every backend the daemon drives. tmux is the only one. */export const ALL_TERMINAL_BACKENDS: readonly TerminalBackendName[] = ['tmux']-/** What is watched right now. This is also the persisted snapshot shape — keep it serializable. */-export interface TerminalConfig {- backends: readonly TerminalBackendName[]- /** Empty under auto-detection: the session set comes from discovery, not from configuration. */- herdrSessions: readonly string[]-}--export interface ResolvedTerminalConfig extends TerminalConfig {- /**- * Did the operator name the backends, or did we?- *- * It decides what happens when one of them turns out to be unusable. An explicitly configured backend- * that fails is a startup error — it was asked for, and silence would be a lie. An auto-detected one- * is simply absent, because nobody asked for it and a machine without Herdr must not be told about- * Herdr, still less refuse to start because of it.- */- backendsExplicit: boolean- /** Same distinction for the session list: a named allowlist is honoured verbatim, never widened. */- herdrSessionsExplicit: boolean-}-function strictList(value: string, field: string): string[] {const parts = value.split(',').map((part) => part.trim())if (!parts.length || parts.some((part) => !part)) {@@ -43,7 +13,7 @@ function strictList(value: string, field: string): string[] {}/**- * `herdr` is dropped with a warning rather than rejected.+ * `herdr` — a backend earlier builds supported — is dropped with a warning rather than rejected.** Rejecting it would be the consistent thing to do — an unknown backend is an error — but the daemon* SELF-UPDATES. A machine whose environment still says `TERMINAL_BACKENDS=tmux,herdr` would install a@@ -68,42 +38,3 @@ export function parseTerminalBackends(value = 'tmux'): TerminalBackendName[] {}return kept}--/**- * Retained so an existing `HERDR_SESSIONS` in someone's environment still validates instead of failing- * boot, but the value is inert: `parseTerminalConfig` no longer feeds it anywhere now that `herdr` is- * never in the backend list.- */-export function parseHerdrSessions(value = 'default'): string[] {- const values = strictList(value, 'HERDR_SESSIONS')- for (const session of values) {- if (!HERDR_SESSION_RE.test(session)) {- throw new Error(`HERDR_SESSIONS contains invalid session name "${session}"`)- }- }- return values-}--/**- * Unset means AUTO — every backend usable on this machine, which is now tmux and only tmux.- *- * The tmux flow has never asked for configuration: start a pane, run the engine, the agent appears.- * With Herdr retired there is nothing left for `TERMINAL_BACKENDS` to select between, so the variable- * survives only as a pin (and as the place that warns about the retired name). `herdrSessions` is- * always empty for the same reason — there is no backend left to name sessions for.- */-export function parseTerminalConfig(input: {- TERMINAL_BACKENDS?: string- HERDR_SESSIONS?: string-}): ResolvedTerminalConfig {- const backendsExplicit = input.TERMINAL_BACKENDS !== undefined && input.TERMINAL_BACKENDS !== ''- const backends = backendsExplicit ? parseTerminalBackends(input.TERMINAL_BACKENDS) : ALL_TERMINAL_BACKENDS- const herdrSessionsExplicit = input.HERDR_SESSIONS !== undefined && input.HERDR_SESSIONS !== ''- return {- backends,- // Always empty: `backends` can no longer contain 'herdr', so there is nothing to name sessions for.- herdrSessions: [],- backendsExplicit,- herdrSessionsExplicit,- }-}diff --git a/cli/src/engines/README.md b/cli/src/engines/README.mdindex 7c95b818b..a3cc74ce9 100644--- a/cli/src/engines/README.md+++ b/cli/src/engines/README.md@@ -250,10 +250,10 @@ the bare name silently finds nothing.### Process identity matrix-Process discovery is evidence-based and shared by tmux and Herdr. Resolve commands in the same-interactive shell used to launch them, follow symlinks, then compare the running image by local-`(device,inode)` identity (`/proc/<pid>/exe` on Linux, batched `lsof` on macOS). Basename and package-entrypoint rules remain fallbacks for launchers that exec an interpreter or rewrite their process title.+Process discovery is evidence-based. Resolve commands in the same interactive shell used to launch+them, follow symlinks, then compare the running image by local `(device,inode)` identity+(`/proc/<pid>/exe` on Linux, batched `lsof` on macOS). Basename and package entrypoint rules remain+fallbacks for launchers that exec an interpreter or rewrite their process title.| Engine | Supported runtime evidence ||---|---|diff --git a/cli/src/engines/opencode/reader.ts b/cli/src/engines/opencode/reader.tsindex cc31e2aaf..ae95593b0 100644--- a/cli/src/engines/opencode/reader.ts+++ b/cli/src/engines/opencode/reader.ts@@ -141,10 +141,9 @@ export class OpencodeReader {* and return the one event that MUST still be emitted: a `turn_started` when we attached mid-turn.** Hydrating in silence loses the opening frame of a turn that is already running, and the daemon then- * drops that turn's recap because it never saw it open. Measured on a real pane, on both terminal- * backends:+ * drops that turn's recap because it never saw it open. Measured on a real pane:*- * [agent] fa12f4cb re-attached · engine=opencode · terminal=herdr:default:wG:p1 · session=ses_fec1+ * [agent] fa12f4cb re-attached · engine=opencode · terminal=tmux:%12 · session=ses_fec1* [turn] ses_fec1 ended ← close with nothing to close* [recap] DROPPED (no turn_started was ever seen for this session)*diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 690ea4de4..23692d26e 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -2,13 +2,11 @@ import { execFileSync, spawn, spawnSync } from 'child_process'import { createServer } from 'http'import { createServer as createNetServer } from 'net'import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs'-import { homedir, tmpdir } from 'os'+import { tmpdir } from 'os'import { join } from 'path'import { fileURLToPath } from 'url'import { afterEach, describe, expect, it, vi } from 'vitest'-const isRoot = typeof process.getuid === 'function' && process.getuid() === 0-// Every case here spawns the real hook as a child process, and several spawn shell shims for tmux, ps// and sqlite3 on top of that. On a loaded machine — this file runs alongside 88 others — that chain// takes well over vitest's 5s default, and the failure looks like a product bug rather than what it is.@@ -517,148 +515,6 @@ describe('hook notify terminal scope', () => {expect(registry).toMatchObject([{ sessionId: 'codex-session', engine: 'codex', tmuxPane: '%8' }])})- /**- * Skipped when the suite itself runs as root (common in a container). `checkedSocket` rejects a- * root-OWNED directory that is group-writable — `(stat.uid === 0 && permissions & 0o020)` — because- * under root ownership the group bit really does let another account plant a socket. The rule is- * correct; it is this case's premise ("the owner is a normal account") that does not hold as root.- * Same precedent as the getuid()===0 guard in lib/fsBrowse.spec.ts.- */- it.skipIf(isRoot)('uses only a configured, validated Herdr endpoint for daemon-down registration', async () => {- const dir = mkdtempSync(join(homedir(), '.adapter-hook-herdr-'))- tmpDirs.push(dir)- chmodSync(dir, 0o775)- const dataDir = join(dir, 'data')- const claudeProjectsDir = join(dir, 'claude-projects')- const transcriptPath = join(claudeProjectsDir, 'demo', 'herdr-session.jsonl')- const socketPath = join(dir, 'herdr.sock')- mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })- mkdirSync(dataDir, { recursive: true })- chmodSync(dataDir, 0o755)- writeFileSync(transcriptPath, '{}\n')- const server = createNetServer((socket) => {- let raw = ''- socket.on('data', (chunk) => { raw += chunk.toString('utf8') })- socket.on('end', () => {- const request = JSON.parse(raw.trim()) as { id: string; method: string }- const result = request.method === 'ping'- ? { type: 'pong', version: '0.8.0', protocol: 19 }- : request.method === 'pane.get'- ? { type: 'pane_info', pane: { pane_id: 'w1:p1', terminal_id: 'terminal-1' } }- : { type: 'pane_process_info', process_info: { pane_id: 'w1:p1', shell_pid: 7000 } }- socket.end(`${JSON.stringify({ id: request.id, result })}\n`)- })- })- netServers.push(server)- await new Promise<void>((resolve) => server.listen(socketPath, resolve))- chmodSync(socketPath, 0o600)- const socket = statSync(socketPath)- writeFileSync(join(dataDir, 'terminal-config.json'), `${JSON.stringify({- version: 1,- updatedAt: Date.now(),- backends: ['herdr'],- herdrEndpoints: [{- sessionName: 'test', endpointId: 'endpoint-test', socketPath,- generation: { device: socket.dev, inode: socket.ino },- }],- })}\n`, { mode: 0o600 })- chmodSync(join(dataDir, 'terminal-config.json'), 0o644)-- await runHook({- port: 9,- processEngine: 'claude',- dataDir,- claudeProjectsDir,- env: { HERDR_PANE_ID: 'w1:p1', HERDR_SESSION: 'test', HERDR_SOCKET_PATH: socketPath },- input: {- hook_event_name: 'SessionStart', session_id: 'herdr-session', transcript_path: transcriptPath, cwd: '/tmp/demo',- },- })-- expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))).toMatchObject([{- schemaVersion: 2,- active: true,- sessionId: 'herdr-session',- primaryRuntimeKey: 'herdr\u0000endpoint-test\u0000w1:p1',- runtimes: [{- backend: 'herdr', endpointId: 'endpoint-test', sessionName: 'test', terminalId: 'terminal-1', paneId: 'w1:p1',- }],- }])- expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))[0]).not.toHaveProperty('tmuxPane')- expect(statSync(join(dataDir, 'terminal-config.json')).mode & 0o777).toBe(0o600)- })-- it('rejects a world-writable Herdr endpoint parent during daemon-down registration', async () => {- const dir = mkdtempSync(join(homedir(), '.adapter-hook-herdr-world-writable-'))- tmpDirs.push(dir)- const dataDir = join(dir, 'data')- const claudeProjectsDir = join(dir, 'claude-projects')- const transcriptPath = join(claudeProjectsDir, 'demo', 'herdr-session.jsonl')- const socketPath = join(dir, 'herdr.sock')- mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })- mkdirSync(dataDir, { mode: 0o700 })- writeFileSync(transcriptPath, '{}\n')- let requestCount = 0- const server = createNetServer((socket) => {- requestCount++- socket.end()- })- netServers.push(server)- await new Promise<void>((resolve) => server.listen(socketPath, resolve))- chmodSync(socketPath, 0o600)- const socket = statSync(socketPath)- writeFileSync(join(dataDir, 'terminal-config.json'), `${JSON.stringify({- version: 1,- updatedAt: Date.now(),- backends: ['herdr'],- herdrEndpoints: [{- sessionName: 'test', endpointId: 'endpoint-test', socketPath,- generation: { device: socket.dev, inode: socket.ino },- }],- })}\n`, { mode: 0o600 })- chmodSync(dir, 0o777)-- await runHook({- port: 9,- processEngine: 'claude',- dataDir,- claudeProjectsDir,- env: { HERDR_PANE_ID: 'w1:p1', HERDR_SESSION: 'test', HERDR_SOCKET_PATH: socketPath },- input: {- hook_event_name: 'SessionStart', session_id: 'herdr-session', transcript_path: transcriptPath, cwd: '/tmp/demo',- },- })-- expect(requestCount).toBe(0)- expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf8')).toThrow()- })-- it('rejects a group-writable Herdr config without changing or trusting it', async () => {- const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-herdr-unsafe-config-'))- tmpDirs.push(dir)- const dataDir = join(dir, 'data')- const config = join(dataDir, 'terminal-config.json')- mkdirSync(dataDir, { mode: 0o700 })- writeFileSync(config, `${JSON.stringify({- version: 1,- updatedAt: Date.now(),- backends: ['herdr'],- herdrEndpoints: [],- })}\n`, { mode: 0o600 })- chmodSync(config, 0o660)-- await runHook({- port: 9,- processEngine: 'claude',- dataDir,- env: { HERDR_PANE_ID: 'w1:p1', HERDR_SESSION: 'test', HERDR_SOCKET_PATH: join(dir, 'herdr.sock') },- input: { hook_event_name: 'SessionStart', session_id: 'unsafe-config' },- })-- expect(statSync(config).mode & 0o777).toBe(0o660)- expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf8')).toThrow()- })-it('does not treat engine names in unrelated process arguments as an offline agent', async () => {const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-process-false-positive-'))tmpDirs.push(dir)diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex d67c306cd..36941b284 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -84,6 +84,46 @@ describe('process-owned hook server', () => {expect(handlers.onRegistered).not.toHaveBeenCalled()})+ it('accepts a Herdr hint from a hook installed by an earlier build, and resolves by its tmux pane only', async () => {+ const resolveHookAgent = vi.fn(async () => null)+ const { base, headers } = await start({ resolveHookAgent })+ const response = await fetch(`${base}/api/hook/session-start`, {+ method: 'POST',+ headers,+ body: JSON.stringify({+ engine: 'codex',+ tmuxPane: '%41',+ sessionId: '019fea92-e31a-7692-9c35-f616e9d458b7',+ runtimeHints: [+ { backend: 'tmux', paneId: '%41' },+ { backend: 'herdr', paneId: 'w1:p1', sessionName: 'default', socketPath: '/tmp/herdr.sock' },+ ],+ }),+ })++ expect(response.status).toBe(200)+ expect(resolveHookAgent).toHaveBeenCalledWith({+ engine: 'codex', tmuxPane: '%41', runtimeHints: [{ backend: 'tmux', paneId: '%41' }], callerPid: undefined,+ })+ })++ it('ignores a hook whose only terminal is a Herdr pane', async () => {+ const resolveHookAgent = vi.fn(async () => null)+ const { base, headers } = await start({ resolveHookAgent })+ const response = await fetch(`${base}/api/hook/session-start`, {+ method: 'POST',+ headers,+ body: JSON.stringify({+ engine: 'claude',+ sessionId: 'session-1',+ runtimeHints: [{ backend: 'herdr', paneId: 'w1:p1', sessionName: 'default' }],+ }),+ })++ expect(await response.json()).toEqual({ ignored: true, reason: 'not_in_terminal' })+ expect(resolveHookAgent).not.toHaveBeenCalled()+ })+it('rejects hooks outside configured terminal contexts before attempting process resolution', async () => {const resolveHookAgent = vi.fn(async () => null)const { handlers, base, headers } = await start({ resolveHookAgent })diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex dc91e0483..0496964e2 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -31,8 +31,7 @@ import { isTrustedLocal, listenLocalSocket, type LocalSocketServer } from './lib** Caller ancestry — the hook's process descends from the engine we registered — is the strong one and* always wins. It is not always available: Cursor posts its hooks from outside the pane's process tree,- * on tmux and on Herdr alike, so requiring ancestry rejected every hook that engine ever sent and no- * session bound at all.+ * so requiring ancestry rejected every hook that engine ever sent and no session bound at all.** Only Cursor may use the weaker runtime evidence: the hook named a pane carrying exactly one Cursor* agent, and the caller already proved it can read the 0600 hook credential. Other engines must match@@ -190,6 +189,9 @@ function validHookBody(value: unknown): value is BoundHookBody {if (Object.keys(hint).some((field) => field !== 'backend' && field !== 'paneId')|| typeof hint.paneId !== 'string' || !/^%\d+$/.test(hint.paneId)) return false} else if (hint.backend === 'herdr') {+ // A hook script installed by an earlier build still sends these from inside a Herdr pane. The+ // backend is retired and `normalizedRuntimeHints` drops the hint, but the rest of the body is+ // still good evidence, so the shape stays accepted rather than failing the whole request.if (Object.keys(hint).some((field) => !['backend', 'paneId', 'sessionName', 'socketPath'].includes(field))|| !optionalBoundedString(hint.paneId, 200) || !hint.paneId|| !optionalBoundedString(hint.sessionName, 64)@@ -221,16 +223,6 @@ function normalizedRuntimeHints(body: RegisterInput): HookTerminalHint[] {if (Array.isArray(body.runtimeHints) && body.runtimeHints.length <= 4) {for (const hint of body.runtimeHints) {if (hint?.backend === 'tmux' && /^%\d+$/.test(hint.paneId)) hints.push({ backend: 'tmux', paneId: hint.paneId })- if (hint?.backend === 'herdr'- && typeof hint.paneId === 'string' && hint.paneId.length <= 200- && (hint.sessionName === undefined || (typeof hint.sessionName === 'string' && hint.sessionName.length <= 64))- && (hint.socketPath === undefined || (typeof hint.socketPath === 'string' && hint.socketPath.length <= 4_096))) {- hints.push({- backend: 'herdr', paneId: hint.paneId,- ...(hint.sessionName ? { sessionName: hint.sessionName } : {}),- ...(hint.socketPath ? { socketPath: hint.socketPath } : {}),- })- }}}if (body.tmuxPane && /^%\d+$/.test(body.tmuxPane)diff --git a/cli/src/lib/__fixtures__/herdr/pty-capture.mjs b/cli/src/lib/__fixtures__/herdr/pty-capture.mjsdeleted file mode 100644index 6bb308e1b..000000000--- a/cli/src/lib/__fixtures__/herdr/pty-capture.mjs+++ /dev/null@@ -1,31 +0,0 @@-import { writeFileSync, writeSync } from 'node:fs'--const [outputPath, readyPath] = process.argv.slice(2)-if (!outputPath || !readyPath || !process.stdin.isTTY || typeof process.stdin.setRawMode !== 'function') {- process.exit(2)-}--process.stdin.setRawMode(true)-process.stdin.resume()-writeSync(1, '\u001b[?2004h')-writeFileSync(readyPath, 'ready', { mode: 0o600 })--const chunks = []-const deadline = setTimeout(() => process.exit(3), 10_000)--process.stdin.on('data', (chunk) => {- chunks.push(Buffer.from(chunk))- const bytes = Buffer.concat(chunks)- const bracketedEnd = bytes.indexOf(Buffer.from('\u001b[201~'))- if (bracketedEnd < 0 || bytes.indexOf(0x0d, bracketedEnd + 6) < 0) return- clearTimeout(deadline)- writeFileSync(outputPath, JSON.stringify({- base64: bytes.toString('base64'),- byteLength: bytes.byteLength,- bracketedStarts: bytes.toString('binary').split('\u001b[200~').length - 1,- bracketedEnds: bytes.toString('binary').split('\u001b[201~').length - 1,- carriageReturnsAfterPaste: [...bytes.subarray(bracketedEnd + 6)].filter((byte) => byte === 0x0d).length,- }), { mode: 0o600 })- writeSync(1, '\u001b[?2004l')- process.exit(0)-})diff --git a/cli/src/lib/binaryOnPath.ts b/cli/src/lib/binaryOnPath.tsindex e1234616d..720f50e53 100644--- a/cli/src/lib/binaryOnPath.ts+++ b/cli/src/lib/binaryOnPath.ts@@ -3,9 +3,6 @@** Resolved by reading PATH rather than by spawning: callers use it on the startup path and in error* reporting, where launching a process to ask would be both slower and noisier.- *- * The same shape already lives in `herdrBinaryAvailable` (lib/herdrSessions.ts), which keeps its own- * copy because it is exported API with its own tests.*/import { accessSync, constants } from 'node:fs'import { delimiter, join } from 'node:path'diff --git a/cli/src/lib/discoveryScripts.spec.ts b/cli/src/lib/discoveryScripts.spec.tsindex 21cfea115..ba9ec83fb 100644--- a/cli/src/lib/discoveryScripts.spec.ts+++ b/cli/src/lib/discoveryScripts.spec.ts@@ -26,7 +26,7 @@ describe('generated discovery scripts', () => {const src = readFileSync(join(piHome, 'agent', 'extensions', 'launcher-register.ts'), 'utf-8')expect(src).toContain('process.env.TMUX_PANE')- expect(src).toContain('process.env.HERDR_PANE_ID')+ expect(src).not.toContain('HERDR')expect(src).not.toContain('MACHINE_ID')expect(src).not.toContain('launcherId')})@@ -40,9 +40,9 @@ describe('generated discovery scripts', () => {const src = readFileSync(join(pluginDir, 'launcher-register.js'), 'utf-8')expect(src).toContain('process.env.TMUX_PANE')- expect(src).toContain('process.env.HERDR_PANE_ID')+ expect(src).not.toContain('HERDR')expect(src).not.toContain('MACHINE_ID')expect(src).not.toContain('launcherId')- expect(src).toContain('if ((!pane && !herdrPane)')+ expect(src).toContain('if (!pane || !token')})})diff --git a/cli/src/lib/herdrApiClient.spec.ts b/cli/src/lib/herdrApiClient.spec.tsdeleted file mode 100644index 887e92a29..000000000--- a/cli/src/lib/herdrApiClient.spec.ts+++ /dev/null@@ -1,233 +0,0 @@-import { createServer, type Server } from 'node:net'-import { chmod, lstat, mkdir, mkdtemp, rm, symlink } from 'node:fs/promises'-import { homedir } from 'node:os'-import { join } from 'node:path'-import { afterEach, describe, expect, it } from 'vitest'--const isRoot = typeof process.getuid === 'function' && process.getuid() === 0-import {- HERDR_API_PROTOCOL,- HERDR_API_SCHEMA_VERSION,- HerdrApiClient,- HerdrEndpointError,- resolveHerdrEndpoint,- type HerdrEndpoint,-} from './herdrApiClient.js'--const dirs: string[] = []-const servers: Server[] = []--async function tempDir(): Promise<string> {- const dir = await mkdtemp(join(homedir(), '.harness-herdr-api-test-'))- dirs.push(dir)- await chmod(dir, 0o700)- return dir-}--async function socketServer(- handle: (request: Record<string, unknown>, socket: import('node:net').Socket) => void,-): Promise<{ endpoint: HerdrEndpoint; socketPath: string }> {- const dir = await tempDir()- const socketPath = join(dir, 'herdr.sock')- const server = createServer((socket) => {- let input = ''- socket.setEncoding('utf8')- socket.on('data', (chunk) => {- input += chunk- const newline = input.indexOf('\n')- if (newline < 0) return- const request = JSON.parse(input.slice(0, newline)) as Record<string, unknown>- handle(request, socket)- })- })- servers.push(server)- await new Promise<void>((resolve, reject) => {- server.once('error', reject)- server.listen(socketPath, resolve)- })- await chmod(socketPath, 0o600)- return {- socketPath,- endpoint: await resolveHerdrEndpoint({ sessionName: 'test', socketPath }),- }-}--afterEach(async () => {- await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))))- await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))-})--describe('HerdrApiClient', () => {- it('uses one bounded NDJSON request and validates the response id', async () => {- let observed: Record<string, unknown> | null = null- const { endpoint } = await socketServer((request, socket) => {- observed = request- socket.end(`${JSON.stringify({- id: request.id,- result: {- type: 'pong',- version: '0.8.0',- protocol: HERDR_API_PROTOCOL,- capabilities: { live_handoff: true, detached_server_daemon: true },- },- })}\n`)- })-- const result = await new HerdrApiClient(endpoint).ping()-- expect(result).toEqual({- ok: true,- result: {- type: 'pong',- version: '0.8.0',- protocol: HERDR_API_PROTOCOL,- capabilities: { live_handoff: true, detached_server_daemon: true },- },- })- expect(observed).toMatchObject({ method: 'ping', params: {} })- expect(typeof (observed as Record<string, unknown> | null)?.id).toBe('string')- })-- it('classifies validation, connect, and pre-write abort failures as not started', async () => {- const dir = await tempDir()- const missing = join(dir, 'missing.sock')- await expect(resolveHerdrEndpoint({ sessionName: 'missing', socketPath: missing }))- .rejects.toBeInstanceOf(HerdrEndpointError)-- const { endpoint } = await socketServer((_request, socket) => socket.end())- const controller = new AbortController()- controller.abort()- await expect(new HerdrApiClient(endpoint).request('pane.send_input', {- pane_id: 'w1:p1',- text: 'secret-prompt',- keys: ['Enter'],- }, { mutation: 'single_enqueue', signal: controller.signal })).resolves.toMatchObject({- ok: false,- dispatch: 'not_started',- })- })-- it('classifies a lost response after write as possibly executed without leaking request text', async () => {- const { endpoint } = await socketServer((_request, socket) => socket.destroy())- const result = await new HerdrApiClient(endpoint, { timeoutMs: 250 }).request('pane.send_input', {- pane_id: 'w1:p1',- text: 'unique-secret-prompt',- keys: ['Enter'],- }, { mutation: 'single_enqueue' })-- expect(result).toMatchObject({ ok: false, dispatch: 'possibly_executed' })- expect(JSON.stringify(result)).not.toContain('unique-secret-prompt')- expect(JSON.stringify(result)).not.toContain(endpoint.socketPath)- })-- it('classifies only proven single-enqueue rejections as rejected', async () => {- const { endpoint } = await socketServer((request, socket) => {- socket.end(`${JSON.stringify({- id: request.id,- error: { code: 'pane_send_failed', message: 'queue full' },- })}\n`)- })- const client = new HerdrApiClient(endpoint)-- await expect(client.request('pane.send_input', {- pane_id: 'w1:p1', text: 'hello', keys: ['Enter'],- }, { mutation: 'single_enqueue' })).resolves.toMatchObject({- ok: false,- dispatch: 'rejected',- code: 'pane_send_failed',- })- await expect(client.request('pane.send_keys', {- pane_id: 'w1:p1', keys: ['Down', 'Enter'],- }, { mutation: 'multi_enqueue' })).resolves.toMatchObject({- ok: false,- dispatch: 'possibly_executed',- code: 'pane_send_failed',- })- })-- it('treats malformed, mismatched, and oversized post-write responses as ambiguous', async () => {- const cases = [- (request: Record<string, unknown>, socket: import('node:net').Socket) => socket.end('{bad json}\n'),- (_request: Record<string, unknown>, socket: import('node:net').Socket) => socket.end('{"id":"wrong","result":{"type":"ok"}}\n'),- (request: Record<string, unknown>, socket: import('node:net').Socket) => socket.end(`${JSON.stringify({ id: request.id, result: { type: 'ok', padding: 'x'.repeat(2_000) } })}\n`),- ]- for (const handle of cases) {- const { endpoint } = await socketServer(handle)- const result = await new HerdrApiClient(endpoint, { maxResponseBytes: 1_024 }).request(- 'pane.send_input',- { pane_id: 'w1:p1', text: 'hello', keys: ['Enter'] },- { mutation: 'single_enqueue' },- )- expect(result).toMatchObject({ ok: false, dispatch: 'possibly_executed' })- }- })-- it('rejects oversized requests before connecting', async () => {- let requests = 0- const { endpoint } = await socketServer((_request, socket) => { requests++; socket.end() })- const result = await new HerdrApiClient(endpoint, { maxRequestBytes: 256 }).request(- 'pane.send_input',- { pane_id: 'w1:p1', text: 'x'.repeat(512), keys: ['Enter'] },- { mutation: 'single_enqueue' },- )- expect(result).toMatchObject({ ok: false, dispatch: 'not_started' })- expect(requests).toBe(0)- })-- /**- * Skipped when the suite itself runs as root (common in a container). `checkedSocket` rejects a- * root-OWNED directory that is group-writable — `(stat.uid === 0 && permissions & 0o020)` — because- * under root ownership the group bit really does let another account plant a socket. The rule is- * correct; it is this case's premise ("the owner is a normal account") that does not hold as root.- * Same precedent as the getuid()===0 guard in lib/fsBrowse.spec.ts.- */- it.skipIf(isRoot)('accepts an owner-owned 0775 socket parent under the local account-owner trust model', async () => {- const root = await tempDir()- const parent = join(root, 'herdr')- await mkdir(parent, { mode: 0o775 })- await chmod(parent, 0o775)- const socketPath = join(parent, 'herdr.sock')- const server = createServer()- servers.push(server)- await new Promise<void>((resolve) => server.listen(socketPath, resolve))- await chmod(socketPath, 0o600)-- await expect(resolveHerdrEndpoint({ sessionName: 'shared-group', socketPath })).resolves.toMatchObject({- sessionName: 'shared-group', socketPath,- })- })-- it('rejects symlinked, permissive, and changed endpoint artifacts', async () => {- const { endpoint, socketPath } = await socketServer((request, socket) => {- socket.end(`${JSON.stringify({ id: request.id, result: { type: 'ok' } })}\n`)- })- const linkPath = join(await tempDir(), 'linked.sock')- await symlink(socketPath, linkPath)- await expect(resolveHerdrEndpoint({ sessionName: 'linked', socketPath: linkPath }))- .rejects.toBeInstanceOf(HerdrEndpointError)-- await chmod(socketPath, 0o666)- await expect(resolveHerdrEndpoint({ sessionName: 'permissive', socketPath }))- .rejects.toBeInstanceOf(HerdrEndpointError)- await chmod(socketPath, 0o600)-- const parent = join(await tempDir(), 'unsafe')- await mkdir(parent, { mode: 0o777 })- await chmod(parent, 0o777)- const unsafeSocket = join(parent, 'herdr.sock')- const unsafeServer = createServer()- servers.push(unsafeServer)- await new Promise<void>((resolve) => unsafeServer.listen(unsafeSocket, resolve))- await chmod(unsafeSocket, 0o600)- await expect(resolveHerdrEndpoint({ sessionName: 'unsafe', socketPath: unsafeSocket }))- .rejects.toBeInstanceOf(HerdrEndpointError)-- const before = await lstat(socketPath)- expect(endpoint.generation).toEqual({ device: before.dev, inode: before.ino })- })-- it('pins the generated v0.8 schema and live protocol tuple', () => {- expect(HERDR_API_PROTOCOL).toBe(19)- expect(HERDR_API_SCHEMA_VERSION).toBe(1)- })-})diff --git a/cli/src/lib/herdrApiClient.ts b/cli/src/lib/herdrApiClient.tsdeleted file mode 100644index ab4b2783d..000000000--- a/cli/src/lib/herdrApiClient.ts+++ /dev/null@@ -1,303 +0,0 @@-import { createHash, randomUUID } from 'node:crypto'-import { lstat, realpath } from 'node:fs/promises'-import { createConnection, type Socket } from 'node:net'-import { dirname, isAbsolute, parse, resolve, sep } from 'node:path'--export const HERDR_API_PROTOCOL = 19-export const HERDR_API_SCHEMA_VERSION = 1-export const HERDR_API_MAX_REQUEST_BYTES = 1024 * 1024-export const HERDR_API_MAX_RESPONSE_BYTES = 1024 * 1024--const HERDR_VERSION_RE = /^0\.8\.\d+(?:[-+].*)?$/-const SESSION_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/--export interface HerdrEndpointGeneration {- device: number- inode: number-}--export interface HerdrEndpoint {- sessionName: string- endpointId: string- socketPath: string- generation: HerdrEndpointGeneration-}--export type HerdrMutationKind = 'none' | 'single_enqueue' | 'single_key' | 'multi_enqueue' | 'other'--export type HerdrApiResult<T> =- | { ok: true; result: T }- | {- ok: false- dispatch: 'not_started' | 'rejected' | 'possibly_executed'- code?: string- reason: string- }--export interface HerdrPong {- type: 'pong'- version: string- protocol: number- capabilities?: {- live_handoff: boolean- detached_server_daemon: boolean- } | null-}--export interface HerdrApiClientOptions {- timeoutMs?: number- maxRequestBytes?: number- maxResponseBytes?: number-}--export interface HerdrRequestOptions {- mutation?: HerdrMutationKind- signal?: AbortSignal-}--export class HerdrEndpointError extends Error {- constructor(public readonly code: string) {- super(`Herdr endpoint rejected (${code})`)- this.name = 'HerdrEndpointError'- }-}--function mode(value: number): number {- return value & 0o7777-}--function pathComponents(path: string): string[] {- const root = parse(path).root- const relative = path.slice(root.length)- const components = relative.split(sep).filter(Boolean)- const paths = [root]- for (const component of components) paths.push(resolve(paths.at(-1)!, component))- return paths-}--async function checkedSocket(socketPath: string): Promise<HerdrEndpointGeneration> {- if (!isAbsolute(socketPath)) throw new HerdrEndpointError('path_not_absolute')- const uid = typeof process.getuid === 'function' ? process.getuid() : null- if (uid === null) throw new HerdrEndpointError('uid_unavailable')-- const parent = dirname(socketPath)- for (const path of pathComponents(parent)) {- let stat- try { stat = await lstat(path) } catch { throw new HerdrEndpointError('directory_unavailable') }- if (!stat.isDirectory() || stat.isSymbolicLink()) throw new HerdrEndpointError('unsafe_directory_type')- if (stat.uid !== uid && stat.uid !== 0) throw new HerdrEndpointError('unsafe_directory_owner')- const permissions = mode(stat.mode)- if ((permissions & 0o002) !== 0 || (stat.uid === 0 && (permissions & 0o020) !== 0)) {- throw new HerdrEndpointError('unsafe_directory_mode')- }- }-- let parentStat- try { parentStat = await lstat(parent) } catch { throw new HerdrEndpointError('parent_unavailable') }- if (parentStat.uid !== uid) throw new HerdrEndpointError('unsafe_parent_owner')-- let socketStat- try { socketStat = await lstat(socketPath) } catch { throw new HerdrEndpointError('socket_unavailable') }- if (!socketStat.isSocket() || socketStat.isSymbolicLink()) throw new HerdrEndpointError('unsafe_socket_type')- if (socketStat.uid !== uid) throw new HerdrEndpointError('unsafe_socket_owner')- if (mode(socketStat.mode) !== 0o600) throw new HerdrEndpointError('unsafe_socket_mode')-- let canonical- try { canonical = await realpath(socketPath) } catch { throw new HerdrEndpointError('socket_unavailable') }- if (canonical !== resolve(socketPath)) throw new HerdrEndpointError('socket_not_canonical')- return { device: socketStat.dev, inode: socketStat.ino }-}--export async function resolveHerdrEndpoint(input: {- sessionName: string- socketPath: string-}): Promise<HerdrEndpoint> {- if (!SESSION_NAME_RE.test(input.sessionName)) throw new HerdrEndpointError('invalid_session_name')- const generation = await checkedSocket(input.socketPath)- const socketPath = await realpath(input.socketPath)- const endpointId = createHash('sha256')- .update('herdr\0')- .update(input.sessionName)- .update('\0')- .update(socketPath)- .digest('hex')- .slice(0, 16)- return { sessionName: input.sessionName, endpointId, socketPath, generation }-}--async function endpointGenerationMatches(endpoint: HerdrEndpoint): Promise<boolean> {- try {- const current = await checkedSocket(endpoint.socketPath)- return current.device === endpoint.generation.device && current.inode === endpoint.generation.inode- } catch {- return false- }-}--function failure(- dispatch: 'not_started' | 'rejected' | 'possibly_executed',- reason: string,- code?: string,-): HerdrApiResult<never> {- return { ok: false, dispatch, reason, ...(code ? { code } : {}) }-}--function structuredErrorDispatch(code: string, mutation: HerdrMutationKind): 'rejected' | 'possibly_executed' {- if (mutation === 'none') return 'rejected'- if (code === 'invalid_request' || code === 'invalid_params' || code === 'pane_not_found' || code === 'invalid_key') {- return 'rejected'- }- if (code === 'pane_send_failed' && (mutation === 'single_enqueue' || mutation === 'single_key')) {- return 'rejected'- }- return 'possibly_executed'-}--function socketFailure(writeAttempted: boolean, reason: string): HerdrApiResult<never> {- return failure(writeAttempted ? 'possibly_executed' : 'not_started', reason)-}--function safeObject(value: unknown): value is Record<string, unknown> {- return !!value && typeof value === 'object' && !Array.isArray(value)-}--export class HerdrApiClient {- private readonly timeoutMs: number- private readonly maxRequestBytes: number- private readonly maxResponseBytes: number-- constructor(- readonly endpoint: HerdrEndpoint,- options: HerdrApiClientOptions = {},- ) {- this.timeoutMs = Math.max(50, Math.min(10_000, options.timeoutMs ?? 2_000))- this.maxRequestBytes = Math.max(128, Math.min(HERDR_API_MAX_REQUEST_BYTES, options.maxRequestBytes ?? HERDR_API_MAX_REQUEST_BYTES))- this.maxResponseBytes = Math.max(128, Math.min(HERDR_API_MAX_RESPONSE_BYTES, options.maxResponseBytes ?? HERDR_API_MAX_RESPONSE_BYTES))- }-- async ping(signal?: AbortSignal): Promise<HerdrApiResult<HerdrPong>> {- const response = await this.request<HerdrPong>('ping', {}, { mutation: 'none', signal })- if (!response.ok) return response- const pong = response.result- const capabilities = pong.capabilities- if (- pong.type !== 'pong'- || !HERDR_VERSION_RE.test(pong.version)- || pong.protocol !== HERDR_API_PROTOCOL- || (capabilities != null && (- typeof capabilities.live_handoff !== 'boolean'- || typeof capabilities.detached_server_daemon !== 'boolean'- ))- ) {- return failure('rejected', 'Herdr API protocol is incompatible', 'protocol_mismatch')- }- return response- }-- async request<T = unknown>(- method: string,- params: Record<string, unknown>,- options: HerdrRequestOptions = {},- ): Promise<HerdrApiResult<T>> {- const mutation = options.mutation ?? 'none'- if (options.signal?.aborted) return failure('not_started', 'Herdr API request was aborted')-- const id = randomUUID()- let frame: Buffer- try {- frame = Buffer.from(`${JSON.stringify({ id, method, params })}\n`, 'utf8')- } catch {- return failure('not_started', 'Herdr API request could not be serialized')- }- if (frame.byteLength > this.maxRequestBytes) {- return failure('not_started', 'Herdr API request exceeds the size limit')- }- if (!(await endpointGenerationMatches(this.endpoint))) {- return failure('not_started', 'Herdr endpoint is unavailable or changed')- }-- return new Promise<HerdrApiResult<T>>((resolveResult) => {- let socket: Socket | null = null- let writeAttempted = false- let settled = false- let response = Buffer.alloc(0)-- const finish = (result: HerdrApiResult<T>): void => {- if (settled) return- settled = true- clearTimeout(timer)- options.signal?.removeEventListener('abort', onAbort)- socket?.destroy()- resolveResult(result)- }- const onAbort = (): void => finish(socketFailure(writeAttempted, 'Herdr API request was aborted'))- const timer = setTimeout(() => finish(socketFailure(writeAttempted, 'Herdr API request timed out')), this.timeoutMs)- options.signal?.addEventListener('abort', onAbort, { once: true })-- try {- socket = createConnection({ path: this.endpoint.socketPath })- } catch {- finish(failure('not_started', 'Herdr API connection could not be created'))- return- }-- socket.once('connect', () => {- void endpointGenerationMatches(this.endpoint).then((matches) => {- if (settled) return- if (!matches) {- finish(failure('not_started', 'Herdr endpoint changed before dispatch'))- return- }- writeAttempted = true- try {- socket!.end(frame)- } catch {- finish(failure('possibly_executed', 'Herdr API request write failed'))- }- })- })- socket.on('data', (chunk: Buffer) => {- if (settled) return- response = Buffer.concat([response, chunk])- if (response.byteLength > this.maxResponseBytes) {- finish(socketFailure(writeAttempted, 'Herdr API response exceeds the size limit'))- return- }- const newline = response.indexOf(0x0a)- if (newline < 0) return- if (response.subarray(newline + 1).toString('utf8').trim() !== '') {- finish(socketFailure(writeAttempted, 'Herdr API returned multiple responses'))- return- }- let parsed: unknown- try { parsed = JSON.parse(response.subarray(0, newline).toString('utf8')) } catch {- finish(socketFailure(writeAttempted, 'Herdr API returned malformed JSON'))- return- }- if (!safeObject(parsed) || parsed.id !== id) {- finish(socketFailure(writeAttempted, 'Herdr API response correlation failed'))- return- }- if ('error' in parsed) {- const body = parsed.error- if (!safeObject(body) || typeof body.code !== 'string') {- finish(socketFailure(writeAttempted, 'Herdr API returned a malformed error'))- return- }- const dispatch = structuredErrorDispatch(body.code, mutation)- finish(failure(dispatch, `Herdr API request failed (${body.code})`, body.code))- return- }- if (!('result' in parsed)) {- finish(socketFailure(writeAttempted, 'Herdr API response is missing a result'))- return- }- finish({ ok: true, result: parsed.result as T })- })- socket.once('end', () => {- if (!settled) finish(socketFailure(writeAttempted, 'Herdr API response ended early'))- })- socket.once('error', () => finish(socketFailure(writeAttempted, 'Herdr API transport failed')))- })- }-}diff --git a/cli/src/lib/herdrBackend.real.spec.ts b/cli/src/lib/herdrBackend.real.spec.tsdeleted file mode 100644index 4ee20d6ba..000000000--- a/cli/src/lib/herdrBackend.real.spec.ts+++ /dev/null@@ -1,518 +0,0 @@-import { execFile, spawn, spawnSync, type ChildProcess } from 'node:child_process'-import { access, readFile, rm } from 'node:fs/promises'-import { tmpdir } from 'node:os'-import { dirname, join, resolve } from 'node:path'-import { promisify } from 'node:util'-import { afterAll, beforeAll, describe, expect, it } from 'vitest'-import type { AgentEngine } from '../engines/types.js'-import {- agentCommandOwnershipSnapshot,- ENGINE_CLI_COMMANDS,- ENGINES,- installedEngineBin,-} from './engineBin.js'-import {- HERDR_API_PROTOCOL,- HERDR_API_SCHEMA_VERSION,- HerdrApiClient,- resolveHerdrEndpoint,- type HerdrApiResult,- type HerdrEndpoint,-} from './herdrApiClient.js'-import { HerdrBackend } from './herdrBackend.js'-import { probeTerminalAgents } from './terminalAgentDiscovery.js'-import { terminalRouteKey } from './terminalRuntime.js'-import type { HerdrRuntimeRef } from './terminalTypes.js'-import { probeTmuxAgents } from './tmuxAgentDiscovery.js'--const exec = promisify(execFile)-const herdrBin = process.env.HERDR_BIN || 'herdr'-const enabled = process.env.RUN_REAL_HERDR === '1'-const installed = spawnSync(herdrBin, ['--version'], { encoding: 'utf8' }).status === 0-if (enabled && !installed) console.warn(`[herdr-real] skipped: ${herdrBin} is not installed`)-const realDescribe = enabled && installed ? describe : describe.skip--interface SessionListRow {- name: string- running: boolean- session_dir: string- socket_path: string-}--interface PaneInfo {- pane_id: string- terminal_id: string- workspace_id: string- tab_id: string- cwd?: string- title?: string- terminal_title?: string- terminal_title_stripped?: string-}--interface PaneProcessInfo {- pane_id: string- shell_pid?: number- foreground_processes?: Array<{ pid: number; name: string; argv?: string[]; cmdline?: string }>-}--interface SessionFixture {- name: string- child: ChildProcess- row: SessionListRow- endpoint: HerdrEndpoint- client: HerdrApiClient-}--const runId = `ah-u1-${process.pid}-${Date.now().toString(36)}`-const sessionNames = [`${runId}-a`, `${runId}-b`]-const sessions: SessionFixture[] = []-const tmuxSessions = new Set<string>()-const fixtureDir = join(tmpdir(), runId)-const ptyFixture = resolve(dirname(new URL(import.meta.url).pathname), '__fixtures__/herdr/pty-capture.mjs')-const ownership = agentCommandOwnershipSnapshot()-const engines: Array<[AgentEngine, string, string | null]> = ENGINES.map((engine) => [- engine,- ENGINE_CLI_COMMANDS[engine],- installedEngineBin(engine, ownership),-])--function minimalEnv(): NodeJS.ProcessEnv {- return Object.fromEntries(Object.entries({- HOME: process.env.HOME,- PATH: process.env.PATH,- LANG: process.env.LANG || 'C.UTF-8',- TERM: 'xterm-256color',- XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,- XDG_DATA_HOME: process.env.XDG_DATA_HOME,- }).filter((entry): entry is [string, string] => typeof entry[1] === 'string'))-}--async function eventually<T>(read: () => Promise<T | null>, timeoutMs = 10_000): Promise<T> {- const deadline = Date.now() + timeoutMs- let lastError: unknown- while (Date.now() < deadline) {- try {- const value = await read()- if (value !== null) return value- } catch (error) { lastError = error }- await new Promise((resolvePromise) => setTimeout(resolvePromise, 50))- }- throw lastError ?? new Error('timed out waiting for real Herdr state')-}--async function sessionList(): Promise<SessionListRow[]> {- const result = await exec(herdrBin, ['session', 'list', '--json'], {- timeout: 2_000,- maxBuffer: 512 * 1024,- env: minimalEnv(),- })- const parsed = JSON.parse(result.stdout) as { sessions?: SessionListRow[] }- return Array.isArray(parsed.sessions) ? parsed.sessions : []-}--async function startSession(name: string): Promise<SessionFixture> {- const child = spawn(herdrBin, ['--session', name, 'server'], {- env: minimalEnv(),- stdio: ['ignore', 'pipe', 'pipe'],- })- let diagnostics = ''- child.stdout?.on('data', (chunk) => { diagnostics += String(chunk).slice(0, 4_096) })- child.stderr?.on('data', (chunk) => { diagnostics += String(chunk).slice(0, 4_096) })- const row = await eventually(async () => {- if (child.exitCode !== null) throw new Error(`Herdr test server exited ${child.exitCode}: ${diagnostics}`)- return (await sessionList()).find((candidate) => candidate.name === name && candidate.running) ?? null- })- const endpoint = await resolveHerdrEndpoint({ sessionName: name, socketPath: row.socket_path })- const client = new HerdrApiClient(endpoint, { timeoutMs: 2_000 })- const ping = await client.ping()- if (!ping.ok) throw new Error(`Herdr test server ping failed: ${ping.reason}`)- const fixture = { name, child, row, endpoint, client }- sessions.push(fixture)- return fixture-}--async function call<T>(- client: HerdrApiClient,- method: string,- params: Record<string, unknown> = {},- mutation: 'none' | 'single_enqueue' | 'single_key' | 'multi_enqueue' | 'other' = 'none',-): Promise<T> {- const result = await client.request<T>(method, params, { mutation })- if (!result.ok) throw new Error(`${method} failed: ${result.code ?? result.dispatch}`)- return result.result-}--async function createWorkspace(fixture: SessionFixture, label: string): Promise<PaneInfo> {- const result = await call<{ type: 'workspace_created'; root_pane: PaneInfo }>(- fixture.client,- 'workspace.create',- { cwd: process.cwd(), focus: false, label, env: {} },- 'other',- )- return result.root_pane-}--async function panes(fixture: SessionFixture): Promise<PaneInfo[]> {- return (await call<{ type: 'pane_list'; panes: PaneInfo[] }>(fixture.client, 'pane.list')).panes-}--async function processInfo(fixture: SessionFixture, paneId: string): Promise<PaneProcessInfo> {- return (await call<{ type: 'pane_process_info'; process_info: PaneProcessInfo }>(- fixture.client,- 'pane.process_info',- { pane_id: paneId },- )).process_info-}--async function stopSession(fixture: SessionFixture): Promise<void> {- await exec(herdrBin, ['--session', fixture.name, 'server', 'stop'], {- timeout: 3_000,- env: minimalEnv(),- }).catch(() => {})- if (fixture.child.exitCode === null) fixture.child.kill('SIGTERM')- await new Promise<void>((resolvePromise) => {- if (fixture.child.exitCode !== null) { resolvePromise(); return }- const timer = setTimeout(() => { fixture.child.kill('SIGKILL'); resolvePromise() }, 2_000)- fixture.child.once('exit', () => { clearTimeout(timer); resolvePromise() })- })- await exec(herdrBin, ['session', 'delete', fixture.name], {- timeout: 3_000,- env: minimalEnv(),- }).catch(() => {})-}--async function waitForFile(path: string): Promise<void> {- await eventually(async () => access(path).then(() => true).catch(() => null), 10_000)-}--function shellQuote(value: string): string {- return `'${value.replaceAll("'", `'\\''`)}'`-}--async function captureSubmission(- fixture: SessionFixture,- runtime: HerdrRuntimeRef,- name: string,- payload: string,-): Promise<Buffer> {- const output = join(fixtureDir, `${name}.json`)- const ready = join(fixtureDir, `${name}.ready`)- await rm(output, { force: true })- await rm(ready, { force: true })- const command = `node ${shellQuote(ptyFixture)} ${shellQuote(output)} ${shellQuote(ready)}`- await call(fixture.client, 'pane.send_input', {- pane_id: runtime.paneId,- text: command,- keys: ['Enter'],- }, 'single_enqueue')- try {- await waitForFile(ready)- } catch (error) {- const capture = await fixture.client.request<{ type: 'pane_read'; read: { text: string } }>('pane.read', {- pane_id: runtime.paneId,- source: 'recent_unwrapped',- lines: 30,- format: 'text',- strip_ansi: true,- })- throw new Error(`PTY fixture did not become ready: ${capture.ok ? capture.result.read.text : capture.reason}`, { cause: error })- }- await new Promise((resolvePromise) => setTimeout(resolvePromise, 100))- const submitted = await new HerdrBackend(fixture.endpoint).submitText(runtime, payload)- expect(submitted).toEqual({ state: 'succeeded', dispatch: 'executed' })- await waitForFile(output)- const result = JSON.parse(await readFile(output, 'utf8')) as {- base64: string- bracketedStarts: number- bracketedEnds: number- carriageReturnsAfterPaste: number- }- expect(result.bracketedStarts).toBe(1)- expect(result.bracketedEnds).toBe(1)- expect(result.carriageReturnsAfterPaste).toBe(1)- return Buffer.from(result.base64, 'base64')-}--realDescribe.sequential('real Herdr 0.8 socket backend', () => {- let first: SessionFixture- let second: SessionFixture- let firstPane: PaneInfo- let secondPane: PaneInfo-- const runtime = (fixture: SessionFixture, pane: PaneInfo): HerdrRuntimeRef => ({- backend: 'herdr',- endpointId: fixture.endpoint.endpointId,- sessionName: fixture.name,- terminalId: pane.terminal_id,- paneId: pane.pane_id,- })-- beforeAll(async () => {- await exec('mkdir', ['-p', fixtureDir])- first = await startSession(sessionNames[0])- second = await startSession(sessionNames[1])- }, 20_000)-- afterAll(async () => {- for (const name of tmuxSessions) {- await exec('tmux', ['kill-session', '-t', name], { timeout: 2_000 }).catch(() => {})- }- await Promise.all([...sessions].reverse().map(stopSession))- await rm(fixtureDir, { recursive: true, force: true })- }, 20_000)-- it('negotiates protocol/schema and distinguishes successful empty inventory', async () => {- const schema = await exec(herdrBin, ['api', 'schema', '--json'], {- timeout: 3_000,- maxBuffer: 2 * 1024 * 1024,- env: minimalEnv(),- })- const generated = JSON.parse(schema.stdout) as { protocol: number; schema_version: number }- expect(generated).toMatchObject({ protocol: HERDR_API_PROTOCOL, schema_version: HERDR_API_SCHEMA_VERSION })- await expect(panes(first)).resolves.toEqual([])- await expect(panes(second)).resolves.toEqual([])- })-- it('namespaces duplicate routes and exposes stable endpoint-scoped identity', async () => {- firstPane = await createWorkspace(first, 'harness-u1-a')- secondPane = await createWorkspace(second, 'harness-u1-b')- expect(firstPane.pane_id).toBe('w1:p1')- expect(secondPane.pane_id).toBe('w1:p1')- expect(first.endpoint.endpointId).not.toBe(second.endpoint.endpointId)- expect(firstPane.terminal_id).not.toBe(secondPane.terminal_id)- const [a, b] = await Promise.all([- processInfo(first, firstPane.pane_id),- processInfo(second, secondPane.pane_id),- ])- expect(a.shell_pid).toBeGreaterThan(1)- expect(b.shell_pid).toBeGreaterThan(1)- expect(a.shell_pid).not.toBe(b.shell_pid)- expect(firstPane.cwd).toBe(process.cwd())- const inventory = await new HerdrBackend(first.endpoint).inventory()- expect(inventory.state).toBe('available')- if (inventory.state === 'available') {- expect(inventory.roots.some((root) => root.runtime.backend === 'herdr'- && root.runtime.terminalId === firstPane.terminal_id && root.rootPid === a.shell_pid)).toBe(true)- }- })-- it('creates, notifies, and closes a test-owned workspace through the shared backend contract', async () => {- const backend = new HerdrBackend(first.endpoint)- const created = await backend.create({ cwd: process.cwd(), label: 'harness-lifecycle' })- expect(created.state).toBe('succeeded')- if (created.state !== 'succeeded') return- await expect(backend.notify(created.runtime, 'Harness test', 'Lifecycle message'))- .resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })- await expect(backend.kill(created.runtime))- .resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })- await expect(eventually(async () => (await panes(first)).some(- (pane) => pane.terminal_id === created.runtime.terminalId,- ) ? null : true)).resolves.toBe(true)- })-- it('types literally, presses logical keys, and captures ANSI without implicit focus', async () => {- const backend = new HerdrBackend(first.endpoint)- const current = runtime(first, firstPane)- const marker = join(fixtureDir, 'literal-executed')- await expect(backend.typeLiteral(current, `touch ${shellQuote(marker)}`)).resolves.toEqual({- state: 'succeeded', dispatch: 'executed',- })- await new Promise((resolvePromise) => setTimeout(resolvePromise, 200))- await expect(access(marker)).rejects.toBeTruthy()- await expect(backend.sendKey(current, 'enter')).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })- await waitForFile(marker)-- await call(first.client, 'pane.send_input', {- pane_id: firstPane.pane_id,- text: `printf '\\033[31mHERDR_ANSI_CAPTURE\\033[0m\\n'; printf '\\033]0;HERDR_U1_TITLE\\007'`,- keys: ['Enter'],- }, 'single_enqueue')- const read = await eventually(async () => {- const result = await backend.capture(current, { mode: 'recent_unwrapped', historyLines: 100, ansi: true })- return result.state === 'succeeded' && result.value.includes('HERDR_ANSI_CAPTURE') ? result.value : null- })- expect(read).toMatch(/\u001b\[[0-9;]*mHERDR_ANSI_CAPTURE\u001b\[0m/)- const titled = await eventually(async () => {- const result = await call<{ type: 'pane_info'; pane: PaneInfo }>(first.client, 'pane.get', { pane_id: firstPane.pane_id })- return result.pane.terminal_title_stripped === 'HERDR_U1_TITLE' ? result.pane : null- })- expect(titled.terminal_title_stripped).toBe('HERDR_U1_TITLE')- await expect(backend.setTitle(current, 'Harness Herdr title')).resolves.toEqual({- state: 'succeeded', dispatch: 'executed',- })- const titles = await backend.titles()- expect(titles.state).toBe('succeeded')- if (titles.state === 'succeeded') expect(titles.value.get(terminalRouteKey(current))).toBe('Harness Herdr title')- })-- for (const [engine, bin, path] of engines) {- if (!path) console.warn(`[herdr-real] unavailable matrix row: ${engine} (${bin} has no verified installed executable)`)- const matrixIt = path ? it : it.skip- matrixIt(`discovers ${engine} once and process-only deletion preserves its terminal`, async () => {- const pane = await createWorkspace(first, `matrix-${engine}`)- const current = runtime(first, pane)- const backend = new HerdrBackend(first.endpoint)- await expect(backend.submitText(current, shellQuote(path!))).resolves.toEqual({- state: 'succeeded', dispatch: 'executed',- })-- const discovered = await eventually(async () => {- const result = await probeTerminalAgents([backend], ['herdr'], [first.name], -1)- const inPane = result.agents.filter((candidate) => candidate.runtimes.some(- (candidateRuntime) => terminalRouteKey(candidateRuntime) === terminalRouteKey(current),- ))- return inPane.length === 1 && inPane[0].engine === engine ? inPane[0] : null- }, 20_000)- const capture = await backend.capture(current, { mode: 'recent_unwrapped', historyLines: 30, ansi: false })- expect(discovered, `${bin} was not discovered in ${current.paneId}\n${capture.state === 'succeeded' ? capture.value : capture.reason}`).not.toBeNull()-- const pid = discovered.processIdentity.pid- process.kill(pid, 'SIGTERM')- const gone = await eventually(async () => {- try { process.kill(pid, 0) } catch { return true }- return null- }, 2_000).catch(() => false)- if (!gone) {- try { process.kill(pid, 'SIGKILL') } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error- }- }-- const absent = await eventually(async () => {- const result = await probeTerminalAgents([backend], ['herdr'], [first.name], -1)- return result.agents.some((candidate) => candidate.processIdentity.pid === pid) ? null : true- }, 5_000)- expect(absent, `${bin} remained discoverable after its exact saved PID was terminated`).toBe(true)- const paneAfterDelete = await first.client.request<{ type: 'pane_info'; pane: PaneInfo }>(- 'pane.get', { pane_id: current.paneId },- )- expect(paneAfterDelete.ok).toBe(true)- if (paneAfterDelete.ok) expect(paneAfterDelete.result.pane.terminal_id).toBe(current.terminalId)- }, 35_000)- }-- it.each([- ['short', 'u1 short input'],- ['multiline', 'line one\nline two\nline three\nline four'],- ['long', '0123456789abcdef'.repeat(1_792)],- ])('submits %s text byte-for-byte exactly once through one API request', async (name, payload) => {- const bytes = await captureSubmission(first, runtime(first, firstPane), name, payload)- expect(bytes).toEqual(Buffer.from(`\u001b[200~${payload}\u001b[201~\r`))- expect(Buffer.byteLength(payload)).toBe(name === 'long' ? 28_672 : Buffer.byteLength(payload))-- const processArgs = (await exec('ps', ['-axo', 'args='], { timeout: 2_000 })).stdout- expect(processArgs).not.toContain(payload)- const serverLog = join(first.row.session_dir, 'herdr-server.log')- const log = await readFile(serverLog, 'utf8').catch(() => '')- expect(log).not.toContain(payload)- }, 20_000)-- it('preserves terminal identity across a workspace move and records alias behavior', async () => {- const before = firstPane- const moved = await call<{ type: 'pane_move'; move_result: { pane: PaneInfo; previous_pane_id: string } }>(- first.client,- 'pane.move',- {- pane_id: before.pane_id,- destination: { type: 'new_workspace', label: 'harness-u1-moved', tab_label: 'harness-u1-moved' },- focus: false,- },- 'other',- )- firstPane = moved.move_result.pane- expect(firstPane.pane_id).not.toBe(before.pane_id)- expect(firstPane.terminal_id).toBe(before.terminal_id)- expect((await processInfo(first, firstPane.pane_id)).shell_pid).toBeGreaterThan(1)-- const oldRouteImmediately = await first.client.request<{ type: 'pane_info'; pane: PaneInfo }>(- 'pane.get', { pane_id: before.pane_id },- )- await new Promise((resolvePromise) => setTimeout(resolvePromise, 10_000))- const oldRouteAfterTenSeconds = await first.client.request<{ type: 'pane_info'; pane: PaneInfo }>(- 'pane.get', { pane_id: before.pane_id },- )- console.log('[herdr-real] route alias', JSON.stringify({- immediate: oldRouteImmediately.ok,- afterTenSeconds: oldRouteAfterTenSeconds.ok,- oldRoute: before.pane_id,- currentRoute: firstPane.pane_id,- }))- expect(oldRouteImmediately.ok).toBe(true)- }, 20_000)-- it('keeps the direct inventory/process probe below half the 5s reconcile interval', async () => {- const samples: Record<string, number[]> = { '1': [], '10': [], '50': [] }- let count = (await panes(second)).length- for (const target of [1, 10, 50]) {- while (count < target) {- await createWorkspace(second, `bench-${count + 1}`)- count++- }- for (let sample = 0; sample < 10; sample++) {- const started = performance.now()- const listed = await panes(second)- await Promise.all(listed.map((pane) => processInfo(second, pane.pane_id)))- samples[String(target)].push(performance.now() - started)- }- }- const p95 = Object.fromEntries(Object.entries(samples).map(([key, values]) => {- const ordered = values.toSorted((a, b) => a - b)- return [key, ordered[Math.ceil(ordered.length * 0.95) - 1]]- })) as Record<string, number>- const safeMinimumMs = Math.max(250, Math.ceil((Math.max(...Object.values(p95)) * 2) / 50) * 50)- console.log('[herdr-real] reconcile benchmark', JSON.stringify({ p95Ms: p95, safeMinimumMs }))- expect(p95['50']).toBeLessThan(2_500)- }, 60_000)-- it('classifies stopped transport as unavailable rather than an empty snapshot', async () => {- const isolated = await startSession(`${runId}-availability`)- await expect(panes(isolated)).resolves.toEqual([])- await stopSession(isolated)- sessions.splice(sessions.indexOf(isolated), 1)- const unavailable: HerdrApiResult<unknown> = await isolated.client.request('pane.list', {})- expect(unavailable).toMatchObject({ ok: false, dispatch: 'not_started' })- })-- it('observes both real nested multiplexer topologies without duplicate engine ownership', async () => {- const amp = (await exec('/bin/sh', ['-lc', 'command -v amp'], { timeout: 2_000 })).stdout.trim()- expect(amp).not.toBe('')-- const innerTmux = `${runId}-tmux-in-herdr`- tmuxSessions.add(innerTmux)- await call(first.client, 'pane.send_input', {- pane_id: firstPane.pane_id,- text: `tmux new-session -d -s ${shellQuote(innerTmux)} ${shellQuote(amp)}`,- keys: ['Enter'],- }, 'single_enqueue')- const tmuxAgent = await eventually(async () => {- const result = await probeTmuxAgents()- if (!result.ok) return null- return result.agents.find((agent) => agent.engine === 'amp' && agent.processIdentity.pid > 0) ?? null- }, 20_000)- const outerHerdr = await processInfo(first, firstPane.pane_id)- expect(outerHerdr.foreground_processes?.some((process) => process.pid === tmuxAgent.processIdentity.pid)).toBe(false)-- const outerTmux = `${runId}-herdr-in-tmux`- tmuxSessions.add(outerTmux)- await exec('tmux', ['new-session', '-d', '-s', outerTmux], { timeout: 5_000 })- const outerPane = (await exec('tmux', ['list-panes', '-t', outerTmux, '-F', '#{pane_id}'], { timeout: 2_000 })).stdout.trim()- await exec('tmux', ['send-keys', '-t', outerPane, '-l', '--', `${herdrBin} --session ${second.name}`], { timeout: 2_000 })- await exec('tmux', ['send-keys', '-t', outerPane, 'Enter'], { timeout: 2_000 })- await call(second.client, 'pane.send_input', {- pane_id: secondPane.pane_id,- text: shellQuote(amp),- keys: ['Enter'],- }, 'single_enqueue')- const herdrAmp = await eventually(async () => {- const info = await processInfo(second, secondPane.pane_id)- return info.foreground_processes?.find((process) => process.name === 'amp') ?? null- }, 20_000)- const observed = await probeTmuxAgents()- expect(observed.ok && observed.agents.some((agent) => agent.tmuxPane === outerPane && agent.processIdentity.pid === herdrAmp.pid)).toBe(false)- console.log('[herdr-real] nested topology', JSON.stringify({- tmuxInsideHerdr: { enginePid: tmuxAgent.processIdentity.pid, locators: ['tmux'] },- herdrInsideTmux: { enginePid: herdrAmp.pid, locators: ['herdr'] },- }))- }, 45_000)-})diff --git a/cli/src/lib/herdrBackend.spec.ts b/cli/src/lib/herdrBackend.spec.tsdeleted file mode 100644index 37d1dd73d..000000000--- a/cli/src/lib/herdrBackend.spec.ts+++ /dev/null@@ -1,138 +0,0 @@-import { describe, expect, it, vi } from 'vitest'-import { HerdrBackend } from './herdrBackend.js'-import type { HerdrApiClient, HerdrEndpoint } from './herdrApiClient.js'-import { terminalRouteKey } from './terminalRuntime.js'-import type { HerdrRuntimeRef } from './terminalTypes.js'--const endpoint: HerdrEndpoint = {- sessionName: 'default',- endpointId: 'endpoint-a',- socketPath: '/configured/herdr.sock',- generation: { device: 1, inode: 2 },-}-const runtime: HerdrRuntimeRef = {- backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',-}--function backendWith(request: unknown, ping: unknown = vi.fn(async () => ({- ok: true as const,- result: { type: 'pong' as const, version: '0.8.0', protocol: 19 },-}))): HerdrBackend {- return new HerdrBackend(endpoint, { request, ping, endpoint } as HerdrApiClient)-}--describe('HerdrBackend', () => {- it('reads endpoint-scoped pane labels and terminal titles from the API snapshot', async () => {- const backend = backendWith(vi.fn(async () => ({- ok: true as const,- result: {- type: 'session_snapshot',- snapshot: {- version: '0.8.0', protocol: 19, panes: [- { pane_id: 'w1:p1', terminal_id: 'terminal-a', label: 'manual label', terminal_title_stripped: 'shell title' },- { pane_id: 'w1:p2', terminal_id: 'terminal-b', terminal_title_stripped: 'terminal title' },- ],- },- },- })))- const result = await backend.titles()- expect(result.state).toBe('succeeded')- if (result.state !== 'succeeded') return- expect([...result.value.values()]).toEqual(['manual label', 'terminal title'])- expect([...result.value.keys()]).toEqual([- terminalRouteKey(runtime),- terminalRouteKey({ ...runtime, terminalId: 'terminal-b', paneId: 'w1:p2' }),- ])- })-- it('distinguishes a successful empty snapshot from unavailable transport', async () => {- const empty = backendWith(vi.fn(async () => ({- ok: true as const,- result: { type: 'session_snapshot', snapshot: { version: '0.8.0', protocol: 19, panes: [] } },- })))- expect(await empty.inventory()).toEqual({ state: 'available', roots: [] })-- const unavailable = backendWith(vi.fn(), vi.fn(async () => ({- ok: false as const, dispatch: 'not_started' as const, reason: 'Herdr API unavailable',- })))- expect(await unavailable.inventory()).toEqual({ state: 'unavailable', reason: 'Herdr API unavailable' })- })-- it('builds endpoint-scoped roots from snapshot and pane process info', async () => {- const request = vi.fn(async (method: string) => method === 'session.snapshot'- ? { ok: true as const, result: { type: 'session_snapshot', snapshot: { version: '0.8.0', protocol: 19, panes: [{ pane_id: 'w1:p1', terminal_id: 'terminal-a', cwd: '/work' }] } } }- : { ok: true as const, result: { type: 'pane_process_info', process_info: { pane_id: 'w1:p1', shell_pid: 42 } } })- expect(await backendWith(request).inventory()).toEqual({- state: 'available',- roots: [{ runtime, rootPid: 42, cwd: '/work' }],- })- })-- it('submits stripped multiline text once and preserves ambiguous dispatch evidence', async () => {- const request = vi.fn(async () => ({- ok: false as const,- dispatch: 'possibly_executed' as const,- reason: 'Herdr API response ended early',- }))- const result = await backendWith(request).submitText(runtime, 'one\ntwo\n\n')- expect(request).toHaveBeenCalledOnce()- expect(request).toHaveBeenCalledWith('pane.send_input', {- pane_id: 'w1:p1', text: 'one\ntwo', keys: ['Enter'],- }, { mutation: 'single_enqueue' })- expect(result).toEqual({- state: 'unknown', dispatch: 'possibly_executed', reason: 'Herdr API response ended early',- })- })-- it('uses explicit pane routes for capture and logical keys', async () => {- const request = vi.fn(async (method: string) => method === 'pane.read'- ? { ok: true as const, result: { type: 'pane_read', read: { text: '\u001b[31mred\u001b[0m' } } }- : { ok: true as const, result: { type: 'ok' } })- const backend = backendWith(request)- await expect(backend.capture(runtime, { historyLines: 60 })).resolves.toEqual({ state: 'succeeded', value: '\u001b[31mred\u001b[0m' })- await expect(backend.sendKey(runtime, 'ctrl-c')).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })- expect(request).toHaveBeenLastCalledWith('pane.send_keys', { pane_id: 'w1:p1', keys: ['Ctrl+C'] }, { mutation: 'single_key' })- })-- it('creates a workspace and closes the workspace resolved from its root pane', async () => {- const request = vi.fn(async (method: string) => {- if (method === 'workspace.create') {- return {- ok: true as const,- result: {- type: 'workspace_created',- root_pane: { pane_id: 'w2:p1', terminal_id: 'terminal-created', workspace_id: 'workspace-created' },- },- }- }- if (method === 'pane.get') {- return {- ok: true as const,- result: {- type: 'pane_info',- pane: { pane_id: 'w2:p1', terminal_id: 'terminal-created', workspace_id: 'workspace-created' },- },- }- }- return { ok: true as const, result: { type: 'ok' } }- })- const backend = backendWith(request)-- const created = await backend.create({ cwd: '/tmp/work', label: 'Harness test' })- expect(created).toEqual({- state: 'succeeded',- dispatch: 'executed',- runtime: {- backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default',- terminalId: 'terminal-created', paneId: 'w2:p1',- },- })- if (created.state !== 'succeeded') return- await expect(backend.kill(created.runtime)).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })- expect(request.mock.calls).toEqual([- ['workspace.create', { cwd: '/tmp/work', focus: false, label: 'Harness test', env: {} }, { mutation: 'other' }],- ['pane.get', { pane_id: 'w2:p1' }],- ['workspace.close', { workspace_id: 'workspace-created' }, { mutation: 'other' }],- ])- })-})diff --git a/cli/src/lib/herdrBackend.ts b/cli/src/lib/herdrBackend.tsdeleted file mode 100644index ae6250cf7..000000000--- a/cli/src/lib/herdrBackend.ts+++ /dev/null@@ -1,322 +0,0 @@-import type { TerminalBackend } from './terminalBackend.js'-import { HerdrApiClient, type HerdrApiResult, type HerdrEndpoint } from './herdrApiClient.js'-import {- TERMINAL_ACTION_SUCCEEDED,- terminalActionNotStarted,- terminalActionPossiblyExecuted,- terminalActionRejected,- type HerdrRuntimeRef,- type RuntimeValidation,- type TerminalActionResult,- type TerminalCaptureOptions,- type TerminalCreateRequest,- type TerminalCreateResult,- type TerminalInventoryResult,- type TerminalLogicalKey,- type TerminalProcessExpectation,- type TerminalReadResult,-} from './terminalTypes.js'-import { engineProcessMatchScore, enrichProcessRows, processRows } from './tmux.js'-import { terminalRouteKey } from './terminalRuntime.js'--interface HerdrPaneInfo {- pane_id: string- terminal_id: string- workspace_id?: string- cwd?: string- label?: string- title?: string- terminal_title_stripped?: string-}--interface HerdrSessionSnapshotResult {- type: 'session_snapshot'- snapshot: {- version: string- protocol: number- panes: HerdrPaneInfo[]- }-}--interface HerdrPaneProcessInfoResult {- type: 'pane_process_info'- process_info: {- pane_id: string- shell_pid?: number- }-}--interface HerdrPaneReadResult {- type: 'pane_read'- read: { text: string }-}--interface HerdrPaneInfoResult {- type: 'pane_info'- pane: HerdrPaneInfo-}--interface HerdrWorkspaceCreatedResult {- type: 'workspace_created'- root_pane: HerdrPaneInfo-}--const HERDR_KEYS: Record<TerminalLogicalKey, string> = {- enter: 'Enter',- escape: 'Escape',- tab: 'Tab',- backtab: 'BackTab',- up: 'Up',- down: 'Down',- left: 'Left',- right: 'Right',- home: 'Home',- end: 'End',- backspace: 'Backspace',- delete: 'Delete',- pageup: 'PageUp',- pagedown: 'PageDown',- 'ctrl-c': 'Ctrl+C',- 'ctrl-d': 'Ctrl+D',- 'ctrl-u': 'Ctrl+U',- 'ctrl-w': 'Ctrl+W',- space: 'Space',- '0': '0',- '1': '1',- '2': '2',- '3': '3',- '4': '4',- '5': '5',- '6': '6',- '7': '7',- '8': '8',- '9': '9',-}--function actionResult(result: HerdrApiResult<unknown>): TerminalActionResult {- if (result.ok) return TERMINAL_ACTION_SUCCEEDED- if (result.dispatch === 'not_started') return terminalActionNotStarted(result.reason)- if (result.dispatch === 'rejected') return terminalActionRejected(result.reason)- return terminalActionPossiblyExecuted(result.reason)-}--function runtimeFor(endpoint: HerdrEndpoint, pane: HerdrPaneInfo): HerdrRuntimeRef {- return {- backend: 'herdr',- endpointId: endpoint.endpointId,- sessionName: endpoint.sessionName,- terminalId: pane.terminal_id,- paneId: pane.pane_id,- }-}--function paneTitle(pane: HerdrPaneInfo): string | null {- for (const candidate of [pane.label, pane.terminal_title_stripped, pane.title]) {- if (typeof candidate === 'string' && candidate.trim()) return candidate- }- return null-}--export class HerdrBackend implements TerminalBackend<HerdrRuntimeRef> {- readonly name = 'herdr' as const- readonly instanceId: string- readonly client: HerdrApiClient-- constructor(- readonly endpoint: HerdrEndpoint,- client = new HerdrApiClient(endpoint),- ) {- this.instanceId = `herdr:${endpoint.endpointId}`- this.client = client- }-- async create(request: TerminalCreateRequest): Promise<TerminalCreateResult<HerdrRuntimeRef>> {- const result = await this.client.request<HerdrWorkspaceCreatedResult>('workspace.create', {- ...(request.cwd ? { cwd: request.cwd } : {}),- focus: false,- ...(request.label ? { label: request.label } : {}),- env: request.env ?? {},- }, { mutation: 'other' })- if (!result.ok) {- if (result.dispatch === 'not_started') return terminalActionNotStarted(result.reason)- if (result.dispatch === 'rejected') return terminalActionRejected(result.reason)- return terminalActionPossiblyExecuted(result.reason)- }- if (result.result.type !== 'workspace_created'- || typeof result.result.root_pane?.pane_id !== 'string'- || typeof result.result.root_pane?.terminal_id !== 'string') {- return terminalActionPossiblyExecuted('Herdr created a workspace without returning its root pane')- }- return {- state: 'succeeded',- dispatch: 'executed',- runtime: runtimeFor(this.endpoint, result.result.root_pane),- }- }-- async kill(runtime: HerdrRuntimeRef): Promise<TerminalActionResult> {- if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')- const info = await this.client.request<HerdrPaneInfoResult>('pane.get', { pane_id: runtime.paneId })- if (!info.ok- || info.result.type !== 'pane_info'- || info.result.pane?.terminal_id !== runtime.terminalId- || typeof info.result.pane.workspace_id !== 'string') {- return terminalActionNotStarted('Herdr workspace could not be resolved from terminal runtime')- }- return actionResult(await this.client.request('workspace.close', {- workspace_id: info.result.pane.workspace_id,- }, { mutation: 'other' }))- }-- async titles(): Promise<TerminalReadResult<Map<string, string>>> {- const snapshot = await this.client.request<HerdrSessionSnapshotResult>('session.snapshot', {})- if (!snapshot.ok) return { state: 'failed', reason: snapshot.reason }- if (snapshot.result.type !== 'session_snapshot' || !Array.isArray(snapshot.result.snapshot?.panes)) {- return { state: 'failed', reason: 'Herdr session snapshot has an incompatible shape' }- }- const titles = new Map<string, string>()- for (const pane of snapshot.result.snapshot.panes) {- if (!pane || typeof pane.pane_id !== 'string' || typeof pane.terminal_id !== 'string') continue- const title = paneTitle(pane)- if (title) titles.set(terminalRouteKey(runtimeFor(this.endpoint, pane)), title)- }- return { state: 'succeeded', value: titles }- }-- private owns(runtime: HerdrRuntimeRef): boolean {- return runtime.endpointId === this.endpoint.endpointId && runtime.sessionName === this.endpoint.sessionName- }-- async inventory(): Promise<TerminalInventoryResult> {- const ping = await this.client.ping()- if (!ping.ok) {- return ping.code === 'protocol_mismatch'- ? { state: 'incompatible', reason: ping.reason }- : { state: 'unavailable', reason: ping.reason }- }- const snapshot = await this.client.request<HerdrSessionSnapshotResult>('session.snapshot', {})- if (!snapshot.ok) return { state: 'unavailable', reason: snapshot.reason }- if (snapshot.result.type !== 'session_snapshot' || !Array.isArray(snapshot.result.snapshot?.panes)) {- return { state: 'incompatible', reason: 'Herdr session snapshot has an incompatible shape' }- }- const roots = await Promise.all(snapshot.result.snapshot.panes.map(async (pane) => {- if (!pane || typeof pane.pane_id !== 'string' || typeof pane.terminal_id !== 'string') return null- const info = await this.client.request<HerdrPaneProcessInfoResult>('pane.process_info', { pane_id: pane.pane_id })- if (!info.ok- || info.result.type !== 'pane_process_info'- || !Number.isSafeInteger(info.result.process_info?.shell_pid)- || info.result.process_info.shell_pid! <= 0) return null- return {- runtime: runtimeFor(this.endpoint, pane),- rootPid: info.result.process_info.shell_pid!,- cwd: typeof pane.cwd === 'string' ? pane.cwd : '',- }- }))- if (roots.some((root) => root === null)) {- return { state: 'unavailable', reason: 'Herdr pane process inventory failed' }- }- return { state: 'available', roots: roots.filter((root) => root !== null) }- }-- async resolveRuntimeHint(paneId: string): Promise<TerminalReadResult<HerdrRuntimeRef>> {- const info = await this.client.request<HerdrPaneInfoResult>('pane.get', { pane_id: paneId })- if (!info.ok || info.result.type !== 'pane_info' || typeof info.result.pane?.terminal_id !== 'string') {- return { state: 'failed', reason: info.ok ? 'Herdr pane response is incompatible' : info.reason }- }- return { state: 'succeeded', value: runtimeFor(this.endpoint, info.result.pane) }- }-- async validate(runtime: HerdrRuntimeRef, _expected: TerminalProcessExpectation): Promise<RuntimeValidation> {- if (!this.owns(runtime)) return { state: 'gone', reason: 'Herdr runtime belongs to another configured endpoint' }- const resolved = await this.resolveRuntimeHint(runtime.paneId)- if (resolved.state === 'failed') return { state: 'unknown', reason: resolved.reason }- if (resolved.value.terminalId !== runtime.terminalId) {- return { state: 'gone', reason: 'Herdr terminal identity changed under pane route' }- }- if (!_expected.processIdentity) return { state: 'alive' }- const [info, rows] = await Promise.all([- this.client.request<HerdrPaneProcessInfoResult>('pane.process_info', { pane_id: runtime.paneId }),- processRows(),- ])- if (!info.ok || !rows || info.result.type !== 'pane_process_info'- || !Number.isSafeInteger(info.result.process_info?.shell_pid)) {- return { state: 'unknown', reason: 'Herdr process identity could not be verified' }- }- const enrichedRows = await enrichProcessRows(rows, new Set([_expected.processIdentity.pid]))- const expected = enrichedRows.find((row) => row.pid === _expected.processIdentity!.pid)- if (!expected || expected.startMarker !== _expected.processIdentity.startMarker) {- return { state: 'gone', reason: 'Herdr engine process identity changed' }- }- if (engineProcessMatchScore(expected, _expected.engine) <= 0) {- return { state: 'gone', reason: 'Herdr process no longer matches the registered engine' }- }- const byPid = new Map(enrichedRows.map((row) => [row.pid, row]))- const rootPid = info.result.process_info.shell_pid!- let pid = expected.pid- const visited = new Set<number>()- while (pid > 0 && !visited.has(pid)) {- if (pid === rootPid) return { state: 'alive' }- visited.add(pid)- pid = byPid.get(pid)?.parentPid ?? 0- }- return { state: 'gone', reason: 'Herdr engine process is no longer under the terminal root' }- }-- async capture(runtime: HerdrRuntimeRef, options: TerminalCaptureOptions = {}): Promise<TerminalReadResult<string>> {- if (!this.owns(runtime)) return { state: 'failed', reason: 'Herdr runtime belongs to another configured endpoint' }- const result = await this.client.request<HerdrPaneReadResult>('pane.read', {- pane_id: runtime.paneId,- source: options.mode ?? 'recent_unwrapped',- lines: Math.max(20, Math.min(300, Math.floor(options.historyLines ?? 100))),- format: options.ansi === false ? 'text' : 'ansi',- strip_ansi: options.ansi === false,- })- if (!result.ok) return { state: 'failed', reason: result.reason }- if (result.result.type !== 'pane_read' || typeof result.result.read?.text !== 'string') {- return { state: 'failed', reason: 'Herdr pane capture has an incompatible shape' }- }- return { state: 'succeeded', value: result.result.read.text }- }-- async typeLiteral(runtime: HerdrRuntimeRef, text: string): Promise<TerminalActionResult> {- if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')- return actionResult(await this.client.request('pane.send_text', {- pane_id: runtime.paneId,- text,- }, { mutation: 'single_enqueue' }))- }-- async submitText(runtime: HerdrRuntimeRef, text: string): Promise<TerminalActionResult> {- if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')- return actionResult(await this.client.request('pane.send_input', {- pane_id: runtime.paneId,- text: text.replace(/[\r\n]+$/, ''),- keys: ['Enter'],- }, { mutation: 'single_enqueue' }))- }-- async sendKey(runtime: HerdrRuntimeRef, key: TerminalLogicalKey): Promise<TerminalActionResult> {- if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')- return actionResult(await this.client.request('pane.send_keys', {- pane_id: runtime.paneId,- keys: [HERDR_KEYS[key]],- }, { mutation: 'single_key' }))- }-- async setTitle(runtime: HerdrRuntimeRef, title: string): Promise<TerminalActionResult> {- if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')- return actionResult(await this.client.request('pane.rename', {- pane_id: runtime.paneId,- label: title.slice(0, 200),- }, { mutation: 'other' }))- }-- async notify(runtime: HerdrRuntimeRef, title: string, body: string): Promise<TerminalActionResult> {- if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')- return actionResult(await this.client.request('notification.show', {- title: title.slice(0, 200),- body: body.slice(0, 1_000),- sound: 'none',- }, { mutation: 'other' }))- }-}diff --git a/cli/src/lib/herdrSessions.spec.ts b/cli/src/lib/herdrSessions.spec.tsdeleted file mode 100644index 6839f54b4..000000000--- a/cli/src/lib/herdrSessions.spec.ts+++ /dev/null@@ -1,155 +0,0 @@-import { afterAll, describe, expect, it, vi } from 'vitest'-import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'-import { tmpdir } from 'node:os'-import { join } from 'node:path'-import {- discoverRunningHerdrSessions,- herdrBinaryAvailable,- herdrHintSelects,- parseHerdrSessionList,- resolveConfiguredHerdrSessions,-} from './herdrSessions.js'--const stubDirs: string[] = []-afterAll(() => { for (const dir of stubDirs) rmSync(dir, { recursive: true, force: true }) })--describe('configured Herdr session bootstrap', () => {- it('parses bounded session-list output without treating pane content as CLI data', () => {- expect(parseHerdrSessionList(JSON.stringify({ sessions: [{- name: 'default', running: true, session_dir: '/config/default', socket_path: '/config/default/herdr.sock',- }] }))).toEqual([{- name: 'default', running: true, session_dir: '/config/default', socket_path: '/config/default/herdr.sock',- }])- })-- it('reports configured targets independently and never falls back to an unconfigured session', async () => {- const result = await resolveConfiguredHerdrSessions(['default', 'work'], async () => [{- name: 'other', running: true, session_dir: '/other', socket_path: '/other/herdr.sock',- }])- expect(result).toEqual([- { state: 'unavailable', sessionName: 'default', reason: 'configured Herdr session is not running' },- { state: 'unavailable', sessionName: 'work', reason: 'configured Herdr session is not running' },- ])- })-- it('rejects configured aliases that resolve to the same canonical endpoint', async () => {- const result = await resolveConfiguredHerdrSessions(- ['default', 'alias'],- async () => [- { name: 'default', running: true, session_dir: '/safe', socket_path: '/safe/herdr.sock' },- { name: 'alias', running: true, session_dir: '/safe', socket_path: '/safe/herdr.sock' },- ],- async ({ sessionName, socketPath }) => ({- sessionName,- socketPath,- endpointId: `endpoint-${sessionName}`,- generation: { device: 1, inode: 2 },- }),- )- expect(result).toEqual([- {- state: 'unavailable', sessionName: 'default',- reason: 'configured Herdr sessions resolve to the same canonical endpoint',- },- {- state: 'unavailable', sessionName: 'alias',- reason: 'configured Herdr sessions resolve to the same canonical endpoint',- },- ])- })-- it('rejects malformed and oversized output', () => {- expect(() => parseHerdrSessionList('{"sessions":[{}]}')).toThrow('incompatible shape')- expect(() => parseHerdrSessionList('x'.repeat(512 * 1024 + 1))).toThrow('size limit')- })-})--describe('Herdr auto-discovery (no configuration)', () => {- const endpoint = async ({ sessionName, socketPath }: { sessionName: string; socketPath: string }) => ({- sessionName, socketPath, endpointId: `id:${socketPath}`, generation: { device: 1, inode: 1 },- })-- /**- * `discoverRunningHerdrSessions` short-circuits to [] unless the binary really exists, so passing the- * bare name `'herdr'` made these cases depend on whether the DEVELOPER happened to have Herdr- * installed. On this machine (`~/.local/bin/herdr`) they passed; on any clean one they returned [] —- * which the adoption case fails on and the two negative cases pass VACUOUSLY, proving nothing. Caught- * on Ubuntu; a fresh macOS behaves identically. Point them at an executable we create instead.- */- const herdrBin = (() => {- const dir = mkdtempSync(join(tmpdir(), 'herdr-bin-'))- stubDirs.push(dir)- const bin = join(dir, 'herdr')- writeFileSync(bin, '#!/bin/sh\nexit 0\n')- chmodSync(bin, 0o755)- return bin- })()-- it('adopts every RUNNING session, whatever it is called', async () => {- // The point of auto-detection: the user starts a session with a name we were never told about, and- // its panes are watched on the next pass. A stopped session is not a target.- const result = await discoverRunningHerdrSessions(- herdrBin,- async () => [- { name: 'scratch', running: true, session_dir: '/a', socket_path: '/a/herdr.sock' },- { name: 'default', running: true, session_dir: '/b', socket_path: '/b/herdr.sock' },- { name: 'stopped', running: false, session_dir: '/c', socket_path: '/c/herdr.sock' },- ],- endpoint,- )- expect(result.map((target) => [target.sessionName, target.state])).toEqual([- ['scratch', 'available'],- ['default', 'available'],- ])- })-- it('costs nothing on a machine without Herdr — no spawn, no targets', async () => {- const list = vi.fn()- await expect(discoverRunningHerdrSessions('herdr-does-not-exist-anywhere', list, endpoint)).resolves.toEqual([])- expect(list).not.toHaveBeenCalled()- expect(herdrBinaryAvailable('herdr-does-not-exist-anywhere')).toBe(false)- })-- it('stays quiet when an installed Herdr cannot answer', async () => {- // Installed but broken, or a build whose `session list --json` shape moved. Nobody asked for Herdr,- // so there is nothing to report and nothing to adopt — never a startup failure.- await expect(discoverRunningHerdrSessions(herdrBin, async () => { throw new Error('exit 1') }, endpoint))- .resolves.toEqual([])- await expect(discoverRunningHerdrSessions(herdrBin, async () => [], endpoint)).resolves.toEqual([])- })-- it('still refuses two discovered sessions that alias one endpoint', async () => {- // Discovery must not become a way around the alias rule the configured path enforces.- const result = await discoverRunningHerdrSessions(- herdrBin,- async () => [- { name: 'one', running: true, session_dir: '/same', socket_path: '/same/herdr.sock' },- { name: 'two', running: true, session_dir: '/same', socket_path: '/same/herdr.sock' },- ],- endpoint,- )- expect(result.every((target) => target.state === 'unavailable')).toBe(true)- })-})--describe('hook hint → endpoint selection', () => {- const endpoint = { sessionName: 'default', socketPath: '/config/default/herdr.sock' }-- it('matches on the socket path alone, because herdr 0.8.0 exports no HERDR_SESSION', () => {- // The pane env measured on 0.8.0: HERDR_PANE_ID, HERDR_SOCKET_PATH, HERDR_ENV, HERDR_TAB_ID,- // HERDR_WORKSPACE_ID. Requiring a session name rejected every real hook, so nothing ever bound —- // a resumed session opened blank and a turn typed in the pane emitted no frames.- expect(herdrHintSelects(endpoint, { socketPath: '/config/default/herdr.sock' })).toBe(true)- expect(herdrHintSelects(endpoint, { sessionName: 'default' })).toBe(true)- expect(herdrHintSelects(endpoint, { sessionName: 'default', socketPath: '/config/default/herdr.sock' })).toBe(true)- })-- it('refuses a hint that identifies nothing, or that disagrees', () => {- // A hint with no identifying field must never match "whatever backend is first" — that would let a- // pane in one session speak for an agent in another.- expect(herdrHintSelects(endpoint, {})).toBe(false)- expect(herdrHintSelects(endpoint, { sessionName: 'other' })).toBe(false)- expect(herdrHintSelects(endpoint, { socketPath: '/somewhere/else.sock' })).toBe(false)- expect(herdrHintSelects(endpoint, { sessionName: 'default', socketPath: '/somewhere/else.sock' })).toBe(false)- })-})diff --git a/cli/src/lib/herdrSessions.ts b/cli/src/lib/herdrSessions.tsdeleted file mode 100644index 939aac4b9..000000000--- a/cli/src/lib/herdrSessions.ts+++ /dev/null@@ -1,190 +0,0 @@-import { execFile } from 'node:child_process'-import { accessSync, constants, realpathSync } from 'node:fs'-import { delimiter, join } from 'node:path'-import { promisify } from 'node:util'-import { HerdrEndpointError, resolveHerdrEndpoint, type HerdrEndpoint } from './herdrApiClient.js'--const exec = promisify(execFile)-const MAX_LIST_BYTES = 512 * 1024--export interface HerdrSessionListRow {- name: string- running: boolean- session_dir: string- socket_path: string-}--export type HerdrTargetResolution =- | { state: 'available'; sessionName: string; endpoint: HerdrEndpoint }- | { state: 'unavailable'; sessionName: string; reason: string }--function validRow(value: unknown): value is HerdrSessionListRow {- if (!value || typeof value !== 'object') return false- const row = value as Partial<HerdrSessionListRow>- return typeof row.name === 'string'- && row.name.length <= 64- && typeof row.running === 'boolean'- && typeof row.session_dir === 'string'- && row.session_dir.length <= 4_096- && typeof row.socket_path === 'string'- && row.socket_path.length <= 4_096-}--export function parseHerdrSessionList(stdout: string): HerdrSessionListRow[] {- if (Buffer.byteLength(stdout) > MAX_LIST_BYTES) throw new Error('Herdr session list exceeds the size limit')- const parsed = JSON.parse(stdout) as { sessions?: unknown }- if (!Array.isArray(parsed.sessions) || !parsed.sessions.every(validRow)) {- throw new Error('Herdr session list has an incompatible shape')- }- return parsed.sessions-}--/** CLI bootstrap contains no prompt/session transcript content and is never used for pane control. */-export async function listInstalledHerdrSessions(herdrBin = 'herdr'): Promise<HerdrSessionListRow[]> {- const result = await exec(herdrBin, ['session', 'list', '--json'], {- timeout: 2_000,- maxBuffer: MAX_LIST_BYTES,- encoding: 'utf8',- })- return parseHerdrSessionList(result.stdout)-}--/**- * Does a hook's terminal hint identify THIS already-resolved endpoint?- *- * Measured on herdr 0.8.0: a pane's environment carries `HERDR_PANE_ID`, `HERDR_SOCKET_PATH`,- * `HERDR_ENV`, `HERDR_TAB_ID` and `HERDR_WORKSPACE_ID` — and **no `HERDR_SESSION`**. Matching a backend- * by session name alone therefore rejected every real Herdr hook (`no_matching_engine_process`, 37 times- * in one afternoon here), so no session ever bound: a resumed session showed a blank conversation and a- * turn typed in the pane produced no frames at all.- *- * The socket path is the better key anyway — it is what the endpoint IS, while the session name is a- * label for it. Both are accepted, whichever the running Herdr exports, and a field that is present but- * disagrees disqualifies the match.- *- * This only ever SELECTS among endpoints already validated at discovery: a hook cannot introduce a- * socket, only point at one we resolved ourselves. Symlinked paths are compared canonically so a hook- * reporting `~/.config/...` still matches an endpoint resolved through `/System/Volumes/Data/...`.- */-export function herdrHintSelects(- endpoint: Pick<HerdrEndpoint, 'sessionName' | 'socketPath'>,- hint: { sessionName?: string; socketPath?: string },-): boolean {- const wantsName = !!hint.sessionName- const wantsPath = !!hint.socketPath- if (!wantsName && !wantsPath) return false- if (wantsName && endpoint.sessionName !== hint.sessionName) return false- if (wantsPath && !samePath(endpoint.socketPath, hint.socketPath!)) return false- return true-}--function samePath(left: string, right: string): boolean {- if (left === right) return true- try { return realpathSync(left) === realpathSync(right) } catch { return false }-}--/**- * Is a Herdr binary visible to this user, without spawning anything?- *- * Auto-detection runs before every reconcile pass, and the overwhelmingly common machine has no Herdr- * at all — so the negative case must cost nothing. A PATH walk with `accessSync(X_OK)` is a handful of- * stat calls (the same technique `engineBin.commandCandidates` uses to resolve vendor CLIs); spawning- * `herdr session list` only to watch it fail with ENOENT twelve times a minute is not acceptable as a- * default. An absolute `HERDR_BIN` is checked directly.- */-export function herdrBinaryAvailable(herdrBin = 'herdr'): boolean {- const candidates = herdrBin.includes('/')- ? [herdrBin]- : (process.env.PATH ?? '').split(delimiter).filter(Boolean).map((entry) => join(entry, herdrBin))- for (const candidate of candidates) {- try {- accessSync(candidate, constants.X_OK)- return true- } catch { /* keep looking */ }- }- return false-}--/**- * Every Herdr session that is currently RUNNING, resolved the same way a configured one is.- *- * This is what "no configuration" means in practice: the names come from the user's own `herdr session- * list`, not from an env var they have to know about, so starting a session — with any name, at any- * time — makes its panes discoverable on the next pass. Nothing about the trust model changes: every- * endpoint still goes through `resolveHerdrEndpoint`'s canonical-path, owner, type, mode and- * socket-generation checks, and a hook-supplied socket path still never widens what is adopted here.- *- * Returns [] when Herdr is absent or reports nothing, which is the quiet path for a tmux-only machine.- */-export async function discoverRunningHerdrSessions(- herdrBin = 'herdr',- list: () => Promise<HerdrSessionListRow[]> = () => listInstalledHerdrSessions(herdrBin),- resolveEndpoint: typeof resolveHerdrEndpoint = resolveHerdrEndpoint,-): Promise<HerdrTargetResolution[]> {- if (!herdrBinaryAvailable(herdrBin)) return []- let rows: HerdrSessionListRow[]- try {- rows = await list()- } catch {- // Installed but unusable (a broken build, a version whose `session list --json` shape moved). Not an- // error the operator asked for, so it is simply nothing to adopt.- return []- }- const running = rows.filter((row) => row.running).map((row) => row.name)- if (!running.length) return []- return resolveConfiguredHerdrSessions(running, async () => rows, resolveEndpoint)-}--export async function resolveConfiguredHerdrSessions(- sessionNames: readonly string[],- list: () => Promise<HerdrSessionListRow[]> = listInstalledHerdrSessions,- resolveEndpoint: typeof resolveHerdrEndpoint = resolveHerdrEndpoint,-): Promise<HerdrTargetResolution[]> {- let rows: HerdrSessionListRow[]- try {- rows = await list()- } catch {- return sessionNames.map((sessionName) => ({- state: 'unavailable',- sessionName,- reason: 'Herdr session discovery failed',- }))- }-- const targets = await Promise.all(sessionNames.map(async (sessionName): Promise<HerdrTargetResolution> => {- const matches = rows.filter((row) => row.name === sessionName)- if (matches.length !== 1 || !matches[0].running) {- return { state: 'unavailable', sessionName, reason: 'configured Herdr session is not running' }- }- try {- return {- state: 'available',- sessionName,- endpoint: await resolveEndpoint({ sessionName, socketPath: matches[0].socket_path }),- }- } catch (error) {- return {- state: 'unavailable',- sessionName,- reason: error instanceof HerdrEndpointError- ? `configured Herdr endpoint failed validation (${error.code})`- : 'configured Herdr endpoint failed validation',- }- }- }))-- const canonicalPaths = new Map<string, number>()- for (const target of targets) {- if (target.state === 'available') {- canonicalPaths.set(target.endpoint.socketPath, (canonicalPaths.get(target.endpoint.socketPath) ?? 0) + 1)- }- }- return targets.map((target) => target.state === 'available'- && (canonicalPaths.get(target.endpoint.socketPath) ?? 0) > 1- ? {- state: 'unavailable',- sessionName: target.sessionName,- reason: 'configured Herdr sessions resolve to the same canonical endpoint',- }- : target)-}diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex 8edb462c6..1193f93d6 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -424,9 +424,8 @@ export const MachineRegister = async ({ directory, worktree, project }) => {const seen = new Set()const post = async (sessionID) => {const pane = process.env.TMUX_PANE- const herdrPane = process.env.HERDR_PANE_IDconst token = hookToken()- if ((!pane && !herdrPane) || !token || !sessionID || seen.has(sessionID)) return+ if (!pane || !token || !sessionID || seen.has(sessionID)) returnseen.add(sessionID)try {await fetch("http://127.0.0.1:${port}/api/hook/session-start", {@@ -441,7 +440,6 @@ export const MachineRegister = async ({ directory, worktree, project }) => {callerPid: process.pid,runtimeHints: [...(pane ? [{ backend: "tmux", paneId: pane }] : []),- ...(herdrPane ? [{ backend: "herdr", paneId: herdrPane, sessionName: process.env.HERDR_SESSION, socketPath: process.env.HERDR_SOCKET_PATH }] : []),],}),})@@ -727,10 +725,9 @@ export default function (pi: ExtensionAPI) {const register = async (ctx: any) => {const pane = process.env.TMUX_PANE;- const herdrPane = process.env.HERDR_PANE_ID;let token = "";try { token = readFileSync(${JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential'))}, "utf8").trim(); } catch {}- if ((!pane && !herdrPane) || !token) return;+ if (!pane || !token) return;// Pi knows the session file path immediately but only WRITES it once the first assistant message// lands. Sending a path that isn't on disk yet is rejected by the daemon (it validates the file),// so announce without one first and attach the real path on a later turn.@@ -753,7 +750,6 @@ export default function (pi: ExtensionAPI) {callerPid: process.pid,runtimeHints: [...(pane ? [{ backend: "tmux", paneId: pane }] : []),- ...(herdrPane ? [{ backend: "herdr", paneId: herdrPane, sessionName: process.env.HERDR_SESSION, socketPath: process.env.HERDR_SOCKET_PATH }] : []),],}),});@@ -841,8 +837,7 @@ const SESSIONS_DIR = ${JSON.stringify(sessionsDir)}export default function (amp: any) {const pane = process.env.TMUX_PANE- const herdrPane = process.env.HERDR_PANE_ID- if (!pane && !herdrPane) return+ if (!pane) return// NOT \`process.cwd()\`: Bun runs a plugin with the PLUGIN's directory as its cwd, so that reports// \`<project>/.amp/plugins\` (measured). \`PWD\` is inherited from the shell that launched plain Amp.@@ -896,7 +891,6 @@ export default function (amp: any) {callerPid: process.pid,runtimeHints: [...(pane ? [{ backend: 'tmux', paneId: pane }] : []),- ...(herdrPane ? [{ backend: 'herdr', paneId: herdrPane, sessionName: process.env.HERDR_SESSION, socketPath: process.env.HERDR_SOCKET_PATH }] : []),],}),})diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex d8558fc54..9a9daa116 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -377,66 +377,59 @@ describe('registry remote display names', () => {expect(registry.byAgent('after-reused-pid-lock')).toBeTruthy()})- it('deduplicates nested backends by process identity while scoping Herdr routes to endpoints', async () => {+ it('deduplicates nested panes by process identity', async () => {const { registry } = await loadRegistryModule()registry.load()const identity = processIdentity(700)- const tmux = registry.openProcessAgent({+ const outer = registry.openProcessAgent({agentId: 'nested-agent',engine: 'claude',tmuxPane: '%7',processIdentity: identity,})- const herdrRuntime = {- backend: 'herdr' as const,- endpointId: 'herdr:default:abc',- sessionName: 'default',- terminalId: 'terminal-a',- paneId: 'w1:p1',- }const nested = registry.openProcessAgent({engine: 'claude',- runtimes: [herdrRuntime],+ runtimes: [{ backend: 'tmux', paneId: '%8' }],processIdentity: identity,})const other = registry.openProcessAgent({- agentId: 'other-endpoint-agent',+ agentId: 'other-agent',engine: 'claude',- runtimes: [{ ...herdrRuntime, endpointId: 'herdr:work:def', sessionName: 'work', terminalId: 'terminal-b' }],+ runtimes: [{ backend: 'tmux', paneId: '%9' }],processIdentity: processIdentity(701),})- expect(nested?.entry.agentId).toBe(tmux?.entry.agentId)+ expect(nested?.entry.agentId).toBe(outer?.entry.agentId)expect(nested?.entry.runtimes).toHaveLength(2)- expect(other?.entry.agentId).toBe('other-endpoint-agent')+ expect(other?.entry.agentId).toBe('other-agent')expect(registry.list()).toHaveLength(2)})- it('persists Herdr-only rows without a legacy tmuxPane projection', async () => {+ it('drops runtimes a retired Herdr backend left on disk, and agents left with none', async () => {const { registry } = await loadRegistryModule()registry.load()- registry.openProcessAgent({- agentId: 'herdr-agent',- engine: 'codex',- runtimes: [{- backend: 'herdr',- endpointId: 'herdr:default:abc',- sessionName: 'default',- terminalId: 'terminal-1',- paneId: 'w1:p1',- }],- processIdentity: processIdentity(900),- })+ registry.openProcessAgent({ agentId: 'mixed', engine: 'claude', tmuxPane: '%40', processIdentity: processIdentity(940) })+ const [row] = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))+ const herdr = { backend: 'herdr', endpointId: 'herdr:default:abc', sessionName: 'default', terminalId: 'terminal-1', paneId: 'w1:p1' }+ const herdrKey = 'herdr\u0000herdr:default:abc\u0000w1:p1'+ const { tmuxPane: _pane, ...herdrOnly } = row+ writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([+ { ...row, runtimes: [...row.runtimes, herdr], primaryRuntimeKey: herdrKey },+ { ...herdrOnly, agentId: 'herdr-only', sessionId: '', processIdentity: null, runtimes: [herdr], primaryRuntimeKey: herdrKey },+ ]), { mode: 0o600 })- const [persisted] = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))- expect(persisted).not.toHaveProperty('tmuxPane')- expect(persisted).toMatchObject({- schemaVersion: 2,- agentId: 'herdr-agent',- runtimes: [{ backend: 'herdr', endpointId: 'herdr:default:abc', paneId: 'w1:p1' }],- })- registry.load()- expect(registry.byAgent('herdr-agent')?.runtimes[0]).toMatchObject({ backend: 'herdr', terminalId: 'terminal-1' })+ const { registry: reloaded } = await loadRegistryModule()+ reloaded.load()++ expect(reloaded.byAgent('mixed')?.runtimes).toEqual([{ backend: 'tmux', paneId: '%40' }])+ expect(reloaded.byAgent('mixed')?.primaryRuntimeKey).toBe('tmux\u0000%40')+ expect(reloaded.byAgent('herdr-only')).toBeUndefined()+ const persisted = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))+ expect(persisted.map((entry: { agentId: string }) => entry.agentId)).toEqual(['mixed'])+ expect(JSON.stringify(persisted)).not.toContain('herdr')+ // Still writable: nothing about the retired rows blocked the file.+ reloaded.openProcessAgent({ agentId: 'after', engine: 'claude', tmuxPane: '%41', processIdentity: processIdentity(941) })+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))).toHaveLength(2)})it('repairs a Codex parent registry entry overwritten with a child rollout', async () => {diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex d2efa08d6..832a22185 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -217,7 +217,7 @@ export interface RegisteredSession {/** Authoritative backend-neutral terminal placements for this one process-owned agent. */runtimes: TerminalRuntimeRef[]primaryRuntimeKey: string- /** Additive rollback/wire projection. Empty in memory and omitted on disk for Herdr-only agents. */+ /** Additive rollback/wire projection of the tmux runtime. */tmuxPane: stringsource: string | nulltitle: string | null@@ -465,12 +465,46 @@ function boundedIdentityPart(value: unknown, max = 200): value is string {export function validTerminalRuntime(value: unknown): value is TerminalRuntimeRef {if (!value || typeof value !== 'object') return falseconst runtime = value as Partial<TerminalRuntimeRef>- if (runtime.backend === 'tmux') return typeof runtime.paneId === 'string' && PANE_RE.test(runtime.paneId)- return runtime.backend === 'herdr'- && boundedIdentityPart(runtime.endpointId)- && boundedIdentityPart(runtime.sessionName, 100)- && boundedIdentityPart(runtime.terminalId)- && boundedIdentityPart(runtime.paneId)+ return runtime.backend === 'tmux' && typeof runtime.paneId === 'string' && PANE_RE.test(runtime.paneId)+}++function retiredRuntime(value: unknown): boolean {+ return !!value && typeof value === 'object' && (value as { backend?: unknown }).backend === 'herdr'+}++/**+ * Earlier builds could also place an agent in a Herdr pane. That backend is gone, so its runtimes are+ * dropped on read — the rest of the row is untouched, and a primary that named one falls to the first+ * remaining tmux route. Returns `null` for a row left with no terminal at all: nothing can reach it.+ * A row without a retired runtime is returned as is.+ */+function withoutRetiredRuntimes(value: unknown): unknown {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return value+ const row = value as Record<string, unknown>+ if (!Array.isArray(row.runtimes) || !row.runtimes.some(retiredRuntime)) return value+ const runtimes = row.runtimes.filter((runtime) => !retiredRuntime(runtime))+ const hasLegacyPane = typeof row.tmuxPane === 'string' && PANE_RE.test(row.tmuxPane)+ if (!runtimes.length && !hasLegacyPane) return null+ const { runtimes: _retired, ...rest } = row+ const cleaned: Record<string, unknown> = runtimes.length ? { ...rest, runtimes } : rest+ if (typeof row.primaryRuntimeKey === 'string' && row.primaryRuntimeKey.startsWith('herdr\u0000')) {+ const first = runtimes.find(validTerminalRuntime)+ cleaned.primaryRuntimeKey = first ? terminalRouteKey(first) : ''+ }+ // A v2 row always carries `runtimes`, even when only the legacy pane is left to fill it.+ if (!runtimes.length && Object.hasOwn(row, 'schemaVersion')) {+ const pane = { backend: 'tmux' as const, paneId: row.tmuxPane as string }+ cleaned.runtimes = [pane]+ cleaned.primaryRuntimeKey = terminalRouteKey(pane)+ }+ return cleaned+}++/** `withoutRetiredRuntimes` over a whole stored file, dropping the rows it empties. */+function withoutRetiredRows(stored: readonly unknown[]): { rows: unknown[]; dropped: number; changed: boolean } {+ const cleaned = stored.map(withoutRetiredRuntimes)+ const rows = cleaned.filter((row, i) => row !== null || stored[i] === null)+ return { rows, dropped: stored.length - rows.length, changed: cleaned.some((row, i) => row !== stored[i]) }}function normalizedRuntimes(raw: unknown, legacyTmuxPane?: unknown): TerminalRuntimeRef[] {@@ -491,7 +525,8 @@ function persistedRow(entry: RegisteredSession): RegisteredSession | Omit<Registreturn { ...row, runtimes: row.runtimes.map((runtime) => ({ ...runtime })) }}-export function strictPersistedRow(value: unknown): RegisteredSession | null {+export function strictPersistedRow(raw: unknown): RegisteredSession | null {+ const value = withoutRetiredRuntimes(raw)if (!value || typeof value !== 'object') return nullconst row = value as Partial<RegisteredSession>const runtimes = normalizedRuntimes(row.runtimes, row.tmuxPane)@@ -747,7 +782,7 @@ class Registry {* `sessionId` (`cancel`, `question_response`, `compact`, `session_get`) while everything else* addresses the agent. `resolve()` is the one lookup that accepts either. */private sessionIndex = new Map<string, string>()- /** backend-scoped route → agentId. Public Herdr pane ids are never indexed without endpointId. */+ /** backend-scoped route → agentId. */private runtimeIndex = new Map<string, string>()/** engine + PID start marker → agentId. This is authoritative across nested multiplexers. */private processIndex = new Map<string, string>()@@ -830,12 +865,14 @@ class Registry {const rebooted = bootChanged(savedBoot, bootId)writeBoot(bootId) // refresh the reference so a reboot is detected exactly once, even across same-boot restartstry {- const parsed = JSON.parse(readPrivateStateFile(FILE)) as unknown- if (!Array.isArray(parsed)) {+ const stored = JSON.parse(readPrivateStateFile(FILE)) as unknown+ if (!Array.isArray(stored)) {this.writeBlocked = trueconsole.error('[registry] registry root is not an array; refusing to overwrite it')return}+ const { rows: parsed, dropped, changed: strippedRetired } = withoutRetiredRows(stored)+ if (dropped) console.log(`[registry] dropped ${dropped} agent(s) that lived only in a retired Herdr terminal`)if (parsed.some(hasUnknownRowSchema)) {this.writeBlocked = trueconsole.error('[registry] registry contains an unknown row schema; refusing to overwrite it')@@ -859,10 +896,11 @@ class Registry {const id = rowId(row)if (id) this.persistedBaseline.set(id, rowFingerprint(row))}+ // The rollback copy is the file as found, retired runtimes and all — not the cleaned rows.if (arr.some((row) => row.schemaVersion !== 2)) {- atomicWriteJson(PRE_V2_BACKUP_FILE, arr, true)+ atomicWriteJson(PRE_V2_BACKUP_FILE, stored, true)}- let changed = false+ let changed = strippedRetiredif (rebooted) {this.rebooted = trueconsole.log(`[registry] machine rebooted since last run — ${arr.length} agent(s) kept with their process identity cleared (stale panes, restored on start)`)@@ -1990,8 +2028,9 @@ class Registry {}))const latestValues: unknown[] = (() => {if (!existsSync(FILE)) return []- const parsed = JSON.parse(readPrivateStateFile(FILE)) as unknown- if (!Array.isArray(parsed)) throw new Error('registry root changed to a non-array value')+ const stored = JSON.parse(readPrivateStateFile(FILE)) as unknown+ if (!Array.isArray(stored)) throw new Error('registry root changed to a non-array value')+ const parsed = withoutRetiredRows(stored).rowsif (parsed.some(hasUnknownRowSchema)) {throw new Error('registry contains an unknown row schema')}diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.tsindex 6829d7448..11717fc67 100644--- a/cli/src/lib/restoreAgents.spec.ts+++ b/cli/src/lib/restoreAgents.spec.ts@@ -210,14 +210,14 @@ describe('restoreAgents — which agents get a pane back', () => {expect(h.calls).toEqual([])})- it('skips herdr-only rows and failed launches, saying why', async () => {+ it('skips rows with no tmux pane and failed launches, saying why', async () => {const h = harness([- row({ agentId: 'herdr', runtimes: [{ backend: 'herdr', sessionName: 's', paneId: 'p' } as unknown as TerminalRuntimeRef] }),+ row({ agentId: 'paneless', runtimes: [{ backend: 'unknown', sessionName: 's', paneId: 'p' } as unknown as TerminalRuntimeRef] }),row({ agentId: 'broken', launch: { state: 'failed', error: 'START_TIMEOUT' } }),])const summary = await restoreAgents(h.deps)expect(summary.restored).toEqual([])- expect(summary.skipped.map((s) => s.agentId)).toEqual(['herdr', 'broken'])+ expect(summary.skipped.map((s) => s.agentId)).toEqual(['paneless', 'broken'])expect(h.paneCreates).toBe(0)})diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.tsindex 9cf238ef4..ce1e8e56e 100644--- a/cli/src/lib/stopAgentService.spec.ts+++ b/cli/src/lib/stopAgentService.spec.ts@@ -43,7 +43,7 @@ it('storage failure leaves the live process and registry untouched', async () =>it.each(['terminal', 'without tmux', 'failed process', 'failed tmux'] as const)('retains work when stopping %s', async mode => {stoppedAgents.beginResume(row.agentId)if (mode === 'terminal') Object.assign(row, { engine: 'terminal', sessionId: '', processIdentity: null })- if (mode === 'without tmux') { deps.tmuxBackend = null; row.runtimes = [{ backend: 'herdr', endpointId: 'fixture', paneId: '1' } as any] }+ if (mode === 'without tmux') { deps.tmuxBackend = null; row.runtimes = [{ backend: 'unknown', endpointId: 'fixture', paneId: '1' } as any] }if (mode === 'failed process') vi.mocked(terminateDeletedAgent).mockResolvedValue('failed')if (mode === 'failed tmux') vi.mocked(deps.tmuxBackend!.kill).mockResolvedValue({ state: 'unknown', dispatch: 'possibly_executed', reason: 'fixture' })const stopping = createStopAgentService(deps)(row.agentId)@@ -94,7 +94,7 @@ it.each(['process', 'pane'] as const)('a rejected %s check retains history, releit.each(['no backend', 'no tmux route'] as const)('cannot confirm stopping a shell with %s', async mode => {row.engine = 'terminal'if (mode === 'no backend') deps.tmuxBackend = null- else row.runtimes = [{ backend: 'herdr', endpointId: 'fixture', paneId: '1' } as any]+ else row.runtimes = [{ backend: 'unknown', endpointId: 'fixture', paneId: '1' } as any]await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('Could not confirm')expect(deps.forgetSession).not.toHaveBeenCalled()})@@ -129,7 +129,7 @@ it('only signals through the validated process deleter and does not erase a neweawait actions.checkRuntime(entry); actions.kill(77, 'SIGTERM'); await actions.sleep(1); actions.log('fixture stop')deps.stopJobs.set(row.agentId, Promise.resolve()); return 'terminated'})- row.runtimes.push({ backend: 'herdr', endpointId: 'fixture', paneId: '2' } as any)+ row.runtimes.push({ backend: 'unknown', endpointId: 'fixture', paneId: '2' } as any)await createStopAgentService(deps)(row.agentId)expect(signal).toHaveBeenCalledExactlyOnceWith(77, 'SIGTERM'); expect(deps.stopJobs.has(row.agentId)).toBe(true)expect(deps.tmuxBackend!.kill).toHaveBeenCalledExactlyOnceWith({ backend: 'tmux', paneId: '%44' })diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.tsindex b45906609..6ce7870db 100644--- a/cli/src/lib/stoppedAgents.spec.ts+++ b/cli/src/lib/stoppedAgents.spec.ts@@ -183,7 +183,7 @@ it('keeps readable archives discoverable beside corrupt, unsupported and mismatcit('persists a standalone shell and a runtime without the legacy tmux alias', async () => {const { saved, store } = await fixture()- store.save({ ...saved, engine: 'terminal', sessionId: '', tmuxPane: '', runtimes: [{ backend: 'herdr', endpointId: 'fixture', paneId: '1' } as any], primaryRuntimeKey: ['herdr', 'fixture', '1'].join('\0'), codexHome: null })+ store.save({ ...saved, engine: 'terminal', sessionId: '', tmuxPane: '', runtimes: [{ backend: 'unknown', endpointId: 'fixture', paneId: '1' } as any], primaryRuntimeKey: ['unknown', 'fixture', '1'].join('\0'), codexHome: null })const disk = JSON.parse(readFileSync(join(directory, 'stopped-agents', `${saved.agentId}.json`), 'utf8'))expect(disk.session).not.toHaveProperty('tmuxPane')expect(disk.session.sessionId).toBe('')diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.tsindex c209ddb62..b5b9c27cc 100644--- a/cli/src/lib/stoppedAgents.ts+++ b/cli/src/lib/stoppedAgents.ts@@ -68,7 +68,7 @@ export class StoppedAgentStore {defaultName: projectDisplayName(session),touchedAt: Date.now(),}- // Herdr-only snapshots omit the legacy alias just like registry persistence.+ // A snapshot without a tmux pane omits the legacy alias just like registry persistence.if (!snapshot.tmuxPane) delete (snapshot as Partial<RegisteredSession>).tmuxPaneatomicWriteJson(join(this.directory, `${session.agentId}.json`), { version: 1, session: snapshot })}diff --git a/cli/src/lib/terminalAgentDiscovery.codexHome.spec.ts b/cli/src/lib/terminalAgentDiscovery.codexHome.spec.tsindex bc36806d2..5b1ae8254 100644--- a/cli/src/lib/terminalAgentDiscovery.codexHome.spec.ts+++ b/cli/src/lib/terminalAgentDiscovery.codexHome.spec.ts@@ -52,7 +52,6 @@ describe('Codex profile on the live terminal discovery path', () => {const probe = await probeTerminalAgents([backendWith([{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }, { runtime: OTHER_RUNTIME, rootPid: 20, cwd: '/work' }])],['tmux'],- [],999,)const byEngine = Object.fromEntries(probe.agents.map((agent) => [agent.engine, agent.codexHome]))@@ -64,7 +63,7 @@ describe('Codex profile on the live terminal discovery path', () => {it('passes an unreadable probe through as undefined, so the registry keeps what it knew', async () => {processRows.mockResolvedValue([row(10, 1, 'bash'), row(30, 10, 'codex')])probeCodexHome.mockResolvedValue(undefined)- const probe = await probeTerminalAgents([backendWith([{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }])], ['tmux'], [], 999)+ const probe = await probeTerminalAgents([backendWith([{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }])], ['tmux'], 999)expect(probe.agents[0]).toHaveProperty('codexHome', undefined)})})diff --git a/cli/src/lib/terminalAgentDiscovery.gateway.spec.ts b/cli/src/lib/terminalAgentDiscovery.gateway.spec.tsindex 13a9d4289..bc724db6a 100644--- a/cli/src/lib/terminalAgentDiscovery.gateway.spec.ts+++ b/cli/src/lib/terminalAgentDiscovery.gateway.spec.ts@@ -29,11 +29,9 @@ const row = (pid: number, parentPid: number, executable: string, args = executab({ pid, parentPid, executable, startMarker: START, args })const TMUX_RUNTIME: TerminalRuntimeRef = { backend: 'tmux', paneId: '%1' }-const HERDR_RUNTIME: TerminalRuntimeRef = {- backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',-}+const SECOND_RUNTIME: TerminalRuntimeRef = { backend: 'tmux', paneId: '%2' }-function backendWith(name: 'tmux' | 'herdr', instanceId: string, roots: TerminalRootObservation[]): TerminalBackend {+function backendWith(name: 'tmux', instanceId: string, roots: TerminalRootObservation[]): TerminalBackend {return {name,instanceId,@@ -47,26 +45,27 @@ beforeEach(() => {})describe('gateway detection on the live terminal discovery path', () => {- it('marks an ori-launched engine under EITHER backend, from the process rather than the pane', async () => {+ it('marks an ori-launched engine in every pane, from the process rather than the pane', async () => {processRows.mockResolvedValue([row(10, 1, 'bash'), row(30, 10, 'claude'), // tmux pane %1- row(20, 1, 'bash'), row(40, 20, 'codex'), // herdr pane w1:p1+ row(20, 1, 'bash'), row(40, 20, 'codex'), // tmux pane %2])probeGatewayRuntime.mockResolvedValue({ kind: 'ori', apiKey: 'sk-or-v1-test' })const probe = await probeTerminalAgents([- backendWith('tmux', 'tmux', [{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }]),- backendWith('herdr', 'herdr:endpoint-a', [{ runtime: HERDR_RUNTIME, rootPid: 20, cwd: '/work' }]),+ backendWith('tmux', 'tmux', [+ { runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' },+ { runtime: SECOND_RUNTIME, rootPid: 20, cwd: '/work' },+ ]),],- ['tmux', 'herdr'],- ['default'],+ ['tmux'],999,)expect(probe.agents.map((agent) => agent.engine).sort()).toEqual(['claude', 'codex'])expect(probe.agents.every((agent) => agent.gateway === 'ori')).toBe(true)- // Probed by process identity + argv — never by which multiplexer owns the pane.+ // Probed by process identity + argv — never by which pane it is in.expect(probeGatewayRuntime).toHaveBeenCalledTimes(2)for (const [identity, args] of probeGatewayRuntime.mock.calls) {expect(identity).toMatchObject({ startMarker: START })@@ -79,13 +78,13 @@ describe('gateway detection on the live terminal discovery path', () => {const backends = [backendWith('tmux', 'tmux', [{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }])]probeGatewayRuntime.mockResolvedValue({ kind: null })- const vendor = await probeTerminalAgents(backends, ['tmux'], [], 999)+ const vendor = await probeTerminalAgents(backends, ['tmux'], 999)expect(vendor.agents[0].gateway).toBeNull()// `{ kind: null }` from a FAILED read is the same shape, so the reconciler's contract is what keeps// an agent from being downgraded: registry.updateProcessIdentity only writes a defined value.probeGatewayRuntime.mockResolvedValue({ kind: null })- const unreadable = await probeTerminalAgents(backends, ['tmux'], [], 999)+ const unreadable = await probeTerminalAgents(backends, ['tmux'], 999)expect(unreadable.agents[0].gateway).not.toBe('ori')})@@ -94,7 +93,6 @@ describe('gateway detection on the live terminal discovery path', () => {const probe = await probeTerminalAgents([backendWith('tmux', 'tmux', [{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }])],['tmux'],- [],999,)expect(probe.processTableAvailable).toBe(false)diff --git a/cli/src/lib/terminalAgentDiscovery.grid.spec.ts b/cli/src/lib/terminalAgentDiscovery.grid.spec.tsindex 22a67dce5..f2e40a3f6 100644--- a/cli/src/lib/terminalAgentDiscovery.grid.spec.ts+++ b/cli/src/lib/terminalAgentDiscovery.grid.spec.ts@@ -32,12 +32,10 @@ const row = (pid: number, parentPid: number, executable: string, args = executab({ pid, parentPid, executable, startMarker: START, args })const TMUX_RUNTIME: TerminalRuntimeRef = { backend: 'tmux', paneId: '%1' }-const HERDR_RUNTIME: TerminalRuntimeRef = {- backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',-}+const SECOND_RUNTIME: TerminalRuntimeRef = { backend: 'tmux', paneId: '%2' }const ASSIGNMENT = { baseUrl: 'https://grid.autonomous.ai/grid-3378218621364f16/relay', model: 'GLM-4.7-Flash' }-function backendWith(name: 'tmux' | 'herdr', instanceId: string, roots: TerminalRootObservation[]): TerminalBackend {+function backendWith(name: 'tmux', instanceId: string, roots: TerminalRootObservation[]): TerminalBackend {return {name,instanceId,@@ -53,7 +51,7 @@ beforeEach(() => {})describe('grid assignment on the live terminal discovery path', () => {- it('reports the grid under EITHER backend, from the process rather than the pane', async () => {+ it('reports the grid for every pane, from the process rather than the pane', async () => {processRows.mockResolvedValue([row(10, 1, 'bash'), row(30, 10, 'claude'),row(20, 1, 'bash'), row(40, 20, 'codex'),@@ -62,11 +60,12 @@ describe('grid assignment on the live terminal discovery path', () => {const probe = await probeTerminalAgents([- backendWith('tmux', 'tmux', [{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }]),- backendWith('herdr', 'herdr:endpoint-a', [{ runtime: HERDR_RUNTIME, rootPid: 20, cwd: '/work' }]),+ backendWith('tmux', 'tmux', [+ { runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' },+ { runtime: SECOND_RUNTIME, rootPid: 20, cwd: '/work' },+ ]),],- ['tmux', 'herdr'],- ['default'],+ ['tmux'],999,)@@ -84,7 +83,6 @@ describe('grid assignment on the live terminal discovery path', () => {const probe = await probeTerminalAgents([backendWith('tmux', 'tmux', [{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }])],['tmux'],- [],999,)expect(probe.agents[0].grid).toBeNull()@@ -95,7 +93,6 @@ describe('grid assignment on the live terminal discovery path', () => {const probe = await probeTerminalAgents([backendWith('tmux', 'tmux', [{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }])],['tmux'],- [],999,)expect(probe.processTableAvailable).toBe(false)diff --git a/cli/src/lib/terminalAgentDiscovery.spec.ts b/cli/src/lib/terminalAgentDiscovery.spec.tsindex af4ec2a19..2c3362a5a 100644--- a/cli/src/lib/terminalAgentDiscovery.spec.ts+++ b/cli/src/lib/terminalAgentDiscovery.spec.ts@@ -11,55 +11,29 @@ const claude = (pid: number, parentPid: number): ProcessRow => ({ pid, parentPidconst tmux: TerminalRootObservation = {runtime: { backend: 'tmux', paneId: '%1' }, rootPid: 10, cwd: '/work',}-const herdr: TerminalRootObservation = {- runtime: {- backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',- },- rootPid: 20,- cwd: '/work',+const nested: TerminalRootObservation = {+ runtime: { backend: 'tmux', paneId: '%2' }, rootPid: 20, cwd: '/work',}-describe('backend-neutral process discovery', () => {- it('deduplicates nested/coexisting roots by engine PID and start marker', () => {+describe('process discovery', () => {+ it('deduplicates nested roots by engine PID and start marker', () => {const result = discoverTerminalAgentsFromSnapshot(- [tmux, herdr],+ [tmux, nested],[shell(10, 1), shell(20, 10), claude(30, 20)],999,- ['tmux', 'herdr'],- ['default'],+ ['tmux'],)expect(result.agents).toHaveLength(1)expect(result.agents[0].runtimes).toHaveLength(2)- expect(result.agents[0].primaryRuntimeKey).toBe(terminalRouteKey(herdr.runtime))+ expect(result.agents[0].primaryRuntimeKey).toBe(terminalRouteKey(nested.runtime))})- it('keeps duplicate public Herdr routes distinct across endpoints', () => {- const second = {- ...herdr,- runtime: { ...herdr.runtime, endpointId: 'endpoint-b', sessionName: 'work', terminalId: 'terminal-b' },- rootPid: 40,- } as TerminalRootObservation+ it('chooses the nearest root as primary', () => {const result = discoverTerminalAgentsFromSnapshot(- [herdr, second],- [shell(20, 1), claude(30, 20), shell(40, 1), claude(50, 40)],- 999,- ['herdr'],- ['default', 'work'],- )- expect(result.agents).toHaveLength(2)- expect(result.agents.map((agent) => agent.primaryRuntimeKey)).toEqual([- terminalRouteKey(herdr.runtime),- terminalRouteKey(second.runtime),- ])- })-- it('chooses the nearest root before configured backend order', () => {- const result = discoverTerminalAgentsFromSnapshot(- [tmux, herdr],+ [tmux, nested],[shell(20, 1), shell(25, 20), shell(10, 25), claude(30, 10)],999,- ['tmux', 'herdr'],- ['default'],+ ['tmux'],)expect(result.agents[0].primaryRuntimeKey).toBe(terminalRouteKey(tmux.runtime))})diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.tsindex 5d864d360..018886197 100644--- a/cli/src/lib/terminalAgentDiscovery.ts+++ b/cli/src/lib/terminalAgentDiscovery.ts@@ -43,8 +43,8 @@ export interface DiscoveredTerminalAgent {* undefined = the probe could not read the process; the registry then keeps whatever it already knew,* rather than downgrading a gateway agent to a vendor one on one failed read.*- * Deliberately NOT a property of the terminal: the probe reads the engine's own env and argv, so a- * gateway launch is recognized identically under tmux and under Herdr.+ * Deliberately NOT a property of the terminal: the probe reads the engine's own env and argv, not+ * anything the pane says about itself.*/gateway?: 'ori' | null/**@@ -173,14 +173,9 @@ function rootOwner(}}-function runtimeRank(runtime: TerminalRuntimeRef, backendOrder: readonly string[], herdrSessionOrder: readonly string[]): number[] {+function runtimeRank(runtime: TerminalRuntimeRef, backendOrder: readonly string[]): number {const backend = backendOrder.indexOf(runtime.backend)- const session = runtime.backend === 'herdr' ? herdrSessionOrder.indexOf(runtime.sessionName) : 0- return [backend < 0 ? Number.MAX_SAFE_INTEGER : backend, session < 0 ? Number.MAX_SAFE_INTEGER : session]-}--function rankBefore(a: number[], b: number[]): boolean {- return a[0] < b[0] || (a[0] === b[0] && a[1] < b[1])+ return backend < 0 ? Number.MAX_SAFE_INTEGER : backend}/** Pure process-authoritative merge used by fixtures and the live coordinator. */@@ -189,7 +184,6 @@ export function discoverTerminalAgentsFromSnapshot(rows: readonly ProcessRow[],daemonPid: number,backendOrder: readonly string[],- herdrSessionOrder: readonly string[],hints: ReadonlyMap<string, AgentEngine> = new Map(),ownership = agentCommandOwnershipSnapshot(),): { agents: DiscoveredTerminalAgent[]; ambiguousPlacements: Set<string> } {@@ -218,10 +212,9 @@ export function discoverTerminalAgentsFromSnapshot(for (const observation of observations) byPlacement.set(terminalPlacementKey(observation.runtime), observation)const ordered = [...byPlacement.values()].sort((a, b) => {if (a.depth !== b.depth) return a.depth - b.depth- const ar = runtimeRank(a.runtime, backendOrder, herdrSessionOrder)- const br = runtimeRank(b.runtime, backendOrder, herdrSessionOrder)- if (rankBefore(ar, br)) return -1- if (rankBefore(br, ar)) return 1+ const ar = runtimeRank(a.runtime, backendOrder)+ const br = runtimeRank(b.runtime, backendOrder)+ if (ar !== br) return ar - brreturn terminalPlacementKey(a.runtime).localeCompare(terminalPlacementKey(b.runtime))})return {@@ -238,7 +231,6 @@ export function discoverTerminalAgentsFromSnapshot(export async function probeTerminalAgents(backends: readonly TerminalBackend[],backendOrder: readonly string[],- herdrSessionOrder: readonly string[],daemonPid = process.pid,hints: ReadonlyMap<string, AgentEngine> = new Map(),): Promise<TerminalAgentProbe> {@@ -257,7 +249,6 @@ export async function probeTerminalAgents(enrichedRows,daemonPid,backendOrder,- herdrSessionOrder,hints,)// Which endpoint each agent's engine talks to. Cached per live process, so this is one read per agentdiff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.tsindex 4c63134c0..de65d5ef1 100644--- a/cli/src/lib/terminalAgentReconciler.spec.ts+++ b/cli/src/lib/terminalAgentReconciler.spec.ts@@ -7,9 +7,6 @@ import { terminalRouteKey } from './terminalRuntime.js'import type { TerminalRuntimeRef } from './terminalTypes.js'const tmux: TerminalRuntimeRef = { backend: 'tmux', paneId: '%1' }-const herdr: TerminalRuntimeRef = {- backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',-}const identity = { pid: 42, executable: 'claude', startMarker: 'Sat Aug 15 10:00:00 2026' }function session(runtimes: TerminalRuntimeRef[] = [tmux]): RegisteredSession {@@ -38,7 +35,7 @@ describe('composite terminal reconciliation', () => {const current = { ...session([tmux]), active: false }const onTerminalAvailability = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),onTerminalAvailability,probe: async () => probe([@@ -56,7 +53,7 @@ describe('composite terminal reconciliation', () => {const onTerminalAvailability = vi.fn()const onProbeStatus = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),onTerminalAvailability, onProbeStatus,probe: async () => ({@@ -80,7 +77,7 @@ describe('composite terminal reconciliation', () => {return probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }])})const reconciler = new TerminalAgentReconciler({- current: () => [], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(), probe: probed,})let started = false@@ -93,14 +90,14 @@ describe('composite terminal reconciliation', () => {reconciler.stop()})- it('does not count an unavailable endpoint as a confirmed miss', async () => {- const current = session([herdr])+ it('does not count an unavailable backend as a confirmed miss', async () => {+ const current = session([tmux])const onDormant = vi.fn()const onRemoved = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['herdr'], herdrSessionOrder: ['default'],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved,- probe: async () => probe([{ instanceId: 'herdr:endpoint-a', result: { state: 'unavailable', reason: 'stopped' } }]),+ probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'unavailable', reason: 'stopped' } }]),})await reconciler.trigger()await reconciler.trigger()@@ -108,41 +105,15 @@ describe('composite terminal reconciliation', () => {expect(onRemoved).not.toHaveBeenCalled()})- it('refreshes configured targets before every cycle so an initially stopped Herdr session can recover', async () => {- const current = session([herdr])- const onObserved = vi.fn()- const onRemoved = vi.fn()- let available = false- const beforeProbe = vi.fn(async () => { available = beforeProbe.mock.calls.length > 1 })- const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['herdr'], herdrSessionOrder: ['default'],- onDiscovered: vi.fn(), onObserved, onDormant: vi.fn(), onRemoved, beforeProbe,- probe: async () => available- ? probe(- [{ instanceId: 'herdr:endpoint-a', result: { state: 'available', roots: [{ runtime: herdr, rootPid: 1, cwd: '/work' }] } }],- [observed([herdr])],- )- : probe([{ instanceId: 'herdr:endpoint-a', result: { state: 'unavailable', reason: 'stopped' } }]),- })-- await reconciler.trigger()- expect(onObserved).not.toHaveBeenCalled()- await reconciler.trigger()-- expect(beforeProbe).toHaveBeenCalledTimes(2)- expect(onObserved).toHaveBeenCalledWith(expect.objectContaining({ runtimes: [herdr] }), current)- expect(onRemoved).not.toHaveBeenCalled()- })-it('removes only after two successful negative inventories', async () => {- const current = session([herdr])+ const current = session([tmux])const onRemoved = vi.fn()const validate = vi.fn(async () => ({ state: 'gone' as const, reason: 'process exited' }))- const backend = { instanceId: 'herdr:endpoint-a', validate } as unknown as TerminalBackend+ const backend = { instanceId: 'tmux:default', validate } as unknown as TerminalBackendconst reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [backend], backendOrder: ['herdr'], herdrSessionOrder: ['default'],+ current: () => [current], backends: [backend], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved,- probe: async () => probe([{ instanceId: 'herdr:endpoint-a', result: { state: 'available', roots: [] } }]),+ probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),})await reconciler.trigger()expect(onRemoved).not.toHaveBeenCalled()@@ -158,7 +129,7 @@ describe('composite terminal reconciliation', () => {const validate = vi.fn(async () => ({ state: 'alive' as const }))const backend = { instanceId: 'tmux:default', validate } as unknown as TerminalBackendconst reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [backend], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [backend], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved,probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),})@@ -180,7 +151,7 @@ describe('composite terminal reconciliation', () => {const validate = vi.fn(async () => ({ state: 'unknown' as const, reason: 'process table timed out' }))const backend = { instanceId: 'tmux:default', validate } as unknown as TerminalBackendconst reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [backend], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [backend], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved,probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),})@@ -192,38 +163,6 @@ describe('composite terminal reconciliation', () => {expect(onRemoved).not.toHaveBeenCalled()})- it('refreshes a moved Herdr route on the same process without changing agent ownership', async () => {- const current = session([herdr])- const moved = { ...herdr, paneId: 'w2:p4' }- const onObserved = vi.fn()- const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['herdr'], herdrSessionOrder: ['default'],- onDiscovered: vi.fn(), onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),- probe: async () => probe(- [{ instanceId: 'herdr:endpoint-a', result: { state: 'available', roots: [{ runtime: moved, rootPid: 1, cwd: '/work' }] } }],- [observed([moved])],- ),- })- await reconciler.trigger()- expect(onObserved).toHaveBeenCalledWith(expect.objectContaining({ runtimes: [moved] }), current)- })-- it('keeps a healthy locator active when another backend is unavailable', async () => {- const current = session([tmux, herdr])- const onObserved = vi.fn()- const onDormant = vi.fn()- const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux', 'herdr'], herdrSessionOrder: ['default'],- onDiscovered: vi.fn(), onObserved, onDormant, onRemoved: vi.fn(),- probe: async () => probe([- { instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } },- { instanceId: 'herdr:endpoint-a', result: { state: 'unavailable', reason: 'stopped' } },- ], [observed([tmux])]),- })- await reconciler.trigger()- expect(onObserved).toHaveBeenCalledWith(expect.objectContaining({ runtimes: [herdr, tmux] }), current)- expect(onDormant).not.toHaveBeenCalled()- })})describe('restart route hold', () => {@@ -237,7 +176,7 @@ describe('restart route hold', () => {const validate = vi.fn(async () => ({ state: 'alive' as const }))const backend = { instanceId: 'tmux:default', validate } as unknown as TerminalBackendconst reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [backend], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [backend], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved,probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),})@@ -261,7 +200,7 @@ describe('restart route hold', () => {const onDiscovered = vi.fn()const onObserved = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered, onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } }],@@ -284,7 +223,7 @@ describe('restart route hold', () => {const validate = vi.fn(async () => ({ state: 'alive' as const }))const backend = { instanceId: 'tmux:default', validate } as unknown as TerminalBackendconst reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [backend], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [backend], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved: vi.fn(),probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),})@@ -316,7 +255,7 @@ describe('verified process adoption', () => {return await apply()}const reconciler = new TerminalAgentReconciler({- current: () => current, backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => current, backends: [], backendOrder: ['tmux'],onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),probe: probeSnapshot, transaction,})@@ -336,7 +275,7 @@ describe('verified process adoption', () => {const onDiscovered = vi.fn()const onObserved = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [existing], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [existing], backends: [], backendOrder: ['tmux'],onDiscovered, onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),})@@ -360,7 +299,7 @@ describe('verified process adoption', () => {const onDiscovered = vi.fn()const onRemoved = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered, onObserved, onDormant: vi.fn(), onRemoved,probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } }],@@ -382,7 +321,7 @@ describe('verified process adoption', () => {const validate = vi.fn(async () => ({ state: 'alive' as const }))const backend = { instanceId: 'tmux:default', validate } as unknown as TerminalBackendconst reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [backend], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [backend], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),})@@ -406,7 +345,7 @@ describe('verified process adoption', () => {}const onObserved = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } }],@@ -430,7 +369,7 @@ describe('verified process adoption', () => {processIdentity: { pid: 999, executable: 'claude', startMarker: 'Tue Sep 24 09:00:00 2026' },}const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } }],@@ -446,7 +385,7 @@ describe('verified process adoption', () => {it('reports no adopted agent when the registry callback rejects the process', async () => {const onDiscovered = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [], backends: [], backendOrder: ['tmux'],onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),})@@ -468,7 +407,7 @@ describe('start()', () => {return probe([])})const reconciler = new TerminalAgentReconciler({- current: () => [], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),probe: scan,})@@ -494,7 +433,7 @@ describe('a terminal pane (engine `terminal`)', () => {const onDormant = vi.fn()const onRemoved = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved,probe: async () => probe(live),})@@ -509,7 +448,7 @@ describe('a terminal pane (engine `terminal`)', () => {const onObserved = vi.fn()const claude = observed([tmux])const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered, onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),probe: async () => probe(live, [claude]),})@@ -525,7 +464,7 @@ describe('a terminal pane (engine `terminal`)', () => {const onDormant = vi.fn()const onRemoved = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved,probe: async () => probe(live),})@@ -540,7 +479,7 @@ describe('a terminal pane (engine `terminal`)', () => {const current = terminal()const onRemoved = vi.fn()const reconciler = new TerminalAgentReconciler({- current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ current: () => [current], backends: [], backendOrder: ['tmux'],onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved,probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),})diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.tsindex 6f8232a58..527809e9d 100644--- a/cli/src/lib/terminalAgentReconciler.ts+++ b/cli/src/lib/terminalAgentReconciler.ts@@ -7,7 +7,7 @@ import {type TerminalAgentProbe,} from './terminalAgentDiscovery.js'import type { TerminalBackend } from './terminalBackend.js'-import { mergeTerminalRuntimes, processIdentityKey, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'+import { mergeTerminalRuntimes, processIdentityKey, terminalInstanceId, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'import type { TerminalRuntimeRef } from './terminalTypes.js'const MISS_LIMIT = 2@@ -16,7 +16,6 @@ export interface TerminalAgentReconcilerDeps {current: () => RegisteredSession[]backends: readonly TerminalBackend[]backendOrder: readonly string[]- herdrSessionOrder: readonly string[]onDiscovered: (agent: DiscoveredTerminalAgent) => void | Promise<void>onObserved: (agent: DiscoveredTerminalAgent, current: RegisteredSession) => void | Promise<void>onDormant: (current: RegisteredSession, reason: string) => void | Promise<void>@@ -24,8 +23,6 @@ export interface TerminalAgentReconcilerDeps {onTerminalAvailability?: (current: RegisteredSession, available: boolean) => void | Promise<void>onProbeStatus?: (status: { ready: true; error: string | null }) => voidtransaction?: <T>(apply: () => T | Promise<T>) => Promise<T>- /** Refresh configured backend instances before each immutable probe cycle. */- beforeProbe?: () => void | Promise<void>probe?: (hints: ReadonlyMap<string, AgentEngine>) => Promise<TerminalAgentProbe>daemonPid?: number}@@ -217,14 +214,12 @@ export class TerminalAgentReconciler {}private async reconcileOnce(): Promise<void> {- await this.deps.beforeProbe?.()const hints = new Map(this.hints)const probe = await (this.deps.probe? this.deps.probe(hints): probeTerminalAgents(this.deps.backends,this.deps.backendOrder,- this.deps.herdrSessionOrder,this.deps.daemonPid ?? process.pid,hints,))@@ -361,7 +356,7 @@ export class TerminalAgentReconciler {.filter((target) => target.result.state === 'available').map((target) => target.instanceId))const unknownRuntimes = current.runtimes.filter((runtime) => !availableInstances.has(- runtime.backend === 'tmux' ? 'tmux:default' : `herdr:${runtime.endpointId}`,+ terminalInstanceId(runtime),))const merged: DiscoveredTerminalAgent = {...observed,diff --git a/cli/src/lib/terminalBackend.ts b/cli/src/lib/terminalBackend.tsindex 11273bdb2..0208d5724 100644--- a/cli/src/lib/terminalBackend.ts+++ b/cli/src/lib/terminalBackend.ts@@ -34,7 +34,7 @@ export interface TerminalBackend<Ref extends TerminalRuntimeRef = TerminalRuntimsetTitle(runtime: Ref, title: string): Promise<TerminalActionResult>notify(runtime: Ref, title: string, body: string): Promise<TerminalActionResult>- /** Byte streaming is optional per backend. MVP is implemented by tmux; Herdr remains capture-only. */+ /** Byte streaming is optional per backend. */openStream?(runtime: Ref,expected: TerminalProcessExpectation,diff --git a/cli/src/lib/terminalBackendCoordinator.spec.ts b/cli/src/lib/terminalBackendCoordinator.spec.tsindex cb09ecf71..62d933d82 100644--- a/cli/src/lib/terminalBackendCoordinator.spec.ts+++ b/cli/src/lib/terminalBackendCoordinator.spec.ts@@ -6,14 +6,12 @@ import { terminalRouteKey } from './terminalRuntime.js'import type { TerminalRuntimeRef, TerminalStreamHandle, TerminalStreamSink } from './terminalTypes.js'const tmux: TerminalRuntimeRef = { backend: 'tmux', paneId: '%1' }-const herdr: TerminalRuntimeRef = {- backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',-}+const second: TerminalRuntimeRef = { backend: 'tmux', paneId: '%2' }function session(): RegisteredSession {return {schemaVersion: 2, active: true, agentId: 'agent-1', sessionId: 's1', boundAt: 1, engine: 'claude', transcriptPath: null,- projectDir: 'work', cwd: '/work', runtimes: [tmux, herdr], primaryRuntimeKey: terminalRouteKey(tmux), tmuxPane: '%1',+ projectDir: 'work', cwd: '/work', runtimes: [tmux, second], primaryRuntimeKey: terminalRouteKey(tmux), tmuxPane: '%1',source: null, title: null, model: null, cliVersion: null,processIdentity: { pid: 42, executable: 'claude', startMarker: 'Sat Aug 15 10:00:00 2026' },registeredAt: 1, touchedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,@@ -22,7 +20,7 @@ function session(): RegisteredSession {function backend(instanceId: string, submit: TerminalBackend['submitText']): TerminalBackend {return {- name: instanceId.startsWith('tmux') ? 'tmux' : 'herdr', instanceId,+ name: 'tmux', instanceId,create: vi.fn(), kill: vi.fn(), inventory: vi.fn(),titles: vi.fn(async () => ({ state: 'succeeded' as const, value: new Map() })),validate: vi.fn(async () => ({ state: 'alive' as const })), capture: vi.fn(), typeLiteral: vi.fn(), submitText: submit,@@ -49,12 +47,19 @@ function streamHandle(): TerminalStreamHandle {}}+/** A submit that answers `onFirst` on the first pane and succeeds on any other. */+function submitBy(onFirst: Awaited<ReturnType<TerminalBackend['submitText']>>) {+ return vi.fn(async (runtime: TerminalRuntimeRef) => runtime.paneId === tmux.paneId+ ? onFirst+ : { state: 'succeeded' as const, dispatch: 'executed' as const })+}+describe('TerminalBackendCoordinator', () => {it('opens a retained terminal runtime even when engine discovery marked the agent dormant', async () => {const tmuxBackend = backend('tmux:default', vi.fn())const handle = streamHandle()tmuxBackend.openStream = vi.fn(async () => ({ state: 'succeeded' as const, value: handle }))- const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'], ['default'])+ const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'])const current = session()current.active = falseconst sink: TerminalStreamSink = { onData: vi.fn(), onClose: vi.fn() }@@ -74,7 +79,7 @@ describe('TerminalBackendCoordinator', () => {it('reports the backend failure when a dormant agent no longer has a terminal pane', async () => {const tmuxBackend = backend('tmux:default', vi.fn())tmuxBackend.openStream = vi.fn(async () => ({ state: 'failed' as const, reason: 'tmux pane is unavailable' }))- const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'], ['default'])+ const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'])const current = session()current.active = false@@ -85,63 +90,52 @@ describe('TerminalBackendCoordinator', () => {)).resolves.toEqual({ state: 'failed', reason: 'tmux pane is unavailable' })})- it('merges backend-scoped title snapshots and prefers the primary runtime title', async () => {- const first = backend('tmux:default', vi.fn())- first.titles = vi.fn(async () => ({ state: 'succeeded' as const, value: new Map([[terminalRouteKey(tmux), 'tmux title']]) }))- const second = backend('herdr:endpoint-a', vi.fn())- second.titles = vi.fn(async () => ({ state: 'succeeded' as const, value: new Map([[terminalRouteKey(herdr), 'Herdr title']]) }))- const coordinator = new TerminalBackendCoordinator([first, second], ['herdr', 'tmux'], ['default'])+ it('merges title snapshots and prefers the primary runtime title', async () => {+ const tmuxBackend = backend('tmux:default', vi.fn())+ tmuxBackend.titles = vi.fn(async () => ({ state: 'succeeded' as const, value: new Map([+ [terminalRouteKey(tmux), 'first title'],+ [terminalRouteKey(second), 'second title'],+ ]) }))+ const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'])const current = session()- current.primaryRuntimeKey = terminalRouteKey(herdr)+ current.primaryRuntimeKey = terminalRouteKey(second)const titles = await coordinator.titles()expect(titles.size).toBe(2)- expect(coordinator.titleFor(current, titles)).toBe('Herdr title')+ expect(coordinator.titleFor(current, titles)).toBe('second title')})it('fails over only when dispatch is proven not to have started', async () => {- const first = backend('tmux:default', vi.fn(async () => ({ state: 'failed' as const, dispatch: 'not_started' as const, reason: 'missing' })))- const second = backend('herdr:endpoint-a', vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })))- const result = await new TerminalBackendCoordinator([first, second], ['tmux', 'herdr'], ['default']).submitText(session(), 'hello')+ const submit = submitBy({ state: 'failed', dispatch: 'not_started', reason: 'missing' })+ const result = await new TerminalBackendCoordinator([backend('tmux:default', submit)], ['tmux']).submitText(session(), 'hello')expect(result).toEqual({ state: 'succeeded', dispatch: 'executed' })- expect(second.submitText).toHaveBeenCalledOnce()+ expect(submit).toHaveBeenCalledTimes(2)+ expect(submit).toHaveBeenLastCalledWith(second, 'hello')})it('never retries a possibly executed side effect', async () => {- const first = backend('tmux:default', vi.fn(async () => ({ state: 'unknown' as const, dispatch: 'possibly_executed' as const, reason: 'lost response' })))- const second = backend('herdr:endpoint-a', vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })))- const result = await new TerminalBackendCoordinator([first, second], ['tmux', 'herdr'], ['default']).submitText(session(), 'hello')+ const submit = submitBy({ state: 'unknown', dispatch: 'possibly_executed', reason: 'lost response' })+ const result = await new TerminalBackendCoordinator([backend('tmux:default', submit)], ['tmux']).submitText(session(), 'hello')expect(result).toMatchObject({ state: 'unknown', dispatch: 'possibly_executed' })- expect(second.submitText).not.toHaveBeenCalled()+ expect(submit).toHaveBeenCalledOnce()})- it('allows read-only capture failover and refreshes a Herdr lease after a route move', async () => {- const first = backend('tmux:default', vi.fn())- first.capture = vi.fn(async () => ({ state: 'failed' as const, reason: 'capture failed' }))- const second = backend('herdr:endpoint-a', vi.fn())- second.capture = vi.fn(async () => ({ state: 'succeeded' as const, value: 'screen' }))- const coordinator = new TerminalBackendCoordinator([first, second], ['tmux', 'herdr'], ['default'])+ it('allows read-only capture failover', async () => {+ const tmuxBackend = backend('tmux:default', vi.fn())+ tmuxBackend.capture = vi.fn(async (runtime: TerminalRuntimeRef) => runtime.paneId === tmux.paneId+ ? { state: 'failed' as const, reason: 'capture failed' }+ : { state: 'succeeded' as const, value: 'screen' })+ const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'])const current = session()await expect(coordinator.capture(current)).resolves.toEqual({ state: 'succeeded', value: 'screen' })const acquired = await coordinator.acquireLease(current)expect(acquired.state).toBe('succeeded')if (acquired.state !== 'succeeded') returnexpect(coordinator.leaseIsCurrent(acquired.value, current)).toBe(true)- current.runtimes = [herdr]- current.primaryRuntimeKey = terminalRouteKey(herdr)- const herdrLease = await coordinator.acquireLease(current)- expect(herdrLease.state).toBe('succeeded')- if (herdrLease.state !== 'succeeded') return- current.runtimes[0] = { ...herdr, paneId: 'w2:p4' }- current.primaryRuntimeKey = terminalRouteKey(current.runtimes[0])- expect(coordinator.leaseIsCurrent(herdrLease.value, current)).toBe(true)- expect(herdrLease.value.runtime).toMatchObject({ paneId: 'w2:p4', terminalId: 'terminal-a' })})it('uses lease-aware pre-dispatch fallback but never retries ambiguous completion', async () => {- const first = backend('tmux:default', vi.fn(async () => ({ state: 'failed' as const, dispatch: 'rejected' as const, reason: 'rejected' })))- const secondSubmit = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))- const second = backend('herdr:endpoint-a', secondSubmit)- const coordinator = new TerminalBackendCoordinator([first, second], ['tmux', 'herdr'], ['default'])+ const tmuxBackend = backend('tmux:default', submitBy({ state: 'failed', dispatch: 'rejected', reason: 'rejected' }))+ const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'])const current = session()const acquired = await coordinator.acquireLease(current)expect(acquired.state).toBe('succeeded')@@ -149,25 +143,21 @@ describe('TerminalBackendCoordinator', () => {await expect(coordinator.submitTextForLease(current, acquired.value, 'hello')).resolves.toEqual({state: 'succeeded', dispatch: 'executed',})- expect(acquired.value.runtime).toEqual(herdr)+ expect(acquired.value.runtime).toEqual(second)- first.submitText = vi.fn(async () => ({ state: 'unknown' as const, dispatch: 'possibly_executed' as const, reason: 'lost response' }))+ const ambiguous = submitBy({ state: 'unknown', dispatch: 'possibly_executed', reason: 'lost response' })+ tmuxBackend.submitText = ambiguousconst another = await coordinator.acquireLease(current)if (another.state !== 'succeeded') return- secondSubmit.mockClear()await expect(coordinator.submitTextForLease(current, another.value, 'again')).resolves.toMatchObject({state: 'unknown', dispatch: 'possibly_executed',})- expect(secondSubmit).not.toHaveBeenCalled()+ expect(ambiguous).toHaveBeenCalledOnce()})it('never changes placement for a side effect issued through an already pinned multi-step lease', async () => {- const firstSubmit = vi.fn(async () => ({ state: 'failed' as const, dispatch: 'rejected' as const, reason: 'rejected' }))- const secondSubmit = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))- const coordinator = new TerminalBackendCoordinator([- backend('tmux:default', firstSubmit),- backend('herdr:endpoint-a', secondSubmit),- ], ['tmux', 'herdr'], ['default'])+ const submit = submitBy({ state: 'failed', dispatch: 'rejected', reason: 'rejected' })+ const coordinator = new TerminalBackendCoordinator([backend('tmux:default', submit)], ['tmux'])const acquired = await coordinator.acquireLease(session())expect(acquired.state).toBe('succeeded')if (acquired.state !== 'succeeded') return@@ -175,21 +165,19 @@ describe('TerminalBackendCoordinator', () => {await expect(coordinator.submitTextLease(acquired.value, 'hello')).resolves.toMatchObject({state: 'failed', dispatch: 'rejected',})- expect(firstSubmit).toHaveBeenCalledOnce()- expect(secondSubmit).not.toHaveBeenCalled()+ expect(submit).toHaveBeenCalledOnce()+ expect(submit).toHaveBeenCalledWith(tmux, 'hello')})- it('keeps an active lease valid when refreshed endpoint discovery reuses the same backend instance', async () => {- const herdrBackend = backend('herdr:endpoint-a', vi.fn())- const coordinator = new TerminalBackendCoordinator([herdrBackend], ['herdr'], ['default'])+ it('keeps an active lease valid when the backends are replaced by the same instance', async () => {+ const tmuxBackend = backend('tmux:default', vi.fn())+ const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'])const current = session()- current.runtimes = [herdr]- current.primaryRuntimeKey = terminalRouteKey(herdr)const acquired = await coordinator.acquireLease(current)expect(acquired.state).toBe('succeeded')if (acquired.state !== 'succeeded') return- coordinator.replaceBackends([herdrBackend])+ coordinator.replaceBackends([tmuxBackend])expect(coordinator.leaseIsCurrent(acquired.value, current)).toBe(true)await expect(coordinator.validateLease(acquired.value, current)).resolves.toBe(true)diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.tsindex c40311652..ad08d4462 100644--- a/cli/src/lib/terminalBackendCoordinator.ts+++ b/cli/src/lib/terminalBackendCoordinator.ts@@ -49,7 +49,6 @@ export class TerminalBackendCoordinator {constructor(backends: readonly TerminalBackend[],private readonly backendOrder: readonly string[],- private herdrSessionOrder: readonly string[],) {this.replaceBackends(backends)}@@ -59,14 +58,6 @@ export class TerminalBackendCoordinator {for (const backend of backends) this.byInstance.set(backend.instanceId, backend)}- /**- * The session order is only a deterministic tie-break between two runtimes of the same backend, but it- * has to track discovery: with sessions adopted as they start, the set is no longer fixed at boot.- */- setHerdrSessionOrder(order: readonly string[]): void {- this.herdrSessionOrder = order- }-instances(): TerminalBackend[] {return [...this.byInstance.values()]}@@ -103,9 +94,6 @@ export class TerminalBackendCoordinator {const ab = this.backendOrder.indexOf(a.backend)const bb = this.backendOrder.indexOf(b.backend)if (ab !== bb) return (ab < 0 ? Number.MAX_SAFE_INTEGER : ab) - (bb < 0 ? Number.MAX_SAFE_INTEGER : bb)- if (a.backend === 'herdr' && b.backend === 'herdr') {- return this.herdrSessionOrder.indexOf(a.sessionName) - this.herdrSessionOrder.indexOf(b.sessionName)- }return terminalRouteKey(a).localeCompare(terminalRouteKey(b))})}@@ -152,8 +140,6 @@ export class TerminalBackendCoordinator {if (lease.agentId !== session.agentId || lease.generation !== runtimeGeneration(session)) return falseconst current = session.runtimes.find((runtime) => terminalPlacementKey(runtime) === lease.placementKey)if (!current) return false- // Herdr's pane route is mutable. Refresh it under the stable endpoint + terminal placement rather- // than splitting a pinned interaction across a different placement.lease.runtime = currentreturn true}@@ -184,7 +170,7 @@ export class TerminalBackendCoordinator {return backend ? backend.capture(lease.runtime, options) : { state: 'failed', reason: 'leased terminal backend is disabled' }}- /** Open a byte stream on the first validated streaming-capable runtime. MVP deliberately skips Herdr. */+ /** Open a byte stream on the first validated streaming-capable runtime. */async openStream(session: RegisteredSession,size: TerminalStreamSize,diff --git a/cli/src/lib/terminalConfigSnapshot.spec.ts b/cli/src/lib/terminalConfigSnapshot.spec.tsdeleted file mode 100644index 1507abc7e..000000000--- a/cli/src/lib/terminalConfigSnapshot.spec.ts+++ /dev/null@@ -1,61 +0,0 @@-import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'-import { tmpdir } from 'node:os'-import { join } from 'node:path'-import { afterEach, describe, expect, it } from 'vitest'-import { readTerminalConfigSnapshot, terminalConfigSnapshotPath, writeTerminalConfigSnapshot } from './terminalConfigSnapshot.js'--const cleanup: string[] = []--afterEach(() => {- for (const path of cleanup.splice(0)) rmSync(path, { recursive: true, force: true })-})--describe('terminal config snapshot', () => {- it('atomically persists only configured endpoints in configured order', () => {- const dataDir = mkdtempSync(join(tmpdir(), 'terminal-config-'))- cleanup.push(dataDir)- writeTerminalConfigSnapshot(dataDir, { backends: ['herdr'], herdrSessions: ['work', 'default'] }, [- { sessionName: 'default', endpointId: 'default-id', socketPath: '/safe/default.sock', generation: { device: 1, inode: 2 } },- { sessionName: 'ignored', endpointId: 'ignored-id', socketPath: '/safe/ignored.sock', generation: { device: 3, inode: 4 } },- { sessionName: 'work', endpointId: 'work-id', socketPath: '/safe/work.sock', generation: { device: 5, inode: 6 } },- ])-- const file = terminalConfigSnapshotPath(dataDir)- expect(statSync(file).mode & 0o777).toBe(0o600)- expect(readTerminalConfigSnapshot(dataDir)?.herdrEndpoints.map((endpoint) => endpoint.sessionName)).toEqual(['work', 'default'])- expect(readFileSync(file, 'utf8')).not.toContain('ignored-id')- })-- it('tightens an owner-owned legacy snapshot before reading it', () => {- const dataDir = mkdtempSync(join(tmpdir(), 'terminal-config-'))- cleanup.push(dataDir)- writeTerminalConfigSnapshot(dataDir, { backends: ['tmux'], herdrSessions: [] }, [])- chmodSync(terminalConfigSnapshotPath(dataDir), 0o644)- expect(readTerminalConfigSnapshot(dataDir)?.backends).toEqual(['tmux'])- expect(statSync(terminalConfigSnapshotPath(dataDir)).mode & 0o777).toBe(0o600)- })-- it('rejects a group-writable snapshot instead of tightening and trusting it', () => {- const dataDir = mkdtempSync(join(tmpdir(), 'terminal-config-'))- cleanup.push(dataDir)- writeTerminalConfigSnapshot(dataDir, { backends: ['tmux'], herdrSessions: [] }, [])- chmodSync(terminalConfigSnapshotPath(dataDir), 0o660)- expect(readTerminalConfigSnapshot(dataDir)).toBeNull()- expect(statSync(terminalConfigSnapshotPath(dataDir)).mode & 0o777).toBe(0o660)- })-- it('neither reads nor replaces a symlinked snapshot', () => {- const root = mkdtempSync(join(tmpdir(), 'terminal-config-'))- cleanup.push(root)- const dataDir = join(root, 'data')- const target = join(root, 'target.json')- writeFileSync(target, '{}', { mode: 0o600 })- writeTerminalConfigSnapshot(dataDir, { backends: ['tmux'], herdrSessions: [] }, [])- rmSync(terminalConfigSnapshotPath(dataDir))- symlinkSync(target, terminalConfigSnapshotPath(dataDir))-- expect(readTerminalConfigSnapshot(dataDir)).toBeNull()- expect(() => writeTerminalConfigSnapshot(dataDir, { backends: ['tmux'], herdrSessions: [] }, [])).toThrow()- expect(readFileSync(target, 'utf8')).toBe('{}')- })-})diff --git a/cli/src/lib/terminalConfigSnapshot.ts b/cli/src/lib/terminalConfigSnapshot.tsdeleted file mode 100644index cbf18a7b6..000000000--- a/cli/src/lib/terminalConfigSnapshot.ts+++ /dev/null@@ -1,102 +0,0 @@-import { randomUUID } from 'node:crypto'-import { closeSync, constants, fchmodSync, fsyncSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs'-import { isAbsolute, join } from 'node:path'-import type { TerminalConfig } from '../config/terminalConfig.js'-import type { HerdrEndpoint } from './herdrApiClient.js'-import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'-import type { TerminalBackendName } from './terminalTypes.js'--const SNAPSHOT_FILE = 'terminal-config.json'-const MAX_SNAPSHOT_BYTES = 64 * 1024--export interface TerminalConfigEndpointSnapshot {- sessionName: string- endpointId: string- socketPath: string- generation: { device: number; inode: number }-}--export interface TerminalConfigSnapshot {- version: 1- updatedAt: number- backends: TerminalBackendName[]- herdrEndpoints: TerminalConfigEndpointSnapshot[]-}--export function terminalConfigSnapshotPath(dataDir: string): string {- return join(dataDir, SNAPSHOT_FILE)-}--export function writeTerminalConfigSnapshot(- dataDir: string,- config: TerminalConfig,- endpoints: readonly HerdrEndpoint[],-): TerminalConfigSnapshot {- const allowed = new Set(config.herdrSessions)- const herdrEndpoints = endpoints- .filter((endpoint) => allowed.has(endpoint.sessionName))- .sort((a, b) => config.herdrSessions.indexOf(a.sessionName) - config.herdrSessions.indexOf(b.sessionName))- .map(({ sessionName, endpointId, socketPath, generation }) => ({- sessionName,- endpointId,- socketPath,- generation: { ...generation },- }))- const snapshot: TerminalConfigSnapshot = {- version: 1,- updatedAt: Date.now(),- backends: [...config.backends],- herdrEndpoints,- }- secureStateDirectory(dataDir)- const file = terminalConfigSnapshotPath(dataDir)- hardenPrivateStateFileIfPresent(file, MAX_SNAPSHOT_BYTES)- const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`- let renamed = false- try {- const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)- try {- writeFileSync(fd, `${JSON.stringify(snapshot, null, 2)}\n`)- fchmodSync(fd, 0o600)- fsyncSync(fd)- } finally {- closeSync(fd)- }- renameSync(temporary, file)- renamed = true- const directoryFd = openSync(dataDir, 'r')- try { fsyncSync(directoryFd) } finally { closeSync(directoryFd) }- } finally {- if (!renamed) rmSync(temporary, { force: true })- }- return snapshot-}--function validString(value: unknown, max = 200): value is string {- return typeof value === 'string' && value.length > 0 && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value)-}--export function readTerminalConfigSnapshot(dataDir: string): TerminalConfigSnapshot | null {- const file = terminalConfigSnapshotPath(dataDir)- try {- secureStateDirectory(dataDir, false)- const parsed = JSON.parse(readPrivateStateFile(file, MAX_SNAPSHOT_BYTES)) as Partial<TerminalConfigSnapshot>- if (parsed.version !== 1 || !Number.isFinite(parsed.updatedAt)) return null- if (!Array.isArray(parsed.backends)- || parsed.backends.some((backend) => backend !== 'tmux' && backend !== 'herdr')- || new Set(parsed.backends).size !== parsed.backends.length) return null- if (!Array.isArray(parsed.herdrEndpoints)) return null- for (const endpoint of parsed.herdrEndpoints) {- if (!endpoint || typeof endpoint !== 'object') return null- if (!validString(endpoint.sessionName, 64)- || !validString(endpoint.endpointId)- || !validString(endpoint.socketPath, 4_096)- || !isAbsolute(endpoint.socketPath)- || !Number.isSafeInteger(endpoint.generation?.device)- || !Number.isSafeInteger(endpoint.generation?.inode)) return null- }- return parsed as TerminalConfigSnapshot- } catch {- return null- }-}diff --git a/cli/src/lib/terminalEnvironment.spec.ts b/cli/src/lib/terminalEnvironment.spec.tsindex 3a32e5ef0..6ee03e2d8 100644--- a/cli/src/lib/terminalEnvironment.spec.ts+++ b/cli/src/lib/terminalEnvironment.spec.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'import { scrubTerminalContext, TERMINAL_CONTEXT_VARIABLES } from './terminalEnvironment.js'describe('scrubTerminalContext', () => {- it('removes the complete tmux and Herdr routing context without touching unrelated values', () => {+ it('removes the complete tmux routing context without touching unrelated values', () => {const environment = Object.fromEntries([...TERMINAL_CONTEXT_VARIABLES.map((key) => [key, `value-${key}`]),['PATH', '/bin'],diff --git a/cli/src/lib/terminalEnvironment.ts b/cli/src/lib/terminalEnvironment.tsindex ff04a12d5..1ea3f9f95 100644--- a/cli/src/lib/terminalEnvironment.ts+++ b/cli/src/lib/terminalEnvironment.ts@@ -1,12 +1,6 @@export const TERMINAL_CONTEXT_VARIABLES = ['TMUX','TMUX_PANE',- 'HERDR_ENV',- 'HERDR_SESSION',- 'HERDR_SOCKET_PATH',- 'HERDR_WORKSPACE_ID',- 'HERDR_TAB_ID',- 'HERDR_PANE_ID',] as const/** Mutate a child-only environment copy so one-shots cannot register as top-level terminal agents. */diff --git a/cli/src/lib/terminalRuntime.spec.ts b/cli/src/lib/terminalRuntime.spec.tsindex a637f9cdf..8c403fd62 100644--- a/cli/src/lib/terminalRuntime.spec.ts+++ b/cli/src/lib/terminalRuntime.spec.ts@@ -6,29 +6,14 @@ import {terminalPlacementKey,terminalRouteKey,} from './terminalRuntime.js'-import type { HerdrRuntimeRef, TmuxRuntimeRef } from './terminalTypes.js'+import type { TmuxRuntimeRef } from './terminalTypes.js'const tmux: TmuxRuntimeRef = { backend: 'tmux', paneId: '%3' }-const herdr: HerdrRuntimeRef = {- backend: 'herdr',- endpointId: 'herdr:default:abc',- sessionName: 'default',- terminalId: 'terminal-1',- paneId: 'w1:p1',-}-describe('terminal runtime identity', () => {- it('scopes duplicate Herdr pane routes to their configured endpoint', () => {- const other = { ...herdr, endpointId: 'herdr:work:def', sessionName: 'work' }- expect(terminalRouteKey(herdr)).not.toBe(terminalRouteKey(other))- expect(terminalPlacementKey(herdr)).not.toBe(terminalPlacementKey(other))- })-- it('keeps Herdr placement stable while replacing a moved route', () => {- const moved = { ...herdr, paneId: 'w2:p4' }- expect(terminalPlacementKey(moved)).toBe(terminalPlacementKey(herdr))- expect(terminalRouteKey(moved)).not.toBe(terminalRouteKey(herdr))- expect(mergeTerminalRuntimes([tmux, herdr], [moved])).toEqual([moved, tmux])+ it('merges observed runtimes without duplicating a placement', () => {+ const other: TmuxRuntimeRef = { backend: 'tmux', paneId: '%4' }+ expect(terminalPlacementKey(tmux)).toBe(terminalRouteKey(tmux))+ expect(mergeTerminalRuntimes([tmux], [other, { ...tmux }])).toEqual([tmux, other])})it('keys process identity without treating argv-derived executable as authoritative', () => {diff --git a/cli/src/lib/terminalRuntime.ts b/cli/src/lib/terminalRuntime.tsindex c0d1a4421..97baa40c9 100644--- a/cli/src/lib/terminalRuntime.ts+++ b/cli/src/lib/terminalRuntime.ts@@ -7,29 +7,23 @@ function assertKeyPart(value: string, field: string): string {return value}-/** Stable route key. It changes when a Herdr terminal moves to a different public pane route. */+/** Stable route key. */export function terminalRouteKey(runtime: TerminalRuntimeRef): string {- return runtime.backend === 'tmux'- ? `tmux${SEP}${assertKeyPart(runtime.paneId, 'tmux pane id')}`- : `herdr${SEP}${assertKeyPart(runtime.endpointId, 'Herdr endpoint id')}${SEP}${assertKeyPart(runtime.paneId, 'Herdr pane id')}`+ return `tmux${SEP}${assertKeyPart(runtime.paneId, 'tmux pane id')}`}-export function terminalInstanceId(runtime: TerminalRuntimeRef): string {- return runtime.backend === 'tmux' ? 'tmux:default' : `herdr:${assertKeyPart(runtime.endpointId, 'Herdr endpoint id')}`+export function terminalInstanceId(_runtime: TerminalRuntimeRef): string {+ return 'tmux:default'}-/** Human-readable locator label for status and logs. It never contains a Herdr socket path. */+/** Human-readable locator label for status and logs. */export function terminalRuntimeLabel(runtime: TerminalRuntimeRef): string {- return runtime.backend === 'tmux'- ? `tmux:${runtime.paneId}`- : `herdr:${runtime.sessionName}:${runtime.paneId}`+ return `tmux:${runtime.paneId}`}-/** Stable placement key. A Herdr pane move keeps this key because terminal_id is the placement identity. */+/** Stable placement key. For tmux the pane id is both the route and the placement identity. */export function terminalPlacementKey(runtime: TerminalRuntimeRef): string {- return runtime.backend === 'tmux'- ? terminalRouteKey(runtime)- : `herdr${SEP}${assertKeyPart(runtime.endpointId, 'Herdr endpoint id')}${SEP}${assertKeyPart(runtime.terminalId, 'Herdr terminal id')}`+ return terminalRouteKey(runtime)}export function processIdentityKey(engine: string, identity: ProcessIdentity): string {@@ -44,7 +38,7 @@ export function sameTerminalPlacement(a: TerminalRuntimeRef, b: TerminalRuntimeRreturn terminalPlacementKey(a) === terminalPlacementKey(b)}-/** Replace a moved Herdr route without duplicating its stable placement. */+/** Merge observed runtimes into the current set without duplicating a placement. */export function mergeTerminalRuntimes(current: readonly TerminalRuntimeRef[],observed: readonly TerminalRuntimeRef[],diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex 908575213..97a768ef5 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -1,6 +1,6 @@import type { AgentEngine } from '../engines/types.js'-export type TerminalBackendName = 'tmux' | 'herdr'+export type TerminalBackendName = 'tmux'/** PID reuse-safe identity for the process that owns a Harness agent. */export interface ProcessIdentity {@@ -14,23 +14,10 @@ export interface TmuxRuntimeRef {paneId: string}-export interface HerdrRuntimeRef {- backend: 'herdr'- /** Stable configured-target identifier. Never contains the socket path. */- endpointId: string- sessionName: string- /** Stable within one Herdr endpoint, including across pane moves. */- terminalId: string- /** Mutable public route, scoped to endpointId. */- paneId: string-}--export type TerminalRuntimeRef = TmuxRuntimeRef | HerdrRuntimeRef+export type TerminalRuntimeRef = TmuxRuntimeRef-/** Untrusted route hints from hooks. Herdr socket paths are lookup hints, never connection authority. */-export type HookTerminalHint =- | { backend: 'tmux'; paneId: string }- | { backend: 'herdr'; paneId: string; sessionName?: string; socketPath?: string }+/** Untrusted route hints from hooks. */+export type HookTerminalHint = { backend: 'tmux'; paneId: string }export interface TerminalRootObservation {runtime: TerminalRuntimeRefdiff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex 2f1f312e7..af3635d36 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -398,8 +398,8 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {* `TmuxControlStream.open` reads `paneMeta` first and refuses a missing pane and a multi-pane* window. Dropping the check also takes a whole-process-table `ps` scan off every terminal open.*- * `expected` stays in the signature because `TerminalBackend` defines it and Herdr may still want- * it; it is intentionally unused here.+ * `expected` stays in the signature because `TerminalBackend` defines it; it is intentionally+ * unused here.*/async openStream(runtime: TmuxRuntimeRef,diff --git a/desktop/lib/bootstrap/environment_provisioner.dart b/desktop/lib/bootstrap/environment_provisioner.dartindex 935d8e8d4..bcb3e1954 100644--- a/desktop/lib/bootstrap/environment_provisioner.dart+++ b/desktop/lib/bootstrap/environment_provisioner.dart@@ -1051,8 +1051,7 @@ class EnvironmentProvisioner {emit(step: EnvironmentStep.tmux,status: EnvironmentStepStatus.unavailable,- output:- 'tmux does not exist on Windows — terminals come from Herdr instead.',+ output: 'tmux does not exist on Windows.',);}diff --git a/desktop/test/machine_tree_widget_test.dart b/desktop/test/machine_tree_widget_test.dartindex 3f36a2119..153ed18c6 100644--- a/desktop/test/machine_tree_widget_test.dart+++ b/desktop/test/machine_tree_widget_test.dart@@ -78,15 +78,15 @@ void main() {},}),Agent.fromJson({- 'id': 'herdr-only',- 'sessionId': 'session-herdr',- 'name': 'herdr-session',+ 'id': 'foreign-only',+ 'sessionId': 'session-foreign',+ 'name': 'foreign-session','engine': 'claude','status': 'active','terminal': {'runtimes': [{- 'backend': 'herdr',+ 'backend': 'future-backend','endpointId': 'endpoint-a','sessionName': 'default','terminalId': 'terminal-a',@@ -99,7 +99,7 @@ void main() {state.sessionAgentIds.addAll({'session-parent': 'parent','session-child': 'child',- 'session-herdr': 'herdr-only',+ 'session-foreign': 'foreign-only',});notifier.machines = [machine];notifier.machineStates[machine.machineId] = state;diff --git a/docs/extending.md b/docs/extending.mdindex 6daaa6313..9403ea4cd 100644--- a/docs/extending.md+++ b/docs/extending.md@@ -42,9 +42,8 @@ with a stable, multiplexer-namespaced id, and your tool's presence is detectableso a machine that lacks it pays nothing. Then implement: list panes with PID and working directory,send literal text and keys, capture a pane, display a message, create and kill sessions. Carry the newpane identity through process discovery, registry persistence and hooks, and scrub it from recap-workers so they cannot register as phantom agents. The retired Herdr backend is still in the tree-(`cli/src/lib/herdrBackend.ts`) as the worked example of the contract; see-[Adding a multiplexer](CONTRIBUTING.md#adding-a-multiplexer).+workers so they cannot register as phantom agents. `cli/src/lib/tmuxBackend.ts` is the worked example+of the contract; see [Adding a multiplexer](CONTRIBUTING.md#adding-a-multiplexer).```bashcd cli && npm run test:tmux-real # the real multiplexer discovery suite