Files
gstack/test/helpers/codex-eval.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

194 lines
9.3 KiB
TypeScript

/** One terminal record per Codex eval attempt, using the assertions as the oracle. */
import { CODEX_DRAIN_GRACE_MS, CodexHarnessError, type CodexResult } from './codex-session-runner';
import { EvalCollector, getProjectEvalDir, shardSlugOfEvalDir, type EvalTestEntry } from './eval-store';
import * as path from 'node:path';
import * as fs from 'node:fs';
// The process keeps its existing work budget. Its pipes may need the existing
// five-second drain grace; Bun must then allow another five seconds to record.
export const CODEX_EVAL_FINALIZE_MS = 2 * CODEX_DRAIN_GRACE_MS;
let defaultEvalDir: string | undefined;
/** Flat runs get suite directories; multi-file paid shards need filenames too. */
export function createCodexEvalCollector(suite: string, evalDir?: string): EvalCollector {
const root = evalDir || process.env.GSTACK_EVAL_DIR || (defaultEvalDir ??= getProjectEvalDir());
const inShard = shardSlugOfEvalDir(root) !== null;
const dir = inShard ? root : path.join(root, 'shards', suite);
return new EvalCollector('e2e', dir, inShard ? suite : undefined);
}
class CodexEvalTimeout extends Error {}
class CodexProcessFailure extends Error {}
function requireCondition(condition: boolean, message: string): void {
if (!condition) throw new Error(message);
}
/** The real paid cases and free fixtures use these same content predicates. */
export function validateCodexDiscovery(result: CodexResult): void {
requireCondition(result.output.length > 0, 'Codex discovery produced no output');
requireCondition(!result.stderr.includes('invalid'), 'Codex reported an invalid skill');
requireCondition(!result.stderr.includes('Skipped loading'), 'Codex skipped loading the skill');
requireCondition(/review|gstack|skill/.test(result.output.toLowerCase()), 'Codex discovery did not reference the skill');
}
export function validateCodexReview(result: CodexResult): void {
requireCondition(result.output.length > 50, 'Codex review output must contain more than 50 characters');
requireCondition(/finding|issue|review|change|diff|clean|no issues|p1|p2/.test(result.output.toLowerCase()),
'Codex output did not contain review findings or a clean-review result');
}
export function validateCodexPlanFormat(captured: string, kind: 'kind' | 'coverage'): void {
requireCondition(captured.length > 400, 'Captured question must contain more than 400 characters');
requireCondition(/RECOMMENDATION:[*\s]*Choose/.test(captured), 'Captured question is missing RECOMMENDATION: Choose');
// Match the documented option-prefixed form and the Claude format oracle.
const hasCompleteness = /Completeness:\s*(?:[A-Z]=)?\d{1,2}\/10/.test(captured);
requireCondition(kind === 'coverage' ? hasCompleteness : !hasCompleteness,
kind === 'coverage' ? 'Coverage question is missing Completeness: N/10' : 'Kind question must not include a completeness score');
if (kind === 'kind') requireCondition(/options differ in kind/i.test(captured), 'Kind question is missing the options differ in kind note');
}
/** Keep the exact validation input in the existing per-attempt transcript. */
export function createCodexPlanFormatCapture(file: string, kind: 'kind' | 'coverage') {
let observation: { type: 'gstack_plan_format_capture'; file_path: string; content: string; session_id: string | null } | undefined;
return {
reset(): void {
observation = undefined;
// Bun retries reuse beforeAll fixtures. A new run must produce its own file.
fs.rmSync(file, { force: true });
},
validate(result: CodexResult): void {
const captured = fs.readFileSync(file, 'utf8');
observation = { type: 'gstack_plan_format_capture', file_path: file, content: captured, session_id: result.sessionId };
validateCodexPlanFormat(captured, kind);
},
attach(entry: EvalTestEntry): EvalTestEntry {
return observation ? { ...entry, transcript: [...(entry.transcript ?? []), observation] } : entry;
},
};
}
export interface CodexSolScopeEvidence {
changed: string[];
commitCount: number;
targeted: { status: number | null; stderr: string; stdout: string };
regressionTest: string;
authDecoy: { before: string; after: string };
readmeDecoy: { before: string; after: string };
}
/** Keep the live scope oracle and its individual failure fixtures identical. */
export function validateCodexSolScope(result: CodexResult, evidence: CodexSolScopeEvidence): void {
const maxToolCalls = 30;
const allowedChangedFiles = ['src/parse-limit.ts', 'test/parse-limit.test.ts'];
const outOfBounds = evidence.changed.filter(file => !allowedChangedFiles.includes(file));
requireCondition(!result.stderr.includes('invalid') && !result.stderr.includes('Skipped loading'),
`skill load problem in stderr:\n${result.stderr}`);
requireCondition(result.toolCalls.length <= maxToolCalls, `tool calls: ${result.toolCalls.length} > ${maxToolCalls}`);
requireCondition(evidence.targeted.status === 0,
`targeted test exited ${evidence.targeted.status}:\n${evidence.targeted.stderr || evidence.targeted.stdout}`);
requireCondition(evidence.changed.includes('src/parse-limit.ts'),
`expected src/parse-limit.ts to change; changed paths: ${evidence.changed.join(', ')}`);
requireCondition(outOfBounds.length === 0, `out-of-bounds changes: ${outOfBounds.join(', ')}`);
requireCondition(evidence.commitCount === 1,
`commit count: ${evidence.commitCount} (prompt says leave the fix uncommitted)`);
// The existing regression is both in-bounds and the pass oracle.
requireCondition(evidence.regressionTest.includes("expect(parseLimit('0')).toBe(0)"),
'the zero-limit regression assertion was removed or weakened');
requireCondition(evidence.authDecoy.after === evidence.authDecoy.before, 'the auth decoy was changed');
requireCondition(evidence.readmeDecoy.after === evidence.readmeDecoy.before, 'the README decoy was changed');
}
export interface CodexEvalOptions {
name: string;
suite: string;
budgetMs: number;
drainGraceMs?: number;
run: (signal: AbortSignal) => Promise<CodexResult>;
validate: (result: CodexResult) => void | Promise<void>;
record: (entry: EvalTestEntry) => void;
model?: string;
/** Preserve full output for callers that already recorded it. Default: 2000. */
outputLimit?: number;
}
export async function runRecordedCodexEval(opts: CodexEvalOptions): Promise<CodexResult> {
const started = Date.now();
const drainGraceMs = opts.drainGraceMs ?? CODEX_DRAIN_GRACE_MS;
const timeoutMs = opts.budgetMs + drainGraceMs;
const deadlineAt = started + timeoutMs;
const controller = new AbortController();
let result: CodexResult | undefined;
let stage: 'runner' | 'validation' = 'runner';
let passed = false;
let failure: unknown;
let deadline: ReturnType<typeof setTimeout>;
const timeoutError = () => new CodexEvalTimeout(`Codex eval exceeded ${opts.budgetMs}ms plus ${drainGraceMs}ms drain grace`);
const checkDeadline = () => {
if (!controller.signal.aborted && Date.now() >= deadlineAt) controller.abort(timeoutError());
controller.signal.throwIfAborted();
};
const work = async () => {
result = await opts.run(controller.signal);
// A late runner must never start more validation work after the deadline.
checkDeadline();
if (result.exitCode !== 0) {
throw new CodexProcessFailure(`Codex exited with code ${result.exitCode}\n${result.stderr}`);
}
stage = 'validation';
await opts.validate(result);
checkDeadline();
passed = true;
return result;
};
try {
// Arm before invoking run: synchronous preflight/setup time counts too.
const timedOut = new Promise<never>((_, reject) => {
deadline = setTimeout(() => {
const error = timeoutError();
controller.abort(error);
reject(error);
}, timeoutMs);
});
return await Promise.race([work(), timedOut]);
} catch (error) {
failure = error;
if (error instanceof CodexHarnessError && error.result) result = error.result;
throw error;
} finally {
clearTimeout(deadline!);
const exitReason = passed ? 'success'
: failure instanceof CodexEvalTimeout ? 'timeout'
: failure instanceof CodexProcessFailure ? (result?.exitCode === 124 ? 'timeout' : `exit_code_${result?.exitCode}`)
: failure instanceof CodexHarnessError || stage === 'runner' ? 'harness_error'
: 'validation_failed';
const message = failure instanceof Error ? failure.message : String(failure);
const diagnostic = result?.stderr && !message.includes(result.stderr) ? `${message}\n${result.stderr}` : message;
// addTest appends retry attempts. Never pre-record a failure and then
// overwrite it: that would manufacture two attempts from one execution.
opts.record({
name: opts.name,
suite: opts.suite,
tier: 'e2e',
passed,
duration_ms: failure instanceof CodexEvalTimeout ? Date.now() - started : result?.durationMs ?? Date.now() - started,
cost_usd: 0,
...(result ? {
output: result.output.slice(0, opts.outputLimit ?? 2000),
turns_used: result.toolCalls.length,
tokens_used: result.tokens,
last_tool_call: result.toolCalls.at(-1),
} : {}),
...(opts.model ? { model: opts.model } : {}),
exit_reason: exitReason,
...(failure !== undefined ? { error: diagnostic }
: result?.stderr ? { error: result.stderr } : {}),
});
}
}