mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-26 22:51:47 +02:00
* fix: acknowledge seeded plans before invoking review skills * fix: distinguish current plan input from conversation history * fix: keep hermetic plan reviews on manual permissions * fix: distinguish tool discovery from file permission ownership * fix: preserve initial plan mode in observation tests * fix: wait for scope decisions before writing review findings * fix: carry autoplan decisions consistently into review artifacts * test: retain native failure context in periodic assertions * fix: advance active file permissions before queued questions * fix: finish red-team attempts before retry and cleanup * fix: finalize plan format captures and judges before retry * fix: cancel setup-gbrain SDK attempts before fixture cleanup * test: select periodic consumers of the bounded attempt helper * fix native Bash permission cards and queued questions * fix: preserve independent decisions and review scope Keep CEO approach, engineering scope and outside-review choices from approving independent remedies together. Carry declared contracts through DX polish and resolve new gaps before editing the plan. Regenerate every host and retain existing stop boundaries. Validation: 654 focused tests passed across nine files; all-host generation passed. Full free and periodic validation pending. Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix: require approval before design plan amendments Align the Design review philosophy and rating recipe with its section protocol: resolve one proposed fix, then apply only that approved decision and retain honest scores for declined fixes. Validation: 469 focused tests passed across four files; all-host generation passed. Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix: observe native question completion before transcript persistence Match owned completion hooks to submitted choices, reject conflicting or late answers, and retain bounded failure evidence. * test: recognize review posture in acknowledged native questions Require the selected mode acknowledgement, a completed follow-up question, and its current decoded display while preserving existing posture assertions. * fix: preserve settled CEO choices and isolate pending remedies Resolve established approach gates with cited authority and keep independent fixes out of unrelated option commitments and plan amendments. * fix: carry approved DX choices through later review steps Choose documentation approaches within the accepted scope and map resolved confusion points without reopening them through a bulk menu. * test: handle native settings-file edit prompts Keep one-time owned-file approvals and retain the actual sampled Autoplan permission frame with its matching barrier state. * test: accept standard CEO reply directives with tuning footers Recognize the exact trailing preference footer and letter-list directive while preserving current-display and exact acknowledgement checks. * test: scope split reviewers to their generated plan artifacts * test: observe native Bash permissions and invocation results * test: handle owned Bash prompts during mode preference checks * test: preserve synchronous subprocess rejection in Codex fixture * Fix periodic review handoff navigation Recognize review-first and explicit manual-next-step labels while preserving exact action families, manual preference, and ambiguous-menu rejection. Co-authored-by: OpenAI Codex <noreply@openai.com> * Bind pending file permissions to distinct current targets Allow one captured file request to own the complete current dialog while unrelated file work is pending. Preserve same-path ambiguity, exact input ownership, and one-time grant checks. Co-authored-by: OpenAI Codex <noreply@openai.com> * Make paired CEO verification choices genuinely unresolved Start the positive control with proposed manual checks so its unchanged oracle measures two new coverage decisions. Preserve runtime contracts, targets, count bounds, and all assertions. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep CEO review options and verification within approved scope Audit every offered option for independent add-ons and keep new verification depth pending until accepted. Preserve already requested coverage and trace plan changes to the actual decision. Co-authored-by: OpenAI Codex <noreply@openai.com> * Assemble DX review artifacts before appending the final report Keep early DX evidence above decisions, update artifact sections in place, and append the report using the actual current file suffix. Re-read after deleting an existing report before choosing the append anchor. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep outside plan reviews exclusive and invocation-owned Follow one preflight-selected backend, terminate failed Codex work before fallback, and allocate extra prompt/output files uniquely. Consume only the current invocation’s completed output. Co-authored-by: OpenAI Codex <noreply@openai.com> * Select periodic completion evaluations for report writer changes Register the shared review resolver for eight missing consumers and regress selection for all nine completion cases without changing their IDs or tiers. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep permission ambiguity fixtures on the same normalized target Use distinct raw spellings of one target in the four negative fixtures so they exercise the normalized duplicate-owner guard after exact current-file disambiguation. Preserve the existing exception, no-input, diagnostic and cleanup assertions. Co-authored-by: OpenAI Codex <noreply@openai.com> * Clarify preserved contracts in engineering review fixture Co-authored-by: OpenAI Codex <noreply@openai.com> * Recognize the offered DX follow-up handoff Co-authored-by: OpenAI Codex <noreply@openai.com> * Check independent commitments before presenting review options Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep Codex review output and status in one shell invocation Co-authored-by: OpenAI Codex <noreply@openai.com> * Distinguish seeded plans from reports written by a test attempt Co-authored-by: OpenAI Codex <noreply@openai.com> * Recover clipped Autoplan file approvals with bounded viewport resizing Co-authored-by: OpenAI Codex <noreply@openai.com> * Recover clipped Bash approvals before binding the complete command Co-authored-by: OpenAI Codex <noreply@openai.com> * Isolate setup message tests from the shared checkout Run the real installer in a temporary payload with private config, require successful completion, and guard source and binary contents and mtimes. Co-authored-by: OpenAI Codex <noreply@openai.com> * Fix periodic native permission and report completion handling Match the pinned CLI's soft wraps and clipped headings without granting from incomplete frames. Retire completed file requests, retain mode annotations, and ask section captures for a short final acknowledgement after their full report is saved. Co-authored-by: OpenAI Codex <noreply@openai.com> * Preserve review approvals and validate DX comparison artifacts Keep independent remedies and approved amendments explicit. Give the synthetic DX review its existing documentation and validate peer comparison as required analysis alongside four native decisions. Add positive and negative semantic calibrations while preserving review counts, model budgets and prompt size limits. Co-authored-by: OpenAI Codex <noreply@openai.com> * Make the five-finding CEO fixture's application boundary explicit Materialize the request adapter and service composition used by the synthetic payment application. Explicitly declare the revised unregistered-event and mail-telemetry assumptions while preserving uncaught handler errors, the original invoice path and all five unresolved findings. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep CEO state-path checks scoped to directory preparation Co-authored-by: OpenAI Codex <noreply@openai.com> * Use checked ports and bounded cleanup in pair-agent tests Discover the daemon port from its owned state file, retain startup diagnostics, and await failed-start cleanup. Add occupied-port, early-exit, deadline, and foreign-state regressions while preserving the existing HTTP assertions and hook budgets. Co-authored-by: Codex <noreply@openai.com> * Preserve queued edit identity and recover clipped Bash permissions Distinguish separately queued unfinished edits from mutation of one native tool ID. Keep grants bound to an exact owned request and reject reused IDs, ambiguous inputs, and competing owners. Support the pinned renderer's literal em dash and request a repaint when only the Bash card's top rule is clipped. Grants still require the complete fresh card and an exact native acknowledgment. Validation: 413 integrated parser/event tests passed; private repaint controls and joint source review passed. Full canonical suite and native periodic rerun remain pending. Co-authored-by: Codex <noreply@openai.com> * Keep periodic reviews within their approved contracts and deliverables Carry exact approvals through engineering review, preserve declared contracts when amending CEO plans, and keep prioritization at the requested decision level. Materialize the revised synthetic SDK reference contract while retaining the five original documentation gaps. Accept the observed semicolon in the finite DX handoff menu and register the direct source dependencies used by the engineering cases. Regenerate canonical review documents without changing model budgets, retries, count bands, or native completion assertions. Validation: all-host generation and 275 review, fixture, selection and parity tests passed. Full free-suite and native periodic validation remain pending. Co-authored-by: Codex <noreply@openai.com> * Keep Eng approval cadence and independence guards explicit * Accept ordinary punctuation in manual review handoffs * Recover file permissions alongside queued Bash calls * Carry approved DX work through later review findings * Clarify the synthetic auth internal failure decision * Bound the periodic DX fixture to onboarding changes * Recognize native Design review handoff labels * Hold scope in the integration-choice review fixture * Carry approved Design decisions through review evidence * Capture listener state when feedback reload fails * Exclude workspace caches before checking deprecated flags * Verify Design UI scope against a seeded review plan * Clarify plan review decisions and outside-voice approval flow * Reject setup menus in the Design UI gate * docs: require focused repair validation before final acceptance * fix: separate review commitments within existing prompt budgets * docs: align generation and contributor validation guidance * fix: advance native review prompts and count acknowledged findings * chore: bump version and changelog (v1.87.1.0) Co-Authored-By: OpenAI Codex <noreply@openai.com> * chore: enforce cheap checks and side-effect-free validation previews * fix: handle owned Fetch permissions and oversized native cards * test: ground review fixtures in independent executable contracts * fix: preserve review decisions and verify reports before completion * test: construct the synthetic credential URL without a scanner false positive * test: materialize DX examples and verify their actual local behavior * fix: clarify CEO review decisions and execution order * fix: clarify review workflow ordering and select Design quality checks * Fix review decision gates and incomplete evaluation fixtures Persist CEO and engineering commitment ledgers before menus, preserve exact approvals, and distinguish implementation structure from feature scope. Route Autoplan through the canonical CEO Step 0 ordering. Classify DX findings before requesting approval and ground runtime claims in actual evidence. Complete neutral non-target fixture contracts and accept the captured Design handoff purpose without relaxing its ownership or acknowledgment checks. Record runtime-capability verification in AGENTS.md validation discipline. Validation: 1,335 focused tests passed across 21 files; build, all-host freshness, skill validation (647 artifacts / 107 tracked), and credential checks passed. Prior paid failures are preserved; behavioral acceptance remains pending. * Fix review decision boundaries and owned Read prompts Preserve exact approvals across review options, compare consistent DX milestones, and keep proposed implementation separate from review evidence. Bind modern Read prompts to one immutable native request and wait for its result. Retain captured regression verdicts, correct fixture error names, improve import probe diagnostics, and record focused-first validation discipline in AGENTS.md. * Clarify CEO and engineering review decisions Use explicit decision steps, one engineering ledger, and clear scope/write transitions. Preserve exact approvals and distinguish pending test requirements. Keep unrelated generated content unchanged. * Fix review decision ordering and native evaluation interactions * Clarify engineering decisions and test artifact order * Clarify pending choices and approvals in CEO reviews * Make CEO review phases sequential and clarify completion * Fix Design board submission intent matching * Seed an existing browser test baseline for Autoplan * Document decision-log payloads before state initialization * Preserve exact review scope and decide one change before drafting options * Require input identity before repeating passing model judges * Honor permitted storage throughout CEO review completion * Match complete native permission text within the pinned renderer contract * Align review approvals, independent choices, and bounded validation * fix: preserve reopened approvals and declare fixture interfaces * fix: isolate review artifacts and audit complete questions * fix: match detector artifact permissions to configured storage * fix: complete native permissions and review fixture workflows * fix: order CEO review work and separate engineering guarantees * fix: preserve native validation and separate review choices * fix: clarify review decisions and judge complete report context * fix: constrain review judgments and retain parse failures * fix: compare each affected value before review decisions * fix: make engineering review decisions and completion order explicit * fix: give the complete Autoplan evaluation a bounded chain budget * fix(cso): diagnose forbidden Docker endpoints before tool lookup * fix(reviews): reconcile workflow contracts and generated artifacts after main integration * fix(evals): migrate retained regressions to the native review harness * fix(tests): close native harness and workflow integration regressions * fix(evals): preserve complete permission context and native menu contracts * fix(tests): capture synchronous command output without pipe drain stalls * fix(reviews): clarify decision and completion ordering * fix(reviews): separate decision readiness from final completion checks * refactor(reviews): consolidate decision rules and completion branches * fix(plan-eng-review): order preparation and clarify decision routing * fix(plan-eng-review): restore size and question-format guard parity * fix(plan-eng-review): clarify scope phases and blocked completion * fix(plan-eng-review): unify review flow and report destination * fix(plan-eng-review): define bootstrap and question stage ownership * fix(plan-eng-review): clarify review structure and design lookup * fix(plan-eng-review): render report examples and show saved decisions * fix: consolidate Eng review decisions and select their evaluations * test: cover overlapping terminal attachments and clean merged runner type * fix: preserve Office Hours relationship closings during review updates * fix: retain pasted review targets across slash invocations * docs: preserve validation traces and correct release scope * test: cover pasted targets in both review skills * fix: validate report artifacts before recording success * fix: redact source roots at CSO report boundaries * fix: bind native Design questions before answering * test: select report privacy and native recovery regressions * test: bind rejection predicate in extracted observers * fix: bind complete boxed native questions * test: keep the Design UI fixture on native review * fix: preserve review decisions and evaluation completion outcomes * fix: clarify CEO approval and report completion order * fix: align native review evaluation ownership and completion * fix: bind review evaluators to native decisions and owned artifacts * fix: validate review decisions against native outcomes * fix: preserve review evidence and Autoplan phase handoffs * test: bind review evidence to owned decisions and completion * fix: retain owned native history across compaction * fix(evals): validate current review decisions and setup choices * fix: bind Autoplan reviews and phase completion to current amended input * fix: reconcile native review evidence and close Autoplan phases * test: recognize owned whole-candidate complexity decisions * test: preserve report freshness for approved investigation handoffs * fix: recognize scoped review findings and isolate dual voice fixtures * fix: make review handoffs and question dispatch self-contained * test: recognize complete CEO decisions and procedural pauses * fix: bind current CEO comparison options and risk intervals * test: bind engineering decisions and completion to owned evidence * fix: publish Autoplan phase reports before continuing tools * test: verify actual Autoplan dual-review dispatch evidence * test: select dual review when shared evidence fixtures change * fix: clarify plan review decisions and completion gates * fix: make CEO review decisions and return paths explicit * test: keep Autoplan prompt files inside attempt state * test: preserve source whitespace across permission dialog wraps * fix: publish Autoplan phase reports before continuing * test: recognize current CEO comparisons and reject inactive records * fix: reconcile engineering decision states before completion * test: recognize complete Design decisions and reports * test: verify current engineering decisions before navigation * Recognize source-owned component reduction choices * fix: recognize current CEO ledger and commitment grids * test: supply RequestPolicy context to Eng count fixture * fix: save complete engineering decisions before asking * fix: bind Autoplan publication to the complete phase readback * chore: prepare 1.87.5.0 reliability release * fix: clarify engineering review completion and preserve log failures * fix: bind CEO saved choices and current section ancestry * fix(evals): bind review execution and completion evidence * fix(plan-ceo-review): verify complete decisions before asking * fix(evals): preserve complete engineering choice records * fix(evals): preserve complete review outcomes and bounded fixtures * fix(autoplan): publish phase reports before advancing * fix(plan-ceo-review): validate option fields before asking * fix(plan-eng-review): verify current decisions after answers * fix(evals): bind review decisions and bound fixture scope * fix(plan-ceo-review): verify decision rows and edit saved checkpoints * fix(evals): bind review evidence and scope document lookup * fix(plan-eng-review): update resolution state with its answer * fix(reviews): preserve complete questions through dispatch * fix(evals): recognize completed mode declarations * fix(evals): define cache consistency at wrapper completion * fix(evals): validate owned initial scope and completed review handoffs * fix: assemble complete CEO decision fields before saving * fix: authenticate automatic mode decisions without guessing selectors * fix: bind engineering coverage to approved regression contracts * fix(evals): supply review helpers to native Eng capture * fix(plan-eng-review): preserve the full selected option scope * fix(evals): recognize owned engineering seed and regression evidence * fix(evals): bind engineering retry reports to native approvals * docs: clarify release guarantees (v1.87.5.0) Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix(evals): recognize owned engineering decisions and handoffs * fix(evals): bind engineering decisions and completion evidence * fix(tests): align review contracts and selection fixtures * fix(skills): restore review prompt size limits * fix(plan-eng-review): clarify review execution and completion * fix(evals): preserve configured retries through all supervision layers * Clarify Engineering decisions and report completion * Keep native decision assertions within their source boundary * fix: recognize owned engineering decisions and completed navigation * fix: bind completed auto decisions to their current review * fix: recognize explicit CEO source attribution * fix: dispatch verified CEO decisions without recomposing fields * test: expose existing execution deadlines to review actors * fix: distinguish CEO decision records from incidental headings * test: bind split-scope choices to the registered native actor * test: connect reviewed regressions to required evaluation coverage * Clarify CEO decision routing and completion stages * test: expose existing section review deadlines to fixture actors * test: recognize complete native CEO pacing inventories * test: exclude answered history from current CEO payloads * test: detect phase entry through owned skill HOME aliases * test: validate native review completion and owned report permissions * fix: make Autoplan close packets carry the parent handoff steps * test: assess source-bound HOLD decisions within the existing deadline * fix: keep CEO native decision fields under one formatting authority * test: register integrated review and permission dependencies * test: align native review adapters and finding coverage Preserve explicit AUTO decisions, apply native single-select defaults, and bind complete cropped questions and report permissions to their owned requests. Require seeded review findings instead of crediting setup menus. Keep captured failure controls and additive selection dependencies. The integrated candidate passed 3,099 focused tests across 65 files; affected paid validation remains required before publication. * fix(autoplan): require phase reports before advancing * fix(evals): bind setup and evidence to complete attempts * fix(evals): bind native answers and pending writes to fixture scope Preserve complete option rows when native descriptions wrap, retain current owned Write arguments before journal publication, and keep engineering and DX answers within their declared fixture interfaces. Add captured free regressions without increasing model budgets or relaxing completion checks. * fix(autoplan): verify phase reports across native tool paths Guard owned methodology reads and reviewer dispatches, detect complete driver loads through Bash, and distinguish report-only edits from implementation changes. Follow authenticated native UUID ancestry when journal writes arrive out of order and verify earlier native content for cached phase reads. Keep current close acknowledgment and parent publication in order, require CEO entry before later phases, and register captured failure regressions. * fix(evals): honor native input and collection lifecycles Match complete native Edit panes and truncated question borders, reject stderr close before EOF, and stop the CEO split fixture once its acknowledged scope decisions are collected. Keep semantic validation, process failures, report requirements, and absolute deadlines authoritative. Add captured-event and real-process regressions with selection dependencies. Focused checks pass; final integrated paid and full-suite acceptance remain pending. * fix(autoplan): retain native session ownership across directory changes Recover missed native UUID ancestry through the existing strict graph while preserving ordinary event order and legacy scoping. Bind publication hooks to Claude's original project directory while retaining current cwd for requested file paths. Captured public-event regressions, existing caller checks, and a pinned native CLI loopback verify both fixes. Preserve failed attempts and require fresh paid and final full-suite acceptance. * docs: align evaluation limits and completion version * fix(autoplan): allow authenticated phase reads during journal streaming * fix(evals): bind clipped native questions and owned edit dialogs * fix: preserve overlay retries and bounded cleanup * fix: recognize owned planning preludes in native questions * docs: explain overlay scheduling and cleanup guarantees * fix: require fresh publication after Autoplan phase reruns * Release gstack 1.87.6 * fix: preserve CI paths, process identity, and test deadlines * fix: keep informational setup commands independent of install probes * fix: clarify plan review decisions and bound source audit reports * Fix remaining Windows identity and native path CI failures * Clarify CEO review decision and reviewer-result routing * test: accept no-install planner in retry supervision * fix(ceo-review): make review decisions and report completion explicit * perf(test): add fast PR gates, input-keyed judge reuse and isolated free shards * fix(test): start isolated CEO smoke from its existing project plan * fix(test): repair CI fixture races and preserve retry evidence * fix(ceo-review): clarify approvals, depth and saved completion --------- Co-authored-by: OpenAI Codex <noreply@openai.com>
681 lines
29 KiB
TypeScript
681 lines
29 KiB
TypeScript
/**
|
|
* Claude CLI subprocess runner for skill E2E testing.
|
|
*
|
|
* Spawns `claude -p` as a completely independent process (not via Agent SDK),
|
|
* so it works inside Claude Code sessions. Pipes prompt via stdin, streams
|
|
* NDJSON output for real-time progress, scans for browse errors.
|
|
*/
|
|
|
|
import * as fs from 'fs';
|
|
import * as path from 'path';
|
|
import * as os from 'os';
|
|
import { spawn } from 'child_process';
|
|
import { Readable } from 'node:stream';
|
|
import { createHash, type Hash } from 'node:crypto';
|
|
import { getProjectEvalDir } from './eval-store';
|
|
import { hermeticChildEnv, isHermeticEnabled } from './hermetic-env';
|
|
import { killProcessGroup } from '../../scripts/test-strict-output';
|
|
import { resolveEvalModel } from '../../lib/eval-model';
|
|
|
|
const GSTACK_DEV_DIR = path.join(os.homedir(), '.gstack-dev');
|
|
const HEARTBEAT_PATH = path.join(GSTACK_DEV_DIR, 'e2e-live.json'); // heartbeat stays global
|
|
const PROJECT_DIR = path.dirname(getProjectEvalDir()); // ~/.gstack/projects/$SLUG/
|
|
|
|
/** Sanitize test name for use as filename: strip leading slashes, replace / with - */
|
|
export function sanitizeTestName(name: string): string {
|
|
return name.replace(/^\/+/, '').replace(/\//g, '-');
|
|
}
|
|
|
|
/** Atomic write: write to .tmp then rename. Non-fatal on error. */
|
|
function atomicWriteSync(filePath: string, data: string): void {
|
|
const tmp = filePath + '.tmp';
|
|
fs.writeFileSync(tmp, data);
|
|
fs.renameSync(tmp, filePath);
|
|
}
|
|
|
|
export interface CostEstimate {
|
|
inputChars: number;
|
|
outputChars: number;
|
|
estimatedTokens: number;
|
|
estimatedCost: number; // USD
|
|
turnsUsed: number;
|
|
}
|
|
|
|
export interface SkillTestResult {
|
|
toolCalls: Array<{ tool: string; input: any; output: string }>;
|
|
browseErrors: string[];
|
|
exitReason: string;
|
|
duration: number;
|
|
output: string;
|
|
costEstimate: CostEstimate;
|
|
transcript: any[];
|
|
/** Which model was used for this test (added for Sonnet/Opus split diagnostics) */
|
|
model: string;
|
|
/** Time from spawn to first NDJSON line, in ms (added for rate-limit diagnostics) */
|
|
firstResponseMs: number;
|
|
/** Peak latency between consecutive tool calls, in ms */
|
|
maxInterTurnMs: number;
|
|
}
|
|
|
|
/** Local default startup grace: 90s covers observed API queue latency
|
|
* (60-90s receipts) without letting a dead API burn a 600s budget. */
|
|
export const STARTUP_GRACE_MS = 90_000;
|
|
/** CI floor (TODOS-filed): shared runners queue harder; killing startup
|
|
* before 300s in CI converts ordinary queueing into false failures.
|
|
* Pinned by test/session-runner-startup-grace.test.ts. */
|
|
export const STARTUP_GRACE_CI_FLOOR_MS = 300_000;
|
|
/** Existing pipe-drain allowance; never adds model work time. */
|
|
export const SESSION_DRAIN_GRACE_MS = 5_000;
|
|
|
|
const BROWSE_ERROR_PATTERNS = [
|
|
/Unknown command: \w+/,
|
|
/Unknown snapshot flag: .+/,
|
|
/ERROR: browse binary not found/,
|
|
/Server failed to start/,
|
|
/no such file or directory.*browse/i,
|
|
];
|
|
|
|
// --- Testable NDJSON parser ---
|
|
|
|
export interface ParsedNDJSON {
|
|
transcript: any[];
|
|
resultLine: any | null;
|
|
turnCount: number;
|
|
toolCallCount: number;
|
|
toolCalls: Array<{ tool: string; input: any; output: string }>;
|
|
}
|
|
|
|
function toolResultText(content: unknown): string | null {
|
|
if (typeof content === 'string') return content;
|
|
if (!Array.isArray(content)) return null;
|
|
return content.flatMap(block => block?.type === 'text' && typeof block.text === 'string'
|
|
? [block.text] : []).join('\n');
|
|
}
|
|
|
|
/**
|
|
* Parse an array of NDJSON lines into structured transcript data.
|
|
* Pure function — no I/O, no side effects. Used by both the streaming
|
|
* reader and unit tests.
|
|
*/
|
|
export function parseNDJSON(lines: string[]): ParsedNDJSON {
|
|
const transcript: any[] = [];
|
|
let resultLine: any = null;
|
|
let turnCount = 0;
|
|
let toolCallCount = 0;
|
|
const toolCalls: ParsedNDJSON['toolCalls'] = [];
|
|
const callsByParent = new Map<string | null, Map<string, ParsedNDJSON['toolCalls'][number]>>();
|
|
|
|
for (const line of lines) {
|
|
if (!line.trim()) continue;
|
|
try {
|
|
const event = JSON.parse(line);
|
|
transcript.push(event);
|
|
|
|
// Track turns and tool calls from assistant events
|
|
if (event.type === 'assistant') {
|
|
turnCount++;
|
|
const content = event.message?.content || [];
|
|
for (const item of content) {
|
|
if (item.type === 'tool_use') {
|
|
toolCallCount++;
|
|
const call = {
|
|
tool: item.name || 'unknown',
|
|
input: item.input || {},
|
|
output: '',
|
|
};
|
|
toolCalls.push(call);
|
|
if (typeof item.id === 'string') {
|
|
// Forwarded subagent events may reuse a parent's tool-use ID.
|
|
const parent = event.parent_tool_use_id ?? null;
|
|
let calls = callsByParent.get(parent);
|
|
if (!calls) callsByParent.set(parent, calls = new Map());
|
|
calls.set(item.id, call);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (event.type === 'user' && Array.isArray(event.message?.content)) {
|
|
const results = event.message.content.filter((item: any) => item?.type === 'tool_result');
|
|
const calls = callsByParent.get(event.parent_tool_use_id ?? null);
|
|
for (const result of results) {
|
|
const call = calls?.get(result.tool_use_id);
|
|
if (!call) continue;
|
|
// A sole Agent/Task result also carries the clean verdict separately
|
|
// from the message's agentId/usage wrapper. Keep only public text.
|
|
const verdict = results.length === 1 && ['Agent', 'Task'].includes(call.tool)
|
|
? toolResultText(event.tool_use_result?.content) : null;
|
|
call.output = verdict ?? toolResultText(result.content) ?? '';
|
|
}
|
|
}
|
|
|
|
if (event.type === 'result') resultLine = event;
|
|
} catch { /* skip malformed lines */ }
|
|
}
|
|
|
|
return { transcript, resultLine, turnCount, toolCallCount, toolCalls };
|
|
}
|
|
|
|
function truncate(s: string, max: number): string {
|
|
return s.length > max ? s.slice(0, max) + '…' : s;
|
|
}
|
|
|
|
/** Diagnostic-only projection. Partial input never becomes a complete tool call. */
|
|
function publicStreamProjection(startTime: number): (line: string) => string {
|
|
let messageId: string | undefined;
|
|
const blocks = new Map<number, { type: string; tool?: string; bytes: number; hash: Hash }>();
|
|
return (line) => {
|
|
let row: any;
|
|
try { row = JSON.parse(line); } catch {
|
|
// A truncated line may contain private reasoning or unfinished tool input.
|
|
return JSON.stringify({ type: 'public_stream_diagnostic', kind: 'unparseable_line',
|
|
elapsedMs: Date.now() - startTime, bytes: Buffer.byteLength(line) });
|
|
}
|
|
if (row === null || typeof row !== 'object' || Array.isArray(row)) {
|
|
return JSON.stringify({ type: 'public_stream_diagnostic', kind: 'non_object_line',
|
|
elapsedMs: Date.now() - startTime, bytes: Buffer.byteLength(line) });
|
|
}
|
|
if (row.type === 'stream_event') {
|
|
const event = row.event ?? {};
|
|
if (event.type === 'message_start') {
|
|
messageId = event.message?.id;
|
|
blocks.clear();
|
|
}
|
|
const index = event.index;
|
|
if (event.type === 'content_block_start' && Number.isInteger(index)) {
|
|
blocks.set(index, { type: event.content_block?.type, tool: event.content_block?.name,
|
|
bytes: 0, hash: createHash('sha256') });
|
|
}
|
|
const block = blocks.get(index);
|
|
if (event.type === 'content_block_delta' && block?.type === 'tool_use'
|
|
&& event.delta?.type === 'input_json_delta' && typeof event.delta.partial_json === 'string') {
|
|
const chunk = Buffer.from(event.delta.partial_json);
|
|
block.bytes += chunk.length;
|
|
block.hash.update(chunk);
|
|
}
|
|
const diagnostic = { type: 'public_stream_diagnostic', kind: event.type,
|
|
session_id: row.session_id, messageId, index, elapsedMs: Date.now() - startTime,
|
|
blockType: block?.type, toolName: block?.tool, deltaType: event.delta?.type,
|
|
...(block?.type === 'tool_use' ? { inputBytes: block.bytes,
|
|
inputSha256: block.hash.copy().digest('hex') } : {}),
|
|
...(event.type === 'message_delta' ? { stopReason: event.delta?.stop_reason } : {}),
|
|
};
|
|
if (event.type === 'content_block_stop') blocks.delete(index);
|
|
return JSON.stringify(diagnostic);
|
|
}
|
|
if (Array.isArray(row.message?.content)) {
|
|
row.message.content = row.message.content.map((block: any) =>
|
|
block.type === 'thinking' || block.type === 'redacted_thinking'
|
|
? { type: block.type, omitted: true } : block);
|
|
}
|
|
return JSON.stringify(row);
|
|
};
|
|
}
|
|
|
|
// --- Main runner ---
|
|
|
|
export async function runSkillTest(options: {
|
|
prompt: string;
|
|
workingDirectory: string;
|
|
maxTurns?: number;
|
|
/** Optional harness contract appended to the native system prompt. */
|
|
appendSystemPrompt?: string;
|
|
/** Opt-in section completion reserve; describes the existing entry deadline. */
|
|
completionReserveMs?: number;
|
|
/** Approval allowlist; does not restrict which tools the model can see. */
|
|
allowedTools?: string[];
|
|
/** Optional built-in tool availability. Omit to preserve the CLI defaults. */
|
|
tools?: string[];
|
|
/** Opt-in public block timing/input-size diagnostics; never completion evidence. */
|
|
publicStreamDiagnostics?: boolean;
|
|
timeout?: number;
|
|
testName?: string;
|
|
runId?: string;
|
|
/** Model to use. Defaults to the frontier eval model (overridable via EVALS_MODEL env). */
|
|
model?: string;
|
|
/** Extra env vars merged into the spawned claude -p process. Useful for
|
|
* per-test GSTACK_HOME overrides so the test doesn't have to spell out
|
|
* env setup in the prompt itself. */
|
|
env?: Record<string, string>;
|
|
/** Startup-phase deadline: if NO NDJSON byte arrives within this window,
|
|
* the run is killed EARLY with exitReason 'timeout_startup' instead of
|
|
* burning the whole work budget waiting on an API that is not answering
|
|
* (the recurring '0 turns / $0.00' class — four budget-bump receipts).
|
|
* Defaults to min(STARTUP_GRACE_MS, timeout); the CI floor is higher
|
|
* because CI queueing is real. Startup and model work share timeout;
|
|
* only pipe cleanup may use the separate SESSION_DRAIN_GRACE_MS. */
|
|
startupGraceMs?: number;
|
|
/** Cancel the owned process group when an enclosing attempt expires. */
|
|
signal?: AbortSignal;
|
|
}): Promise<SkillTestResult> {
|
|
const startTime = Date.now();
|
|
options.signal?.throwIfAborted();
|
|
const {
|
|
prompt,
|
|
workingDirectory,
|
|
maxTurns = 15,
|
|
allowedTools = ['Bash', 'Read', 'Write'],
|
|
timeout = 120_000,
|
|
testName,
|
|
runId,
|
|
env: extraEnv,
|
|
signal,
|
|
} = options;
|
|
// The CI floor is a FLOOR, not a default: an explicit startupGraceMs below
|
|
// 300s in CI would re-open the queueing-becomes-false-red hole the floor
|
|
// exists for (review finding — the name promised a clamp the code lacked).
|
|
// Local runs honor the caller verbatim; timeout still caps everything.
|
|
const requestedGrace = options.startupGraceMs ?? (process.env.CI ? STARTUP_GRACE_CI_FLOOR_MS : STARTUP_GRACE_MS);
|
|
const startupGraceMs = Math.min(
|
|
process.env.CI ? Math.max(requestedGrace, STARTUP_GRACE_CI_FLOOR_MS) : requestedGrace,
|
|
timeout,
|
|
);
|
|
const model = options.model ?? process.env.EVALS_MODEL ?? resolveEvalModel('capture');
|
|
|
|
const deadline = startTime + timeout;
|
|
const startedAt = new Date().toISOString();
|
|
let systemPrompt = options.appendSystemPrompt;
|
|
if (options.completionReserveMs !== undefined) {
|
|
const reserve = options.completionReserveMs;
|
|
if (!Number.isFinite(timeout) || timeout <= 0 || !Number.isFinite(reserve) || reserve <= 0 || reserve >= timeout) {
|
|
throw new Error('Section completion reserve must be positive and smaller than the existing work timeout');
|
|
}
|
|
if (!allowedTools.includes('Bash') || (options.tools !== undefined && !options.tools.includes('Bash'))) {
|
|
throw new Error('Section completion clock requires Bash in the declared tools and approval allowlist');
|
|
}
|
|
const notice = `Section completion clock (fixture contract):
|
|
Runner entry UTC: ${new Date(startTime).toISOString()}
|
|
Hard deadline UTC: ${new Date(deadline).toISOString()}
|
|
Completion reserve starts UTC: ${new Date(deadline - reserve).toISOString()}
|
|
Setup, CLI startup and API queueing consume this same window; it never resets.
|
|
Before source Reads and after each saved checkpoint, use Bash to run exactly \`date -u +%Y-%m-%dT%H:%M:%SZ\`. Compare that observed UTC time with the times above. When remaining time is at most ${reserve / 1000} seconds, prioritize the remaining required completion outputs and verification. No required content or gate may be skipped. If the clock read fails, report timing unavailable; do not invent remaining time or restart the deadline.`;
|
|
systemPrompt = systemPrompt ? `${systemPrompt}\n\n${notice}` : notice;
|
|
}
|
|
|
|
// Set up per-run log directory if runId is provided
|
|
let runDir: string | null = null;
|
|
const safeName = testName ? sanitizeTestName(testName) : null;
|
|
if (runId) {
|
|
try {
|
|
runDir = path.join(PROJECT_DIR, 'e2e-runs', runId);
|
|
fs.mkdirSync(runDir, { recursive: true });
|
|
} catch { /* non-fatal */ }
|
|
}
|
|
|
|
// Spawn claude -p with streaming NDJSON output. Prompt piped via stdin to
|
|
// avoid shell escaping issues. --verbose is required for stream-json mode.
|
|
const args = [
|
|
'-p',
|
|
'--model', model,
|
|
'--output-format', 'stream-json',
|
|
'--verbose',
|
|
'--dangerously-skip-permissions',
|
|
'--max-turns', String(maxTurns),
|
|
'--allowed-tools', ...allowedTools,
|
|
];
|
|
if (systemPrompt) args.push('--append-system-prompt', systemPrompt);
|
|
// --allowed-tools controls approval, including when permissions are skipped;
|
|
// only --tools removes unrelated built-ins such as Agent, Bash, and Skill.
|
|
// Keep this opt-in: existing workflow evals intentionally use CLI defaults.
|
|
if (options.tools !== undefined) args.push('--tools', options.tools.join(','));
|
|
if (options.publicStreamDiagnostics) args.push('--include-partial-messages');
|
|
// Hermetic children get zero MCP servers (no --mcp-config is passed).
|
|
// Gated on the same call-time check as the env scrub so EVALS_HERMETIC=0
|
|
// restores operator MCP along with the operator env.
|
|
if (isHermeticEnabled()) args.push('--strict-mcp-config');
|
|
|
|
// Spawn claude directly with array-form args (no shell interpolation).
|
|
// node:child_process spawn (not Bun.spawn): `detached` puts the child in
|
|
// its OWN process group, so the timeout handler can killpg the whole tree.
|
|
// Bun.spawn has no detached option, and its bare proc.kill() signalled only
|
|
// claude itself — tool subprocesses claude spawned survived as orphans
|
|
// burning shared API rate for the rest of the shard's lifetime.
|
|
// Prompt is piped via stdin to avoid temp files and shell escaping.
|
|
const childEnv = hermeticChildEnv({ GSTACK_HEADLESS: '1', ...extraEnv });
|
|
signal?.throwIfAborted();
|
|
// Entry, logging, and hermetic setup consume the same startup/work budget.
|
|
if (Date.now() >= Math.min(deadline, startTime + startupGraceMs)) {
|
|
return {
|
|
toolCalls: [], browseErrors: [], exitReason: 'timeout_startup', duration: Date.now() - startTime,
|
|
output: '', transcript: [], model, firstResponseMs: 0, maxInterTurnMs: 0,
|
|
costEstimate: { inputChars: prompt.length, outputChars: 0, estimatedTokens: 0, estimatedCost: 0, turnsUsed: 0 },
|
|
};
|
|
}
|
|
const proc = spawn('claude', args, {
|
|
cwd: workingDirectory,
|
|
// Hermetic by default (see test/helpers/hermetic-env.ts): operator
|
|
// session context (CONDUCTOR_*, CLAUDECODE, ~/.claude config, ~/.gstack)
|
|
// never reaches the child; EVALS_HERMETIC=0 restores the legacy env.
|
|
// Default GSTACK_HEADLESS=1 so eval/E2E runs classify as headless (BLOCK on an
|
|
// AskUserQuestion failure rather than emit a prose question no human reads). A
|
|
// suite exercising the INTERACTIVE prose-fallback path opts out by passing
|
|
// `env: { GSTACK_HEADLESS: '' }` — extraEnv wins because it spreads last.
|
|
env: childEnv,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
detached: process.platform !== 'win32',
|
|
});
|
|
const stdoutWeb = Readable.toWeb(proc.stdout!) as ReadableStream<Uint8Array>;
|
|
const reader = stdoutWeb.getReader();
|
|
// Exit is independent of descendant-held pipes. Both stream drains and a
|
|
// failed kill that never emits exit have a bounded completion path.
|
|
let exitCode: number | undefined;
|
|
let stdoutDone = false;
|
|
let stderrDone = false;
|
|
let stderrEnded = false;
|
|
let drainExpired = false;
|
|
let streamError: Error | undefined;
|
|
let processError: Error | undefined;
|
|
let drainTimer: ReturnType<typeof setTimeout> | undefined;
|
|
let drainDeadline = Infinity;
|
|
let releaseDrain!: () => void;
|
|
const forcedDrain = new Promise<void>(resolve => { releaseDrain = resolve; });
|
|
let releaseExit!: () => void;
|
|
const procExited = new Promise<void>(resolve => { releaseExit = resolve; });
|
|
let releaseStderr!: () => void;
|
|
const stderrClosed = new Promise<void>(resolve => { releaseStderr = resolve; });
|
|
|
|
// Two-phase timeout. Phase 1 (startup): no NDJSON byte yet — a shorter
|
|
// deadline kills a non-answering API run EARLY and names it, instead of
|
|
// the old single timer burning the full work budget to produce an opaque
|
|
// '0 turns / $0.00' failure. Phase 2 (work): armed by the read loop when
|
|
// the FIRST byte arrives, for the REMAINING budget — model work always
|
|
// stays inside timeout; pipe cleanup has a separate bounded allowance.
|
|
let stderr = '';
|
|
let exitReason = 'unknown';
|
|
let timedOut = false;
|
|
let timedOutInStartup = false;
|
|
let phaseTimer: ReturnType<typeof setTimeout>;
|
|
|
|
const closePipes = () => {
|
|
reader.cancel().catch(() => { /* already closed */ });
|
|
proc.stdin!.destroy();
|
|
proc.stdout!.destroy();
|
|
proc.stderr!.destroy();
|
|
};
|
|
const expireDrain = () => {
|
|
drainExpired ||= !stdoutDone || !stderrDone;
|
|
killProcessGroup(proc, 'SIGKILL');
|
|
closePipes();
|
|
releaseDrain();
|
|
};
|
|
const armDrain = () => {
|
|
// Exit after cancellation must not restart the five-second allowance.
|
|
drainDeadline = Math.min(drainDeadline, Date.now() + SESSION_DRAIN_GRACE_MS);
|
|
clearTimeout(drainTimer);
|
|
drainTimer = setTimeout(expireDrain, Math.max(0, drainDeadline - Date.now()));
|
|
};
|
|
|
|
const killRun = (startupPhase: boolean): void => {
|
|
// Labeling and unblocking are SEPARATE concerns: a timer firing after
|
|
// the child already exited must not relabel a real exit (auth error,
|
|
// crash) as a timeout — but it must STILL group-kill and cancel the
|
|
// reader, or an orphan holding the pipes re-creates the exact
|
|
// blocked-drain hang this runner fixed (an early `return` here was the
|
|
// bug the adversarial pass caught in the first version of this guard).
|
|
if (exitCode === undefined) {
|
|
if (!timedOut) timedOutInStartup = startupPhase;
|
|
timedOut = true;
|
|
} else drainExpired ||= !stdoutDone || !stderrDone;
|
|
// Group SIGKILL (mirrors runShardChild): claude AND every tool
|
|
// subprocess it spawned die together — a bare proc.kill() left orphans
|
|
// that inherited our stdout/stderr pipes and kept the API burning
|
|
// (observed: a 600s timeout stretching past 1400s while an orphan held
|
|
// the pipes open).
|
|
killProcessGroup(proc, 'SIGKILL');
|
|
// Belt and braces with the group kill: even if an orphan survives (EPERM
|
|
// fallback path), cancel() unblocks the read loop below.
|
|
closePipes();
|
|
armDrain();
|
|
};
|
|
const onAbort = () => killRun(false);
|
|
const onExit = (code: number | null, exitSignal: NodeJS.Signals | null) => {
|
|
exitCode = code ?? (exitSignal ? 128 + (os.constants.signals[exitSignal] ?? 0) : 1);
|
|
clearTimeout(phaseTimer);
|
|
armDrain();
|
|
releaseExit();
|
|
};
|
|
const onError = (error: Error) => {
|
|
processError = error;
|
|
stderr += error.message;
|
|
exitCode = 1;
|
|
closePipes();
|
|
releaseExit();
|
|
releaseDrain();
|
|
};
|
|
const onStderr = (chunk: string) => { stderr += chunk; };
|
|
const onStderrDone = () => { stderrDone = true; releaseStderr(); };
|
|
const onStderrEnd = () => { stderrEnded = true; onStderrDone(); };
|
|
const onStderrClose = () => {
|
|
// Close releases the drain, but only end proves stderr reached EOF.
|
|
if (!stderrEnded) streamError ??= new Error('stderr closed before EOF');
|
|
onStderrDone();
|
|
};
|
|
const onStreamError = (error: Error) => { streamError = error; };
|
|
proc.on('exit', onExit);
|
|
proc.on('error', onError);
|
|
proc.stderr!.setEncoding('utf8');
|
|
proc.stderr!.on('data', onStderr);
|
|
proc.stderr!.on('end', onStderrEnd).on('close', onStderrClose).on('error', onStreamError);
|
|
proc.stdout!.on('error', onStreamError);
|
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
phaseTimer = setTimeout(() => killRun(true), Math.max(0, startTime + startupGraceMs - Date.now()));
|
|
proc.stdin!.on('error', () => { /* exit handling reports early child failure */ });
|
|
if (signal?.aborted || Date.now() >= deadline) onAbort();
|
|
else proc.stdin!.end(prompt);
|
|
/** Called once by the read loop on the first NDJSON byte. */
|
|
const armWorkPhase = (elapsedMs: number): void => {
|
|
clearTimeout(phaseTimer);
|
|
if (exitCode === undefined && !timedOut) {
|
|
phaseTimer = setTimeout(() => killRun(false), Math.max(0, timeout - elapsedMs));
|
|
}
|
|
};
|
|
|
|
// Stream NDJSON from stdout for real-time progress
|
|
const collectedLines: string[] = [];
|
|
let liveTurnCount = 0;
|
|
let liveToolCount = 0;
|
|
let firstResponseMs = 0;
|
|
let workPhaseArmed = false;
|
|
let lastToolTime = 0;
|
|
let maxInterTurnMs = 0;
|
|
const decoder = new TextDecoder();
|
|
let buf = '';
|
|
const projectLine = options.publicStreamDiagnostics ? publicStreamProjection(startTime) : (line: string) => line;
|
|
|
|
try {
|
|
try {
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
buf += decoder.decode(value, { stream: true });
|
|
const lines = buf.split('\n');
|
|
buf = lines.pop() || '';
|
|
for (const rawLine of lines) {
|
|
if (!rawLine.trim()) continue;
|
|
const line = projectLine(rawLine);
|
|
collectedLines.push(line);
|
|
|
|
// Track time to first NDJSON line (measures latency from spawn to first Claude response)
|
|
if (!workPhaseArmed) {
|
|
// Flag, not `firstResponseMs === 0`: a first line landing in the
|
|
// same millisecond as spawn would read as "not yet seen" and leave
|
|
// the startup timer live for the whole run (claude adversarial).
|
|
workPhaseArmed = true;
|
|
firstResponseMs = Date.now() - startTime;
|
|
// First byte: startup phase over — arm the work phase for the
|
|
// REMAINING budget (total wall stays <= timeout).
|
|
armWorkPhase(firstResponseMs);
|
|
}
|
|
|
|
// Real-time progress to stderr + persistent logs
|
|
try {
|
|
const event = JSON.parse(line);
|
|
if (event.type === 'assistant') {
|
|
liveTurnCount++;
|
|
const content = event.message?.content || [];
|
|
for (const item of content) {
|
|
if (item.type === 'tool_use') {
|
|
liveToolCount++;
|
|
const now = Date.now();
|
|
const elapsed = Math.round((now - startTime) / 1000);
|
|
// Track inter-turn latency (tool call to tool call)
|
|
if (lastToolTime > 0) {
|
|
const interTurn = now - lastToolTime;
|
|
if (interTurn > maxInterTurnMs) maxInterTurnMs = interTurn;
|
|
}
|
|
lastToolTime = now;
|
|
const progressLine = ` [${elapsed}s] turn ${liveTurnCount} tool #${liveToolCount}: ${item.name}(${truncate(JSON.stringify(item.input || {}), 80)})\n`;
|
|
process.stderr.write(progressLine);
|
|
|
|
// Persist progress.log
|
|
if (runDir) {
|
|
try { fs.appendFileSync(path.join(runDir, 'progress.log'), progressLine); } catch { /* non-fatal */ }
|
|
}
|
|
|
|
// Write heartbeat (atomic)
|
|
if (runId && testName) {
|
|
try {
|
|
const toolDesc = `${item.name}(${truncate(JSON.stringify(item.input || {}), 60)})`;
|
|
atomicWriteSync(HEARTBEAT_PATH, JSON.stringify({
|
|
runId,
|
|
pid: proc.pid,
|
|
startedAt,
|
|
currentTest: testName,
|
|
status: 'running',
|
|
turn: liveTurnCount,
|
|
toolCount: liveToolCount,
|
|
lastTool: toolDesc,
|
|
lastToolAt: new Date().toISOString(),
|
|
elapsedSec: elapsed,
|
|
}, null, 2) + '\n');
|
|
} catch { /* non-fatal */ }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} catch { /* skip — parseNDJSON will handle it later */ }
|
|
|
|
// Append raw NDJSON line to per-test transcript file
|
|
if (runDir && safeName) {
|
|
try { fs.appendFileSync(path.join(runDir, `${safeName}.ndjson`), line + '\n'); } catch { /* non-fatal */ }
|
|
}
|
|
}
|
|
}
|
|
} catch (error) { streamError = error as Error; }
|
|
stdoutDone = true;
|
|
|
|
// Flush remaining buffer
|
|
if (buf.trim()) {
|
|
const line = projectLine(buf);
|
|
collectedLines.push(line);
|
|
if (options.publicStreamDiagnostics && runDir && safeName) {
|
|
try { fs.appendFileSync(path.join(runDir, `${safeName}.ndjson`), line + '\n'); } catch { /* non-fatal */ }
|
|
}
|
|
}
|
|
|
|
await Promise.race([Promise.all([procExited, stderrClosed]), forcedDrain]);
|
|
} finally {
|
|
clearTimeout(phaseTimer);
|
|
clearTimeout(drainTimer);
|
|
signal?.removeEventListener('abort', onAbort);
|
|
killProcessGroup(proc, 'SIGKILL');
|
|
closePipes();
|
|
proc.removeListener('exit', onExit);
|
|
proc.stderr!.removeListener('data', onStderr);
|
|
}
|
|
|
|
if (timedOut) {
|
|
// 'timeout_startup' = the API never sent a byte inside the grace — an
|
|
// availability problem, not a test failure worth reading transcripts
|
|
// for. Distinct so triage (and WS10's inconclusive classification) can
|
|
// key off it without receipts archaeology.
|
|
exitReason = timedOutInStartup ? 'timeout_startup' : 'timeout';
|
|
} else if (exitCode === 0) {
|
|
exitReason = drainExpired ? 'error_output_drain' : streamError ? 'error_output_stream' : 'success';
|
|
if (drainExpired) stderr += `\nOutput drain exceeded ${SESSION_DRAIN_GRACE_MS}ms after exit 0`;
|
|
else if (streamError) stderr += `\nOutput stream failed: ${streamError.message}`;
|
|
} else {
|
|
exitReason = `exit_code_${exitCode ?? 1}`;
|
|
}
|
|
|
|
const duration = Date.now() - startTime;
|
|
|
|
// Parse all collected NDJSON lines
|
|
const parsed = parseNDJSON(collectedLines);
|
|
const { transcript, resultLine, toolCalls } = parsed;
|
|
const browseErrors: string[] = [];
|
|
|
|
// Scan transcript + stderr for browse errors
|
|
const allText = transcript.map(e => JSON.stringify(e)).join('\n') + '\n' + stderr;
|
|
for (const pattern of BROWSE_ERROR_PATTERNS) {
|
|
const match = allText.match(pattern);
|
|
if (match) {
|
|
browseErrors.push(match[0].slice(0, 200));
|
|
}
|
|
}
|
|
|
|
// Native Claude uses exit 1 for its structured max-turns result. Preserve
|
|
// that existing semantic outcome only after a complete, uncancelled drain;
|
|
// success-shaped payloads must never override a process/stream failure.
|
|
const maxTurnsExit = exitCode === 1 && resultLine?.subtype === 'error_max_turns'
|
|
&& resultLine.is_error === true && !timedOut && !signal?.aborted
|
|
&& stdoutDone && stderrDone && !drainExpired && !streamError && !processError;
|
|
if (maxTurnsExit) {
|
|
exitReason = 'error_max_turns';
|
|
} else if (resultLine && exitReason === 'success') {
|
|
if (resultLine.subtype === 'success' && resultLine.is_error) {
|
|
// claude -p can return subtype=success with is_error=true (e.g. API connection failure)
|
|
exitReason = 'error_api';
|
|
} else if (resultLine.subtype === 'success' && exitCode === 0 && !timedOut) {
|
|
exitReason = 'success';
|
|
} else if (resultLine.subtype && resultLine.subtype !== 'success') {
|
|
// Preserve known subtypes like error_max_turns even if is_error is set
|
|
exitReason = resultLine.subtype;
|
|
}
|
|
}
|
|
|
|
// Save failure transcript to persistent run directory (or fallback to workingDirectory)
|
|
if (browseErrors.length > 0 || exitReason !== 'success') {
|
|
try {
|
|
const failureDir = runDir || path.join(workingDirectory, '.gstack', 'test-transcripts');
|
|
fs.mkdirSync(failureDir, { recursive: true });
|
|
const failureName = safeName
|
|
? `${safeName}-failure.json`
|
|
: `e2e-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
|
|
fs.writeFileSync(
|
|
path.join(failureDir, failureName),
|
|
JSON.stringify({
|
|
prompt: prompt.slice(0, 500),
|
|
testName: testName || 'unknown',
|
|
exitReason,
|
|
browseErrors,
|
|
duration,
|
|
turnAtTimeout: timedOut ? liveTurnCount : undefined,
|
|
lastToolCall: liveToolCount > 0 ? `tool #${liveToolCount}` : undefined,
|
|
stderr: stderr.slice(0, 2000),
|
|
result: resultLine ? { type: resultLine.type, subtype: resultLine.subtype, result: resultLine.result?.slice?.(0, 500) } : null,
|
|
}, null, 2),
|
|
);
|
|
} catch { /* non-fatal */ }
|
|
}
|
|
|
|
// Cost from result line (exact) or estimate from chars
|
|
const turnsUsed = resultLine?.num_turns || 0;
|
|
const estimatedCost = resultLine?.total_cost_usd || 0;
|
|
const inputChars = prompt.length;
|
|
const outputChars = (resultLine?.result || '').length;
|
|
const estimatedTokens = (resultLine?.usage?.input_tokens || 0)
|
|
+ (resultLine?.usage?.output_tokens || 0)
|
|
+ (resultLine?.usage?.cache_read_input_tokens || 0);
|
|
|
|
const costEstimate: CostEstimate = {
|
|
inputChars,
|
|
outputChars,
|
|
estimatedTokens,
|
|
estimatedCost: Math.round((estimatedCost) * 100) / 100,
|
|
turnsUsed,
|
|
};
|
|
|
|
return { toolCalls, browseErrors, exitReason, duration, output: resultLine?.result || '', costEstimate, transcript, model, firstResponseMs, maxInterTurnMs };
|
|
}
|