Files
ac20ef1e13 v1.91.16.0 fix: safe installs and upgrades, skills start everywhere, truthful completion (parallel wave) (#3014)
* fix(make-pdf,design): real TOC page numbers and anchors; design models move to gpt-5.5 + gpt-image-2 (#2903, #2807)

* ci: pin every action to a SHA, Scorecard, checksummed Bun, scoped Codex CLI in the CI image, macOS named-regressions job (#1948, #1706, #1997)

* fix(cso,browse): Windows/macOS lease identity, retention skips bad runs, truthful 'not assessed' reports, env.kv false positive, Windows browse spawn fixes (#2894, #2912, #2048, #2637, #2805)

* fix(outside-voice): one Codex model precedence for probe and dispatch, bounded timeouts with KILL escalation, probe cache identity, guarded mktemp, skills hidden in nested Codex (#2776, #2914, #2787, #2881, #2847)

* feat(setup): install registry, ./setup --status, staged activation, per-scope migrations, host tiers and conformance kit, OpenCode/Hermes fixes, Copilot CLI (experimental), disabled_skills, slimmer CLAUDE.md (#1925, #2879, #2347, #2338, #2626, #2629, #2825, #2015, #393, #1206, #2096)

Co-authored-by: Andrey Esipov <61357035+andrey-esipov@users.noreply.github.com>
Co-authored-by: Matthew Williams <5863886+ridermw@users.noreply.github.com>
Co-authored-by: Rocky Wu <92764750+lolisaigao1234@users.noreply.github.com>

* fix(preamble): skills start in worktree-isolated Claude Code sessions — one literal skill-start line, context-recovery helper, no eval in skill blocks, $N token tripwire, honest plan-mode precedence (#2763, #2896, #2851)

* fix(setup): per-install renders for renamed, vendored and custom-config installs, space-safe alias roots, per-host /cso launcher path (#1882, #2906)

* test: free tests never write the real HOME (home-write tripwire), no orphaned browse daemons, symlinked-TMPDIR (macOS) fixes, gbrain-on-PATH isolation (#2895, #2816, #2829, #2841, #2982, #2911, #2909, #2908, #2910)

* chore: integrate wave follow-ups — regenerate all hosts, README model docs, TODOS, touchfiles, duration seeds, Bun 1.3 telemetry test fix, replay fixtures pinned to their recorded bytes

* v1.91.14.0: release metadata

* test(browse): group-kill cleanup falls back to the leader when macOS returns EPERM for a live group

* ci: Codex login steps run under bash (the CI container's default sh rejects pipefail)

* fix: full-suite repairs — private state roots for 7 real-HOME writers, truthful home-guard attribution with --attribute-home, gstack-paths shim in ship-hook fixtures, Copilot in team-init probes, test-of-test detector, cookie review fixture pinned to the approved excerpt

* fix(windows): LF for Dockerfiles, normalized home-guard exclusions, path.relative fixture containment, ship push test spawn timeouts

* test(design-detect): widen the whole-scan budget test's timing margins so a loaded macOS runner can't time out the single-batch call

* fix(evals): qa protocol names defined for the judge, async PTY judge so overlapping sessions keep their cleanup deadline, bws setup cases use the standard JUDGE_MS tier

* test(pty): the non-blocking judge case is POSIX-only (its fake judge is a shebang script, like the PTY harness it covers)

* test(evals): ship-coverage-audit names absolute skill paths, uses Read, and skips the Step 7 artifact nothing consumes (removes the mechanism behind 3 of 4 historical timeouts)

* test: deflake terminal-agent concurrent startup (write the placeholder record before spawning, like the product) and qa-evidence resumed pipe (barrier on a full high-water mark instead of a sleep)

* fix(design): daemon log stream handles open errors instead of crashing the daemon; shutdown test awaits the stubbed exit

* test(evals): skillify checks the product's resolved state root (no GSTACK_HOME bypass), negative cases check every root; tpa shims live outside the agent's cwd and answer consistently

* test(evals): coverage-audit detector splits parallel columns at │ rails and [+] groups; coverage prompts name absolute skill paths; TODOs from the gate eval census

* fix(plan-eng-review): scope gate always sends the menu (no headless 'Scope pending' exit); PTY harness ends idle turn-ends and API-error panels promptly with a precise diagnostic

* test(evals): one position-bound coverage-read rule credits read-only && chains (labels, context ranges, git displays in either order) and still rejects forged output

* fix(ship): documentation section has one saved source inserted by cat (never retyped); spawned-marker evidence is the child output; refreshed codex/factory ship goldens

* test(docsync): the byte-exact insert positive is POSIX-only (the bash-command observer refuses backslash paths by design)

* test(evals): plan-design-with-ui focus-title rule accepts the comma-less 'dimensions or focus' wording (replayed on the captured CI run, negative controls kept)

* fix(qa-callers): exploratory preflight says the scope/method Reads come after exploratory.md; design-review scan check credits an executed scan proven by one engine run over the changed files

---------

Co-authored-by: Andrey Esipov <61357035+andrey-esipov@users.noreply.github.com>
Co-authored-by: Matthew Williams <5863886+ridermw@users.noreply.github.com>
Co-authored-by: Rocky Wu <92764750+lolisaigao1234@users.noreply.github.com>
2026-10-03 07:54:09 -07:00

204 lines
9.1 KiB
TypeScript

/**
* LLM judge for PTY state and snapshot logging. Moved from claude-pty-runner.ts.
* Import through test/helpers/claude-pty-runner.ts from tests; pty/ modules import siblings directly.
*/
import * as fs from 'node:fs';
import { resolveEvalModel } from '../../../lib/eval-model';
import { createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import { resolveClaudeBinary } from './binary';
// ────────────────────────────────────────────────────────────────────────────
// LLM judge — "is the model waiting for user input, working, or hung?"
//
// Regex detectors (isNumberedOptionListVisible, isProseAUQVisible) are fast
// and deterministic but brittle to PTY rendering quirks (cursor-positioning
// escapes that collapse multi-line option lists onto a single logical line).
// When they miss, the polling loop times out at the full budget — even
// though the model is correctly surfacing a question via a format the regex
// can't reassemble.
//
// This LLM judge takes a TTY snapshot and answers a trichotomy:
// - 'waiting' — agent surfaced a question/options, sitting at input prompt
// - 'working' — agent is still generating (spinner, tool calls, "Musing")
// - 'hung' — agent stopped without surfacing anything (rare)
//
// Used by polling loops as a fallback after N seconds with no terminal
// classification. On 'waiting' verdict, return outcome='asked' early.
//
// Cost: ~$0.0005 per call using claude haiku 4.5. Cached by snapshot hash so
// identical TTY frames don't re-charge. All verdicts logged to
// ~/.gstack/analytics/pty-judge.jsonl for offline analysis.
// ────────────────────────────────────────────────────────────────────────────
export interface PtyStateVerdict {
state: 'waiting' | 'working' | 'hung' | 'unknown';
reasoning: string;
/** SHA-1 of the normalized snapshot input (for caching/dedup). */
hash: string;
/** Wall time (ms) the judge call took. */
elapsedMs: number;
}
const PTY_VERDICT_CACHE = new Map<string, PtyStateVerdict>();
/**
* Persist a verdict (or snapshot dump) to the analytics JSONL log.
* Best-effort — failures (disk full, permission denied, etc.) are swallowed
* so the harness never fails on logging.
*/
function logPtyJudge(record: Record<string, unknown>): void {
try {
const dir = `${process.env.HOME}/.gstack/analytics`;
fs.mkdirSync(dir, { recursive: true });
fs.appendFileSync(`${dir}/pty-judge.jsonl`, JSON.stringify(record) + '\n');
} catch {
/* best-effort */
}
}
/**
* Snapshot dump for postmortem debugging when GSTACK_PTY_LOG=1.
* Writes the last 4KB of visible TTY plus context to
* ~/.gstack/analytics/pty-snapshots/<testName>-<elapsed>ms.txt.
*/
export function logPtySnapshot(visible: string, ctx: { testName: string; elapsedMs: number; tag?: string }): void {
if (process.env.GSTACK_PTY_LOG !== '1') return;
try {
const dir = `${process.env.HOME}/.gstack/analytics/pty-snapshots`;
fs.mkdirSync(dir, { recursive: true });
const tag = ctx.tag ? `-${ctx.tag}` : '';
const file = `${dir}/${ctx.testName}-${ctx.elapsedMs}ms${tag}.txt`;
fs.writeFileSync(
file,
`# testName: ${ctx.testName}\n# elapsedMs: ${ctx.elapsedMs}\n# tag: ${ctx.tag ?? ''}\n# visible.length: ${visible.length}\n\n${visible.slice(-4096)}`,
);
} catch {
/* best-effort */
}
}
/**
* Ask Claude Haiku 4.5 to classify a TTY snapshot as waiting/working/hung.
*
* Implementation: spawns `claude -p --model claude-haiku-4-5` synchronously
* with the prompt piped via stdin. Uses subscription auth (no API key env
* required). 30-second timeout; returns 'unknown' on any failure mode
* (timeout, malformed JSON, missing claude binary). Asynchronous: a PTY
* session sharing this process (bun --concurrent) keeps reading its terminal
* and running its close deadlines while the judge waits.
*
* Cache: identical snapshot hashes return the cached verdict without
* re-calling. Cache lives in-process; resets between test runs.
*/
export async function judgePtyState(
visible: string,
ctx?: { testName?: string },
): Promise<PtyStateVerdict> {
// Normalize: strip trailing whitespace lines + take last 4KB. Hash the
// normalized form so spinner-frame-only diffs (which all look "working")
// don't bust the cache and rack up cost.
const tail = visible.slice(-4096).replace(/[ \t]+$/gm, '');
const hash = createHash('sha1').update(tail).digest('hex').slice(0, 16);
const cached = PTY_VERDICT_CACHE.get(hash);
if (cached) return cached;
const judgeStart = Date.now();
const prompt = `You are reading a snapshot of a terminal where Claude Code is running in plan mode for an automated test. Your job: classify the agent's current state.
Pick exactly ONE:
- WAITING — agent surfaced a question or option list and is sitting at the input prompt waiting for user reply. Signs: numbered/lettered options visible (1./2./3. or A)/B)/C)), "Recommendation:" line, cursor at empty input prompt with no recent generation activity, OR a fully-rendered question + reply-instruction (e.g. "Reply with A, B, or C" / "Recommendation:") is visible.
- WORKING — agent is actively generating or running tools. Signs: spinner glyphs (✻ ✶ ✳ ✢ ✽), "Musing..." or "Churned for ..." text, recent tool-call blocks (Read/Edit/Bash/Grep), in-flight token output.
PRECEDENCE OVERRIDE: if a lettered/numbered option list (A)/B)/1./2.) AND a "Recommendation:" or "Reply with"/"Reply A" instruction are BOTH visible in this snapshot, classify WAITING even when spinner glyphs (✻ ✶ ✳ ✢ ✽) are still animating — Claude Code keeps the spinner up at an idle prose decision, so a spinner alongside a fully-rendered question + reply-instruction is a residual render artifact, not active generation.
- HUNG — agent has stopped without surfacing a question and without any spinner/work activity. Rare; usually means a crash.
Respond with strict JSON ONLY (no markdown fences, no prose):
{"state":"waiting","reasoning":"one short sentence"}
Terminal snapshot (last 4KB):
\`\`\`
${tail}
\`\`\``;
let verdict: PtyStateVerdict = {
state: 'unknown',
reasoning: 'judge call did not complete',
hash,
elapsedMs: 0,
};
try {
// Use the same binary resolution as every PTY launch in this file —
// judgePtyState previously hardcoded bare 'claude' three definitions
// below resolveClaudeBinary(), breaking under hermetic PATHs.
const result = await new Promise<{ status: number | null; stdout: string; stderr: string }>((resolve, reject) => {
const child = spawn(
resolveClaudeBinary() ?? 'claude',
['-p', '--model', resolveEvalModel('warmup'), '--max-turns', '1'],
{ stdio: ['pipe', 'pipe', 'pipe'] },
);
let stdout = '';
let stderr = '';
const timer = setTimeout(() => child.kill('SIGTERM'), 30_000);
child.stdout.setEncoding('utf-8').on('data', chunk => { stdout += chunk; });
child.stderr.setEncoding('utf-8').on('data', chunk => { stderr += chunk; });
child.stdin.on('error', () => {});
child.on('error', error => { clearTimeout(timer); reject(error); });
child.on('close', status => { clearTimeout(timer); resolve({ status, stdout, stderr }); });
child.stdin.end(prompt);
});
const elapsedMs = Date.now() - judgeStart;
if (result.status === 0 && result.stdout) {
// Pull the first {...} JSON object out of stdout. Haiku occasionally
// wraps in ```json ...``` despite the prompt; tolerate that.
const match = result.stdout.match(/\{[\s\S]*?"state"[\s\S]*?\}/);
if (match) {
try {
const parsed = JSON.parse(match[0]);
const state = ['waiting', 'working', 'hung'].includes(parsed.state)
? (parsed.state as 'waiting' | 'working' | 'hung')
: 'unknown';
verdict = {
state,
reasoning: typeof parsed.reasoning === 'string' ? parsed.reasoning.slice(0, 200) : '',
hash,
elapsedMs,
};
} catch {
verdict = { state: 'unknown', reasoning: 'malformed JSON', hash, elapsedMs };
}
} else {
verdict = { state: 'unknown', reasoning: 'no JSON in response', hash, elapsedMs };
}
} else {
verdict = {
state: 'unknown',
reasoning: `claude exited ${result.status} (${(result.stderr ?? '').slice(0, 80)})`,
hash,
elapsedMs,
};
}
} catch (err) {
verdict = {
state: 'unknown',
reasoning: `judge spawn failed: ${(err as Error).message}`.slice(0, 200),
hash,
elapsedMs: Date.now() - judgeStart,
};
}
PTY_VERDICT_CACHE.set(hash, verdict);
logPtyJudge({
ts: new Date().toISOString(),
testName: ctx?.testName ?? 'unknown',
state: verdict.state,
reasoning: verdict.reasoning,
hash: verdict.hash,
judgeMs: verdict.elapsedMs,
});
return verdict;
}