Files
gstack/browse/src/terminal-agent-control.ts
T
01593aa67c v1.91.2.0 fix: consolidate gstack reliability wave (#2959)
* fix(memory-ingest): --scan-secrets scans the rendered page and fails closed

--scan-secrets ran gitleaks on the raw transcript .jsonl, then imported a
page rendered from it. gitleaks' assignment rules don't match across a
JSON-escaped quote (KEY=\"v\" on disk), so a secret the rendered page
shows as KEY="v" was imported unflagged. And the gate skipped a file only
on scanner "gitleaks" with findings, so a scan that errored (non-zero
exit, 16MB maxBuffer overflow on a file with many findings, unparseable
report) or could not run (gitleaks missing, slow-probe cooldown) imported
the file unscanned.

Scan the rendered page body, the exact bytes writeStaged() writes, via a
new secretScanText() helper, and skip the file whenever the scan did not
complete. Skipped files stay out of the state file, so the next run
retries them. Reword the helper warnings and setup-gbrain/memory.md,
which described the fail-open as intended.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(test): reconcile Bun failure markers and footer counts

* fix(sync-gbrain): verify source-scoped reads without mutation

* fix(test): recognize grounded TTHW target choices structurally

* fix(aside): make the readiness probe work under zsh and report why it failed

The probe built its deadline into `_T` and expanded it unquoted, so
`$_T aside repl …` only worked in a shell that word-splits. zsh does not: it
looked for a command literally named "gtimeout 30", the probe answered
ASIDE_NOT_RUNNING with Aside installed and ready, and every browsing skill
fell back to the bundled Chromium in silence. zsh is the macOS default and
Aside is macOS-only, so on a stock Mac the probe could never report READY.

The deadline becomes a function, `_gs_d`. It receives the command as "$@",
already split, so sh, bash and zsh all behave the same, and the gtimeout →
timeout → perl alarm chain is unchanged. A 4th arm runs the call unbounded
when none of the three is present, which is what the empty `_T` did before.
Not `eval`: it re-parses the string, so the parens and `;` of the perl arm
become syntax and that arm dies in bash *and* zsh — on a stock Mac, the arm
that actually runs.

On failure the probe now prints the CLI's reason after ASIDE_NOT_RUNNING:,
the shape gstack-render already uses: the first line that starts with a
capital letter, i.e. the CLI's own sentence or Node's `Error:` line below its
loader frame. "Not running" covers states with different fixes — no window
open for the profile, a NODE_OPTIONS preload that kills the CLI — and a bare
verdict sent all of them to "open the Aside app". The BROWSER SETUP prose
quotes that reason before asking the user to open the app.

The text pin asserted the broken invocation verbatim, so it now pins the
function and asserts neither `$_T aside repl` nor an eval form comes back. A
second test executes the rendered probe in sh, bash and zsh on each of the
four deadline arms with stubbed binaries on a narrowed PATH, plus two failing
CLIs: one that prints its own sentence, one that crashes like Node with the
useful line below the frame.

The deadline function costs zero bytes against the lines it replaces; the
reason costs 53 per copy of the probe (44 where the reworded BROWSER SETUP
line gives 9 back). That moves four guards by the measured amount:
plan-devex-review's skeleton cap to 68,550 (measured 68,544), plan-ceo-review's
skeleton cap to 80,150 (measured 80,111) and union ratio to 1.081 (measured
1.0803), and plan-eng-review's union ratio to 1.151 (measured 1.1504).

Fixes #2842, #2941.

* Clarify engineering review startup and decision flow

* Fix Windows readiness fixture PATH and command shim

* fix(test): recognize grounded TTHW target choices structurally

* Clarify engineering review startup and decision flow

* fix(test): restrict QA-only fixture tools to its no-Edit contract

* v1.90.0.0 fix(sync-gbrain): guard readiness verdicts and refresh metadata

* fix(browse): validate canonical upload targets

* fix(gbrain): classify structured PGLite busy response

* fix(browse): preserve native extension runtime APIs

* Fix displayless browser handoff ownership

* Accept unique installed autoplan methodology aliases

* fix(skills): preserve positional literals during installation

* fix(browse): checksum installer contents through stdin

* fix(test): normalize Windows checksum fixture paths

* test: emulate unavailable shasum in Windows checksum fixture

* fix(investigate): preserve owned freeze lifecycle

* fix(review): preserve N+1 retry and Red Team completion

* fix: bound Aside readiness and preserve safe fallback

* test: exercise setup and Chromium on native ARM

* fix: preserve install ownership and ARM browser selection

* Fix gbrain ingest scan boundaries and seed observation

* Refresh managed ship hooks and supervise expanded paid census

* Reject resumed gbrain pages excluded by current policy

* Recover zombie agent locks safely and enable CI Python venv

* Repair paid actor declarations and Aside pitch assertions

* Bump consolidated wave to next free minor release

* Clarify CEO review admin choices and option tradeoffs

* Preserve CEO mode handoff anchors in clarified workflow

* Make Windows portability fixtures use shell-native paths

* Restore ARM Bun alias and clarify ship review gates

* Refresh ship workflow golden snapshots

* Fix Windows DX documentation controls without piped stdin

* Decode Codex child pipes without Bun's encoded-stream stall

* Bound DX pre-review audit before product questions

* Clarify trusted review-start read in paid revalidation

* Bump consolidated wave to next free minor release

* Clarify CEO review admin choices and option tradeoffs

* Preserve CEO mode handoff anchors in clarified workflow

* Make Windows portability fixtures use shell-native paths

* Restore ARM Bun alias and clarify ship review gates

* Refresh ship workflow golden snapshots

* Fix Windows DX documentation controls without piped stdin

* Decode Codex child pipes without Bun's encoded-stream stall

* Bound DX pre-review audit before product questions

* Clarify trusted review-start read in paid revalidation

* Reconcile new main planning flow and paid judge census

* fix: reconcile rebased planning and source-bound validation

* test: pin cookie workflow judge to scored Sonnet model

* fix: keep terminal agent boot out of module imports

* fix: preserve pending-question uncertainty in engineering review

* fix: stabilize Windows reliability-wave fixtures

* fix: clarify design consultation research workflow

* fix: preserve independent design consultation inputs

* fix: resolve design taste scope and browser research guidance

* fix: make consultation opt-in preflight unambiguous

* test: await native Edge owner readiness or terminal result

---------

Co-authored-by: Bruce Krysiak <brucek@alum.mit.edu>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Antonio Vitalic <antoninte99@gmail.com>
2026-09-26 18:57:53 -04:00

365 lines
16 KiB
TypeScript

/**
* terminal-agent process-control primitives shared by cli.ts spawn site,
* server.ts shutdown teardown, and the v1.44 watchdog/respawn loop.
*
* Why this exists: pre-v1.44 used `pkill -f terminal-agent\.ts`, which
* matches any process whose argv contains the string and would kill
* sibling gstack sessions on the same host. The agent now writes a
* structured `terminal-agent-pid` record (`{pid, gen, startedAt}`) and
* every kill site routes through `killAgentByRecord` here — identity-based,
* no regex.
*
* The `gen` field is a per-boot generation counter. Loopback /internal/*
* calls from the parent server include `X-Browse-Gen` so a slow agent that
* the watchdog respawned around can't accidentally service a stale grant
* from the old generation.
*/
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import { spawnSync } from 'child_process';
import { safeUnlink, isProcessAlive } from './error-handling';
import { restrictFilePermissions, mkdirSecure } from './file-permissions';
import { atomicWriteSync } from '../../lib/fs-atomic';
import { readPidCmdline, readPidStartTime } from './xvfb';
function agentProcessInfo(pid: number): { startTime: string; commandLine: string } {
if (!Number.isSafeInteger(pid) || pid <= 0) return { startTime: '', commandLine: '' };
if (process.platform !== 'win32') return { startTime: readPidStartTime(pid), commandLine: readPidCmdline(pid) };
const script = `(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' | Select-Object CreationDate,CommandLine | ConvertTo-Json -Compress)`;
try {
const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true, timeout: 2000 });
if (result.status !== 0 || !result.stdout) return { startTime: '', commandLine: '' };
const processInfo = JSON.parse(result.stdout);
return { startTime: processInfo?.CreationDate || '', commandLine: processInfo?.CommandLine || '' };
} catch { return { startTime: '', commandLine: '' }; }
}
export function readAgentStartTime(pid: number): string {
return agentProcessInfo(pid).startTime;
}
const pendingAgentExits = new Set<any>();
function reclaimPublicationLock(stateDir: string, lockPath: string): boolean {
try {
const inode = fs.lstatSync(lockPath, { bigint: true });
if (!inode.isFile() || inode.size === 0n || inode.size > 4096n) return false;
const contents = fs.readFileSync(lockPath, 'utf8');
const lock = JSON.parse(contents);
const record = readAgentRecord(stateDir);
if (lock?.kind !== 'agent-publication-v1' || !record
|| !Number.isSafeInteger(record.pid) || record.pid <= 0
|| typeof record.gen !== 'string' || !record.gen
|| typeof record.startTime !== 'string' || !record.startTime
|| record.ownerPid !== process.pid
|| typeof record.ownerStartTime !== 'string' || !record.ownerStartTime) return false;
const fields = ['pid', 'gen', 'startTime', 'ownerPid', 'ownerStartTime'] as const;
if (fields.some(field => lock[field] !== record[field])
|| readAgentStartTime(process.pid) !== record.ownerStartTime) return false;
let present = true;
try { process.kill(record.pid, 0); }
catch (err: any) {
if (err?.code !== 'ESRCH') return false;
present = false;
}
if (present) {
if (readAgentStartTime(record.pid) !== record.startTime) return false;
if (process.platform === 'linux') {
const state = fs.readFileSync(`/proc/${record.pid}/stat`, 'utf8').match(/^\d+ \(.*\) ([A-Z])/u)?.[1];
if (state !== 'Z') return false;
} else if (process.platform === 'darwin') {
const result = spawnSync('ps', ['-p', String(record.pid), '-o', 'stat='], { encoding: 'utf8', windowsHide: true, timeout: 2000 });
if (result.status !== 0 || result.stdout?.trim()?.[0] !== 'Z') return false;
} else return false;
}
const currentRecord = readAgentRecord(stateDir);
if (!currentRecord || fields.some(field => currentRecord[field] !== record[field])) return false;
if (present && readAgentStartTime(record.pid) !== record.startTime) return false;
if (fs.readFileSync(lockPath, 'utf8') !== contents) return false;
const current = fs.lstatSync(lockPath, { bigint: true });
if (!current.isFile() || current.dev !== inode.dev || current.ino !== inode.ino) return false;
fs.unlinkSync(lockPath);
return true;
} catch { return false; }
}
export function acquireAgentStateLock(stateDir: string, waitMs = 5000, publicationGen?: string): () => void {
mkdirSecure(stateDir);
const lockPath = path.join(stateDir, 'terminal-agent-pid.lock');
let publication: string | undefined;
if (publicationGen !== undefined) {
const record = readAgentRecord(stateDir);
if (!record || record.pid !== process.pid || record.gen !== publicationGen
|| !record.ownerPid || !isOurAgent(record, record.ownerPid)) {
throw new Error('terminal-agent publication lock identity is unavailable');
}
publication = JSON.stringify({ kind: 'agent-publication-v1', pid: record.pid, gen: record.gen,
startTime: record.startTime, ownerPid: record.ownerPid, ownerStartTime: record.ownerStartTime });
}
const deadline = Date.now() + waitMs;
let reclaimed = false;
let fd: number;
while (true) {
try {
if (publication !== undefined) {
atomicWriteSync(lockPath, publication, { mode: 0o600, noReplace: true });
fd = fs.openSync(lockPath, 'r');
} else {
fd = fs.openSync(lockPath, 'wx', 0o600);
}
break;
} catch (err: any) {
if (err?.code === 'EEXIST' && !reclaimed && reclaimPublicationLock(stateDir, lockPath)) {
reclaimed = true;
continue;
}
if (err?.code !== 'EEXIST' || Date.now() >= deadline) {
throw new Error(`terminal-agent state lock unavailable at ${lockPath}: ${err?.code || err}; inspect the owning process before manual recovery`);
}
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
}
}
const owned = fs.fstatSync(fd, { bigint: true });
return () => {
try {
const current = fs.statSync(lockPath, { bigint: true });
if (current.dev === owned.dev && current.ino === owned.ino) fs.unlinkSync(lockPath);
} catch (err: any) {
if (err?.code !== 'ENOENT') throw err;
} finally { fs.closeSync(fd); }
};
}
/**
* Locate the terminal-agent script on disk. In dev (cli.ts running via
* `bun run`), it lives next to this file in browse/src. In a compiled
* binary, Bun's --compile bakes the source into the executable and
* exposes it relative to process.execPath. Either path must work or
* the agent can't be spawned at all.
*/
export function resolveTerminalAgentScript(searchHints: { metaDir?: string; execPath?: string } = {}): string | null {
const meta = searchHints.metaDir || __dirname;
const exec = searchHints.execPath || process.execPath;
const candidates = [
path.resolve(meta, 'terminal-agent.ts'),
path.resolve(path.dirname(exec), '..', 'src', 'terminal-agent.ts'),
];
for (const c of candidates) {
if (fs.existsSync(c)) return c;
}
return null;
}
/**
* Spawn an owned terminal-agent. A prior record is retained until its exact
* process exits, and the new generation is recorded before it may bind.
*
* Used by both the CLI cold-start path (cli.ts) and the v1.44 watchdog in
* server.ts. Centralizing here removes a copy-paste between them and means
* spawn-env additions (BROWSE_OWNER_PID being the first) land in one place.
*/
export function spawnTerminalAgent(opts: {
stateFile: string;
serverPort: number;
/** PID of the browse server that owns this agent. */
ownerPid: number;
cwd?: string;
/** Optional extra env vars to add to the agent's process env. */
extraEnv?: Record<string, string>;
/** Override script lookup for tests. */
scriptPath?: string;
}): number | null {
if (!Number.isSafeInteger(opts.ownerPid) || opts.ownerPid <= 0) throw new Error('terminal-agent requires a daemon owner PID');
const stateDir = path.dirname(opts.stateFile);
const script = opts.scriptPath || resolveTerminalAgentScript();
if (!script || !fs.existsSync(script)) return null;
const release = acquireAgentStateLock(stateDir);
try {
const prior = readAgentRecord(stateDir);
if (prior) {
if (prior.pid === 0) {
console.warn('[browse] terminal-agent startup or failed exit remains unconfirmed; retaining its reservation');
return null;
}
if (isAgentRecordLive(prior) && !stopAgentByRecord(prior)) {
console.warn(`[browse] terminal-agent PID ${prior.pid} is still running or its identity cannot be confirmed; refusing a second agent`);
return null;
}
clearAgentRecord(stateDir, prior);
safeUnlink(path.join(stateDir, 'terminal-port'));
safeUnlink(path.join(stateDir, 'terminal-internal-token'));
}
const ownerStartTime = readAgentStartTime(opts.ownerPid);
if (!ownerStartTime) throw new Error('terminal-agent owner identity is unavailable');
const gen = crypto.randomBytes(16).toString('base64url');
const reservation: AgentRecord = { pid: 0, gen, startedAt: Date.now(), ownerPid: opts.ownerPid, ownerStartTime };
writeAgentRecord(stateDir, reservation);
let proc: any;
try {
proc = (Bun as any).spawn(['bun', 'run', script, `--agent-gen=${gen}`], {
cwd: opts.cwd || process.cwd(),
env: {
...process.env,
...(opts.extraEnv || {}),
BROWSE_STATE_FILE: opts.stateFile,
BROWSE_SERVER_PORT: String(opts.serverPort),
BROWSE_OWNER_PID: String(opts.ownerPid),
BROWSE_OWNER_START_TIME: ownerStartTime,
BROWSE_AGENT_GEN: gen,
},
stdio: ['ignore', 'ignore', 'ignore'],
windowsHide: true,
});
} catch (err) {
clearAgentRecord(stateDir, reservation);
throw err;
}
const retainUntilExit = () => {
pendingAgentExits.add(proc);
proc.exited?.then(() => {
try {
const releasePending = acquireAgentStateLock(stateDir);
try { clearAgentRecord(stateDir, reservation); } finally { releasePending(); }
} catch (err) { console.warn('[browse] terminal-agent pending exit cleanup failed:', err); }
pendingAgentExits.delete(proc);
}, (err: unknown) => console.warn('[browse] terminal-agent exit remains unconfirmed:', err));
};
const pid = proc.pid;
const startTime = pid ? readAgentStartTime(pid) : '';
if (!pid || !startTime) {
try { proc.kill('SIGTERM'); } catch {}
retainUntilExit();
throw new Error('terminal-agent process identity is unavailable');
}
const record: AgentRecord = { pid, gen, startedAt: Date.now(), startTime, ownerPid: opts.ownerPid, ownerStartTime };
try {
writeAgentRecord(stateDir, record);
} catch (err) {
if (!stopAgentByRecord(record)) {
retainUntilExit();
throw new Error(`terminal-agent record update failed and child ${pid} exit is unconfirmed: ${err}`);
}
clearAgentRecord(stateDir, reservation);
throw err;
}
proc.unref?.();
return pid;
} finally { release(); }
}
export interface AgentRecord {
pid: number;
/** Random per-boot identifier. Loopback /internal/* sees X-Browse-Gen: <gen>. */
gen: string;
/** ms since epoch. Reserved for future PID-reuse guards. */
startedAt: number;
startTime?: string;
ownerPid?: number;
ownerStartTime?: string;
}
export function agentRecordPath(stateDir: string): string {
return path.join(stateDir, 'terminal-agent-pid');
}
/** Read the current record. Returns null on missing/malformed file. */
export function readAgentRecord(stateDir: string): AgentRecord | null {
try {
const raw = fs.readFileSync(agentRecordPath(stateDir), 'utf-8');
const j = JSON.parse(raw);
if (typeof j?.pid === 'number' && typeof j?.gen === 'string' && typeof j?.startedAt === 'number') {
return j as AgentRecord;
}
return null;
} catch {
return null;
}
}
/** Atomic write (throws on failure — boot must not proceed on a bad record). */
export function writeAgentRecord(stateDir: string, record: AgentRecord): void {
try { mkdirSecure(stateDir); } catch {}
const target = agentRecordPath(stateDir);
atomicWriteSync(target, JSON.stringify(record), { mode: 0o600 });
// Windows ACL hardening (POSIX chmod is redundant with mode above).
restrictFilePermissions(target);
}
export function clearAgentRecord(stateDir: string, expected?: AgentRecord): void {
if (expected) {
const current = readAgentRecord(stateDir);
if (!current || current.pid !== expected.pid || current.gen !== expected.gen) return;
}
safeUnlink(agentRecordPath(stateDir));
}
export function isAgentRecordLive(record: AgentRecord): boolean {
return Number.isSafeInteger(record.pid) && record.pid > 0 && isProcessAlive(record.pid);
}
function agentStatus(record: AgentRecord, ownerPid?: number): 'owned' | 'gone' | 'unknown' {
if (!isAgentRecordLive(record)) return 'gone';
if (!record.startTime || !record.ownerPid || !record.ownerStartTime) return 'unknown';
if (ownerPid !== undefined && (record.ownerPid !== ownerPid || record.ownerStartTime !== readAgentStartTime(ownerPid))) return 'unknown';
const actual = agentProcessInfo(record.pid);
if (!actual.startTime) return isAgentRecordLive(record) ? 'unknown' : 'gone';
if (actual.startTime !== record.startTime) return 'gone';
try {
let state: string | undefined;
if (process.platform === 'linux') {
state = fs.readFileSync(`/proc/${record.pid}/stat`, 'utf8').match(/^\d+ \(.*\) ([A-Z])/u)?.[1];
} else if (process.platform === 'darwin') {
const result = spawnSync('ps', ['-p', String(record.pid), '-o', 'stat='], { encoding: 'utf8', windowsHide: true, timeout: 2000 });
if (result.status === 0) state = result.stdout?.trim()?.[0];
}
if (state === 'Z') return 'gone';
} catch {}
if (!isAgentRecordLive(record)) return 'gone';
return actual.commandLine.split(/\s+/).some(arg => arg.replace(/^['"]|['"]$/g, '') === `--agent-gen=${record.gen}`)
? 'owned' : 'unknown';
}
export function isOurAgent(record: AgentRecord, ownerPid?: number): boolean {
return agentStatus(record, ownerPid) === 'owned';
}
export function isAgentRecordGone(record: AgentRecord): boolean {
return agentStatus(record) === 'gone';
}
/**
* Kill the agent identified by `record`. Signal defaults to SIGTERM (give
* the agent a chance to run its own SIGTERM cleanup). Returns true if a
* signal reached an exact-generation live process, false otherwise.
*/
export function killAgentByRecord(
record: AgentRecord,
signal: NodeJS.Signals = 'SIGTERM',
): boolean {
if (!isOurAgent(record)) return false;
try { process.kill(record.pid, signal); return true; } catch { return false; }
}
export function stopAgentByRecord(record: AgentRecord, graceMs = 1000): boolean {
const initial = agentStatus(record);
if (initial === 'gone') return true;
if (initial !== 'owned') return false;
const waitForExit = (ms: number) => {
const deadline = Date.now() + ms;
while (Date.now() < deadline) {
const status = agentStatus(record);
if (status === 'gone') return true;
if (status === 'unknown') return false;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
}
return agentStatus(record) === 'gone';
};
if (!killAgentByRecord(record, 'SIGTERM')) return agentStatus(record) === 'gone';
if (waitForExit(graceMs)) return true;
const afterGrace = agentStatus(record);
if (afterGrace !== 'owned') return afterGrace === 'gone';
if (!killAgentByRecord(record, 'SIGKILL')) return agentStatus(record) === 'gone';
return waitForExit(graceMs);
}