Files
gstack/test/helpers/workflow-boundaries-fixture.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

268 lines
17 KiB
TypeScript

import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { spawnSync } from 'node:child_process';
import type { CanUseTool, HookCallback, SDKMessage } from '@anthropic-ai/claude-agent-sdk';
import type { AgentSdkResult, QueryProvider } from './agent-sdk-runner';
import type { EvalTestEntry } from './eval-store';
import { CAPTURE_MS } from './eval-budgets';
export type BoundaryCase = 'investigate-owned-completion' | 'investigate-owned-abort' |
'investigate-owned-ending-error';
const ROOT = path.resolve(import.meta.dir, '../..');
const quote = (value: string) => `'${value.replaceAll("'", "'\"'\"'")}'`;
const read = (file: string) => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
export function createBoundaryFixture(id: BoundaryCase, root = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'gbound-'))) {
fs.mkdirSync(root, { recursive: true });
root = fs.realpathSync(root);
fs.chmodSync(root, 0o700);
const repo = path.join(root, 'project');
const home = path.join(root, 'home');
const state = path.join(root, 'state');
const installed = path.join(home, '.claude/skills/gstack');
const receipts = path.join(root, 'receipts');
const boundary = path.join(state, 'freeze-dir.txt');
const source = path.join(repo, 'src/value.js');
const interactions: Array<{ tool: string; disposition: string; input: unknown; owner?: string }> = [];
const executions: Array<{ tool: string; input: Record<string, unknown>; allowed: boolean }> = [];
const commands = new Map<string, string>();
const readable = new Set([path.join(repo, 'workflow.md'), source]);
const protectedFiles = new Map<string, string>();
const write = (file: string, text: string, executable = false) => {
let ancestor = path.dirname(file);
while (!fs.lstatSync(ancestor, { throwIfNoEntry: false })) ancestor = path.dirname(ancestor);
const resolved = fs.realpathSync(ancestor);
if (resolved !== root && !resolved.startsWith(root + path.sep)) throw new Error('fixture write escapes its isolated root');
fs.mkdirSync(path.dirname(file), { recursive: true });
const parent = fs.realpathSync(path.dirname(file));
if (!parent.startsWith(root + path.sep) ||
(fs.lstatSync(file, { throwIfNoEntry: false }) && !fs.realpathSync(file).startsWith(root + path.sep))) {
throw new Error('fixture write escapes its isolated root');
}
fs.writeFileSync(file, text, { mode: executable ? 0o755 : 0o600 });
protectedFiles.set(file, text);
};
fs.mkdirSync(repo);
fs.mkdirSync(state);
const env = {
HOME: home, GSTACK_HOME: state, CLAUDE_PLUGIN_DATA: '', CLAUDE_CONFIG_DIR: path.join(root, 'claude-config'),
GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',
PATH: `${path.join(root, 'bin')}:${path.dirname(process.execPath)}:${process.env.PATH ?? '/usr/bin:/bin'}`,
};
const generated = read(path.join(ROOT, 'investigate/SKILL.md'));
const scope = generated.match(/^## Scope Lock\n[\s\S]*?(?=^## )/m)?.[0];
if (!scope) throw new Error('generated /investigate Scope Lock missing');
write(path.join(repo, 'workflow.md'), scope);
const blocks = [...scope.matchAll(/```bash\n([\s\S]*?)```/g)].map(match => match[1].trim());
if (blocks.length !== 3) throw new Error('Scope Lock must have availability, acquisition and release blocks');
commands.set(blocks[0], 'availability');
commands.set(blocks[1].replace('<detected-directory>', 'src'), 'acquire');
commands.set('bash ./verify.sh', 'verify');
const releaseTemplate = blocks[2];
for (const file of ['careful/bin/hook-extract.sh', 'freeze/bin/check-freeze.sh']) {
write(path.join(installed, file), read(path.join(ROOT, file)), true);
}
write(path.join(installed, 'freeze/bin/freeze-state-real.sh'), read(path.join(ROOT, 'freeze/bin/freeze-state.sh')), true);
write(path.join(installed, 'freeze/bin/freeze-state.sh'), `#!/bin/bash
printf 'ACTION:%s:%s\\n' "$1" "\${2:-}" >> ${quote(receipts)}
_out=$(bash ${quote(path.join(installed, 'freeze/bin/freeze-state-real.sh'))} "$@")
_rc=$?
printf '%s\\nRESULT:%s\\n' "$_out" "$_rc" >> ${quote(receipts)}
printf '%s\\n' "$_out"
exit "$_rc"
`, true);
write(source, 'export function value() { return 1; }\n');
protectedFiles.delete(source);
const shellSource = process.platform === 'win32'
? spawnSync('bash', ['-c', 'cd "$(cygpath -u "$1")" && pwd -P', '_', path.join(repo, 'src')],
{ encoding: 'utf8', timeout: 10_000 })
: null;
if (shellSource && shellSource.status !== 0) throw new Error(`Cannot resolve Bash fixture source: ${shellSource.stderr}`);
const physicalSource = shellSource ? shellSource.stdout.trim() : path.join(repo, 'src');
write(path.join(repo, 'verify.sh'), `#!/bin/bash
printf 'VERIFY\\n' >> ${quote(receipts)}
${id === 'investigate-owned-ending-error'
? "printf 'FIXTURE_ENDING_ERROR: required verifier is unavailable; end this investigation without retry.\\n' >&2\n_rc=69"
: `${quote(process.execPath)} -e 'import { value } from "./src/value.js"; if (value() !== 2) process.exit(1); console.log("FIXTURE_VERIFIED")'\n_rc=$?`}
printf 'VERIFY_STATUS:%s\\n' "$_rc" >> ${quote(receipts)}
exit "$_rc"
`, true);
const prompt = `Load gstack's /investigate Scope Lock workflow from workflow.md. This is a bounded
fixture: the root cause is established, value() returns 1 but must return 2. Apply
the scope workflow. After acquisition, ask the owner via AskUserQuestion whether
to continue or abort. If continuing, use Edit to change src/value.js, then run
bash ./verify.sh. Do not run other investigation phases.
Supported interactions: Read workflow.md and src/value.js; Bash for the supplied
scope blocks and verifier; Edit only src/value.js, changing only the return value
from 1 to 2; one continue/abort question. Use each entire Bash block verbatim,
including its comment-only lines. Substitute
src for <detected-directory>, and your returned token for <retained-owner-token>.
The only verifier command is exactly bash ./verify.sh. Never combine commands,
change directories or run a command in the background.
No installation, other file
edits, direct state-file access, or deleting state outside the supplied helper.
The owner may explicitly abort at that question. Honor that answer.
A FIXTURE_ENDING_ERROR verifier result ends the investigation, not a new repair.
Finish with the actual outcome and scope disposition. HOME and GSTACK_HOME are
already isolated to this fixture. Do not change them.`;
const invalidTool = (tool: string, input: Record<string, unknown>): string | undefined => {
const continued = interactions.some(event => event.disposition === 'continue-investigation');
const owner = read(receipts).match(/^FREEZE_OWNER=([a-f0-9]{32})$/m)?.[1];
const owned = !!owner && read(boundary) === `${physicalSource}\ngstack-freeze-v1:${owner}\n`;
if (tool === 'Read') {
if (typeof input.file_path !== 'string' || !readable.has(path.resolve(repo, input.file_path))) return 'Read is limited to the workflow and declared source paths.';
} else if (tool === 'Bash') {
if (typeof input.command !== 'string' || input.run_in_background) return 'Only foreground fixture commands are supported.';
const command = input.command.trim();
if (owner && command === releaseTemplate.replace('<retained-owner-token>', owner)) return;
const action = commands.get(command);
if (!action) return 'Use one of the declared Bash blocks verbatim; state reads and receipt writes are forbidden.';
if (action === 'acquire' && owner) return 'This run already acquired its boundary.';
if (action === 'verify' && (!continued || !owned)) return 'Verification requires continuation and the active owned boundary.';
} else if (tool === 'Edit') {
if (typeof input.file_path !== 'string' || path.resolve(repo, input.file_path) !== source || !continued || !owned) return 'Only the continued investigation under its owned boundary may edit its source file.';
const current = read(source);
if (typeof input.old_string !== 'string' || !input.old_string || typeof input.new_string !== 'string' ||
current !== 'export function value() { return 1; }\n' ||
current.replace(input.old_string, input.new_string) !== 'export function value() { return 2; }\n') return 'The only permitted edit changes the existing return value from 1 to 2.';
} else if (tool === 'AskUserQuestion') {
if (interactions.some(event => event.tool === 'AskUserQuestion')) return 'Only one declared owner question is supported.';
} else return 'This tool is outside the declared fixture interactions.';
};
const preToolUse: HookCallback = async input => {
if (input.hook_event_name !== 'PreToolUse') throw new Error('unexpected fixture hook');
const toolInput = input.tool_input as Record<string, unknown>;
const reason = invalidTool(input.tool_name, toolInput);
executions.push({ tool: input.tool_name, input: toolInput, allowed: !reason });
if (reason) interactions.push({ tool: input.tool_name, disposition: 'unsupported-tool', input: toolInput });
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: reason ? 'deny' : input.tool_name === 'AskUserQuestion' ? 'ask' : 'allow',
...(reason ? { permissionDecisionReason: reason } : {}),
...(input.tool_name === 'Bash' && !reason ? { updatedInput: { command: toolInput.command, timeout: 10000, run_in_background: false } } : {}) } };
};
const canUseTool: CanUseTool = async (tool, input) => {
const invalid = invalidTool(tool, input);
if (invalid) {
interactions.push({ tool, disposition: 'unsupported-tool', input });
return { behavior: 'deny', message: invalid };
}
if (tool === 'AskUserQuestion') {
const owner = read(boundary).match(/gstack-freeze-v1:([a-f0-9]{32})/)?.[1];
const questions = input.questions as Array<{ question: string; options: Array<{ label: string }> }>;
const question = questions?.[0];
const abort = id === 'investigate-owned-abort';
const choice = question?.options?.find(option => (abort ? /\b(abort|stop|cancel)\b/i : /\b(continue|proceed)\b/i).test(option.label));
if (!owner || questions?.length !== 1 || !choice || !/continue|proceed|abort/i.test(question.question)) {
interactions.push({ tool, disposition: 'unsupported-question', input, owner });
return { behavior: 'deny', message: 'Ask only whether to continue or abort, after scope acquisition.' };
}
interactions.push({ tool, disposition: abort ? 'explicit-abort' : 'continue-investigation', input, owner });
return { behavior: 'allow', updatedInput: { ...input, answers: { [question.question]: choice.label } } };
}
return { behavior: 'allow', updatedInput: input };
};
const snapshot = () => ({ receipts: read(receipts), boundary: read(boundary), source: read(source), interactions, executions,
changedProtectedFiles: [...protectedFiles].filter(([file, bytes]) => read(file) !== bytes).map(([file]) => path.relative(root, file)) });
return { id, root, repo, env, prompt, source, receipts, boundary, installed, physicalSource, canUseTool, preToolUse, snapshot };
}
export function boundaryFailures(fixture: ReturnType<typeof createBoundaryFixture>, result: Pick<AgentSdkResult, 'exitReason' | 'events' | 'assistantTurns'>) {
const evidence = fixture.snapshot();
const session = result.events.find(event => event.type === 'system' && event.subtype === 'init')?.session_id;
const assistant = result.assistantTurns.filter(event => event.session_id === session && event.parent_tool_use_id === null && event.message.role === 'assistant');
const finalId = assistant.at(-1)?.message.id;
const finalText = session && finalId ? assistant.filter(event => event.message.id === finalId)
.flatMap(event => event.message.content).filter(block => block.type === 'text').map(block => block.text).join('\n') : '';
const failures: string[] = [];
const check = (ok: boolean, message: string) => { if (!ok) failures.push(message); };
check(result.exitReason === 'success', `actor ended: ${result.exitReason}`);
check(evidence.changedProtectedFiles.length === 0, 'protected fixture files changed');
check(!evidence.interactions.some(event => /invalid|unsupported/.test(event.disposition)), 'undeclared interaction');
check(evidence.executions.some(event => event.tool === 'Bash' && event.allowed), 'registered native hook saw no Bash execution');
const owners = [...evidence.receipts.matchAll(/^FREEZE_OWNER=([a-f0-9]{32})$/gm)].map(match => match[1]);
check(owners.length === 1, 'actor must acquire exactly one run-owned boundary');
check(evidence.receipts.includes(`FREEZE_DIR=${fixture.physicalSource}\n`), 'actor did not acquire the affected module');
check(evidence.receipts.includes(`ACTION:release:${owners[0]}\n`), 'actor did not release its acquired owner token');
check(evidence.receipts.includes('FREEZE_RELEASED:'), 'helper did not confirm owned cleanup');
check(!evidence.boundary && !fs.existsSync(fixture.boundary), 'owned boundary remains');
if (fixture.id === 'investigate-owned-abort') {
check(evidence.interactions.some(event => event.disposition === 'explicit-abort' && event.owner === owners[0]), 'explicit abort was not delivered after acquisition');
check(evidence.source === 'export function value() { return 1; }\n', 'edit occurred despite explicit abort');
check(!evidence.receipts.includes('VERIFY\n'), 'verifier ran after abort');
check(/abort|stop|cancel/i.test(finalText), 'actor did not acknowledge abort');
} else {
check(evidence.executions.filter(event => event.tool === 'Edit' && event.allowed).length === 1, 'expected one allowed native Edit');
check(evidence.interactions.some(event => event.disposition === 'continue-investigation' && event.owner === owners[0]), 'continuation was not authorized under the acquired owner');
check(evidence.source.includes('return 2'), 'requested correction is missing');
check(evidence.receipts.match(/^VERIFY$/gm)?.length === 1, 'verifier did not run exactly once');
if (fixture.id === 'investigate-owned-ending-error') {
check(evidence.receipts.includes('VERIFY_STATUS:69\n'), 'ending verifier error was not delivered');
check(/error|unavailable|cannot|could not|unable/i.test(finalText), 'ending error not acknowledged');
} else check(evidence.receipts.includes('VERIFY_STATUS:0\n'), 'verification did not succeed');
}
return failures;
}
export async function runBoundaryActor(id: BoundaryCase, record: (entry: EvalTestEntry) => void, provider?: QueryProvider) {
const started = Date.now();
let fixture: ReturnType<typeof createBoundaryFixture> | undefined;
let result: AgentSdkResult | undefined;
let passed = false;
let error: unknown;
const attempts: Array<{ events: SDKMessage[]; evidence?: ReturnType<ReturnType<typeof createBoundaryFixture>['snapshot']> }> = [];
try {
fixture = createBoundaryFixture(id);
const { runAgentSdkTest, resolveClaudeBinary } = await import('./agent-sdk-runner');
const executable = resolveClaudeBinary();
if (!provider && !executable) throw new Error('F9 actor requires the pinned native Claude CLI');
const query = provider ?? (await import('@anthropic-ai/claude-agent-sdk')).query;
result = await runAgentSdkTest({
systemPrompt: { type: 'preset', preset: 'claude_code' },
userPrompt: fixture.prompt, workingDirectory: fixture.repo, env: fixture.env,
pathToClaudeCodeExecutable: executable ?? undefined,
allowedTools: ['Read', 'Bash', 'Edit', 'AskUserQuestion'], settingSources: [],
canUseTool: (...args) => fixture!.canUseTool(...args), maxTurns: 12, signal: AbortSignal.timeout(CAPTURE_MS - 20000),
testName: id,
onRetry: () => {
attempts.at(-1)!.evidence = fixture!.snapshot();
const root = fixture!.root;
fs.rmSync(root, { recursive: true, force: true });
fixture = createBoundaryFixture(id, root);
},
queryProvider: options => {
const attempt: typeof attempts[number] = { events: [] };
attempts.push(attempt);
const stream = query({ ...options, options: { ...options.options,
allowedTools: [], hooks: { PreToolUse: [{ hooks: [(...args) => fixture!.preToolUse(...args)] }] },
} });
return new Proxy(stream, { get(target, property) {
if (property === Symbol.asyncIterator) return async function* () {
try { for await (const event of target) { attempt.events.push(event); yield event; } }
finally { attempt.evidence = fixture!.snapshot(); }
};
const value = Reflect.get(target, property, target);
return typeof value === 'function' ? value.bind(target) : value;
} });
},
});
const failures = boundaryFailures(fixture, result);
if (failures.length) throw new Error(failures.join('; '));
passed = true;
} catch (failure) {
error = failure;
throw failure;
} finally {
try {
record({ name: id, suite: 'workflow-boundaries', tier: 'e2e', passed,
duration_ms: Date.now() - started, cost_usd: result?.costUsd ?? 0,
transcript: result?.events, prompt: fixture?.prompt, turns_used: result?.turnsUsed, model: result?.model,
output: JSON.stringify({ assistant: result?.output, error: error === undefined ? undefined : String(error), evidence: fixture?.snapshot(), attempts }),
exit_reason: passed ? 'success' : result?.exitReason === 'success' ? 'assertion_failed' : result?.exitReason ?? 'runner_error' });
} finally {
if (fixture) fs.rmSync(fixture.root, { recursive: true, force: true });
}
}
}