Files
gstack/test/shared-libs-revalidation-prompt.test.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

227 lines
14 KiB
TypeScript

/** Free checks for the bounded revalidation interface and native completion requirement. */
import { describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import {
createSharedInteractiveToolHandler, reviewPrompt, reviewRevalidationPrompt,
SHARED_INTERACTIVE_MAX_TURNS, SHARED_LIBS_ROOT, type SharedLibsFixture,
} from './helpers/shared-libs-eval-fixture';
import { CAPTURE_MS, CAPTURE_LONG_MS } from './helpers/eval-budgets';
const f = { root: '/fixture root', repo: '/fixture root/repo', state: '/fixture root/state',
bin: '/fixture root/bin' } as SharedLibsFixture;
const instructions = path.join(f.root, 'review-lifecycle.md');
const input = path.join(f.root, 'current-advisory.jsonl');
const source = fs.readFileSync(path.join(import.meta.dir, 'skill-e2e-shared-libs.test.ts'), 'utf8');
const helper = fs.readFileSync(path.join(import.meta.dir, 'helpers/shared-libs-eval-fixture.ts'), 'utf8');
const native = JSON.parse(fs.readFileSync(path.join(import.meta.dir,
'fixtures/shared-libs-revalidation-max-turns-public.json'), 'utf8'));
const pathsNative = JSON.parse(fs.readFileSync(path.join(import.meta.dir,
'fixtures/shared-libs-paths-max-turns-public.json'), 'utf8'));
const pathsSource = fs.readFileSync(path.join(import.meta.dir, 'skill-e2e-shared-libs-paths.test.ts'), 'utf8');
const transpile = (text: string) => new Bun.Transpiler({ loader: 'ts' }).transformSync(text);
function pathCaptureAdapter(capture: (...args: any[]) => Promise<any>) {
const start = pathsSource.indexOf('async function exerciseEligibility(');
const end = pathsSource.indexOf('\ndescribeE2E(', start);
expect(start).toBeGreaterThan(0);
expect(end).toBeGreaterThan(start);
const rows: { scenario: string; row: any }[] = [];
const removed: string[] = [];
const attempts: any[] = [];
const fixtures = new Map<string, SharedLibsFixture>();
const afterCompletion = () => { throw new Error('A non-success capture reached completion checks'); };
const exercise = new Function('deps', `const { captures, preparePathEligibilityFixture, fs, path,
reviewLifecycleInstructions, reviewPrompt, reviewRevalidationPrompt, runSharedInteractive, readRequests,
toolCommandTrace, sourceReadTrace, fixtureWorkingTree, reviewRecords, expect, CAPTURE_LONG_MS } = deps;
${transpile(pathsSource.slice(start, end))} return exerciseEligibility;`)({
captures: { runAttempt: async (name: string, kinds: string[], timeout: number, work: any) => {
attempts.push({ name, kinds, timeout });
return work({ add: (scenario: string, row: any) => rows.push({ scenario, row }) });
} },
preparePathEligibilityFixture: (kind: string) => {
const root = path.join('/fixture root', kind);
const fixture = { root, repo: path.join(root, 'repo'), state: path.join(root, 'state'),
bin: path.join(root, 'bin') } as SharedLibsFixture;
fixtures.set(kind, fixture);
return { fixture, current: { evidence_paths: ['src/retry-route.ts'] } };
},
fs: { readFileSync: () => 'authored caller', writeFileSync: () => {},
rmSync: (root: string) => { removed.push(root); } }, path,
reviewLifecycleInstructions: (fixture: SharedLibsFixture) => path.join(fixture.root, 'review-lifecycle.md'),
reviewPrompt, reviewRevalidationPrompt, runSharedInteractive: capture, readRequests: () => [],
toolCommandTrace: afterCompletion, sourceReadTrace: afterCompletion,
fixtureWorkingTree: afterCompletion, reviewRecords: afterCompletion, expect, CAPTURE_LONG_MS,
});
return { exercise, rows, removed, attempts, fixtures };
}
describe('bounded shared-code revalidation prompt', () => {
test('adds execution guidance after the complete shared prompt without supplying an answer or token', () => {
const base = reviewPrompt(f, instructions, input);
const prompt = reviewRevalidationPrompt(f, instructions, input);
expect(prompt.slice(0, base.length)).toBe(base);
const contract = prompt.slice(base.length);
expect(contract).toContain(`${SHARED_INTERACTIVE_MAX_TURNS} assistant turns`);
expect(contract).toContain(path.join(f.state, 'projects/fixture-shared-libs/.review-starts/<REVIEW_START>.json'));
expect(contract).toContain('token actually returned by --start');
expect(contract).toContain('separate, successful Read tool call or a single cat command');
expect(contract).toContain('Do not combine the record read with --start, the diff or other diagnostic commands');
expect(contract).toContain('if the read fails, retry it before proceeding');
expect(contract).not.toMatch(/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}/);
expect(contract).toContain('Batch independent required source reads');
expect(contract).toContain('Preserve every required evidence check and dependency');
expect(contract).toContain('complete, untruncated read-back');
expect(contract).toContain('same tool invocation');
expect(contract).toContain('then return the final review summary');
expect(contract).toContain('Failed persistence or verification remains a failure');
expect(contract).toContain("Late source changes still require the workflow's normal re-review");
expect(contract).not.toContain('choose Skip');
});
test('the actual revalidation capture uses the wrapper and preserves the skip actor', async () => {
const scenario = source.slice(source.indexOf("test('shared-libs-review-revalidation'"));
const marker = "'shared-libs-review-revalidation', async () => {";
const start = scenario.indexOf(marker) + marker.length;
const end = scenario.indexOf('}, result => {', start);
expect(start).toBeGreaterThan(marker.length);
expect(end).toBeGreaterThan(start);
const result = { exitReason: 'success' };
const calls: any[] = [];
const callback = transpile(`async function invokeCapture() { ${scenario.slice(start, end)} }`);
const invoke = new Function('deps', `const { f, instructions, input, reviewRevalidationPrompt, runSharedInteractive } = deps;
let questions = []; ${callback} return invokeCapture;`)({
f, instructions, input, reviewRevalidationPrompt,
runSharedInteractive: async (...args: any[]) => { calls.push(args); return { result, questions: [] }; },
});
expect(await invoke()).toBe(result);
expect(calls).toEqual([[f, 'shared-libs-review-revalidation', reviewRevalidationPrompt(f, instructions, input), 'skip']]);
const lifecycle = source.slice(source.indexOf("test('shared-libs-review-lifecycle'"), source.indexOf("test('shared-libs-review-revalidation'"));
expect(lifecycle).toContain('reviewPrompt(f, instructions, input)');
expect(lifecycle).not.toContain('reviewRevalidationPrompt(');
});
test('the actual interactive runner uses the declared existing limit without changing clocks or actor', async () => {
const start = helper.indexOf('export async function runSharedInteractive(');
expect(start).toBeGreaterThan(0);
let body = helper.slice(start).replace('export async function', 'async function');
for (const [module, replacement] of [
['./agent-sdk-runner', 'deps.sdk'], ['@anthropic-ai/claude-agent-sdk', 'deps.provider'], ['./eval-budgets', 'deps.budgets'],
]) {
expect(body).toContain(`await import('${module}')`);
body = body.replace(`await import('${module}')`, replacement);
}
let observed: any;
let shimCalls = 0;
const invoke = new Function('deps', `const { fs, path, SHARED_LIBS_ROOT, SHARED_INTERACTIVE_MAX_TURNS,
createSharedInteractiveToolHandler, installSourceShims, readRequests } = deps;
${transpile(body)} return runSharedInteractive;`)({
fs, path, SHARED_LIBS_ROOT, SHARED_INTERACTIVE_MAX_TURNS, createSharedInteractiveToolHandler,
installSourceShims: (fixture: SharedLibsFixture) => { expect(fixture).toBe(f); shimCalls++; },
readRequests: () => [], budgets: { CAPTURE_MS },
sdk: { runAgentSdkTest: async (options: any) => { observed = options; return { exitReason: 'success' }; },
passThroughNonAskUserQuestion: (_name: string, value: unknown) => ({ behavior: 'allow', updatedInput: value }),
resolveClaudeBinary: () => '/fixture/claude' },
provider: { query: () => { throw new Error('No provider may run in this free adapter'); } },
});
await invoke(f, 'shared-libs-review-revalidation', 'prompt', 'skip');
expect(shimCalls).toBe(1);
expect(observed.maxTurns).toBe(SHARED_INTERACTIVE_MAX_TURNS);
expect(observed.maxTurns).toBe(30);
expect(observed.maxRetries).toBe(0);
expect(observed.model).toBeUndefined();
expect(observed.allowedTools).toContain('AskUserQuestion');
expect(CAPTURE_MS).toBe(300_000);
expect(CAPTURE_LONG_MS).toBe(600_000);
});
test('actual recordCapture rejects native max-turns even after verified CURRENT persistence', async () => {
const persisted = JSON.parse('{' + native.events.at(-1).message.content[0].content);
expect(persisted.completed).toBe(true);
expect(persisted.converged).toBe(true);
expect(persisted.review_binding.state).toBe('verified');
expect(persisted.review_freshness.status).toBe('CURRENT');
expect(native.terminal.subtype).toBe('error_max_turns');
const start = source.indexOf('async function recordCapture(');
const end = source.indexOf('\nfunction assertReadOnly(', start);
expect(start).toBeGreaterThan(0);
expect(end).toBeGreaterThan(start);
const recordCapture = new Function('expect', `${transpile(source.slice(start, end))} return recordCapture;`)(expect);
const rows: any[] = [];
let verified = false;
const result = { exitReason: native.terminal.subtype, turnsUsed: native.terminal.num_turns,
durationMs: native.terminal.duration_ms, events: [...native.events, native.terminal],
toolCalls: native.events.filter((event: any) => event.type === 'assistant')
.flatMap((event: any) => event.message.content.map((block: any) => ({ tool: block.name, input: block.input }))) };
await expect(recordCapture({ add: (scenario: string, row: any) => rows.push({ scenario, row }) }, 'secondary',
'shared-libs-review-revalidation', async () => result, () => { verified = true; })).rejects.toThrow();
expect(verified).toBe(false);
expect(rows).toHaveLength(1);
expect(rows[0].row.passed).toBe(false);
expect(rows[0].row.exit_reason).toBe('error_max_turns');
expect(rows[0].row.turns_used).toBe(31);
expect(rows[0].row.transcript).toContainEqual(native.terminal);
expect(rows[0].row.transcript).toContainEqual(native.events.at(-1));
});
test.each([
['shared-libs-review-path-eligibility', ['symlinks', 'submodule', 'ignored']],
['shared-libs-review-index-flags', ['assume-unchanged', 'skip-worktree']],
['shared-libs-review-prior-coverage', ['legacy', 'removed-filter']],
] as const)('the actual %s callback supplies the existing bounded interface to every scenario', async (name, kinds) => {
const calls: any[][] = [];
const adapter = pathCaptureAdapter(async (...args: any[]) => {
calls.push(args);
throw new Error('Free capture boundary reached');
});
await expect(adapter.exercise(name, [...kinds])).rejects.toThrow('Free capture boundary reached');
expect(adapter.attempts).toEqual([{ name, kinds: [...kinds], timeout: CAPTURE_LONG_MS }]);
expect(calls).toHaveLength(kinds.length);
for (const kind of kinds) {
const fixture = adapter.fixtures.get(kind)!;
const expected = reviewRevalidationPrompt(fixture, path.join(fixture.root, 'review-lifecycle.md'),
path.join(fixture.root, 'current-advisory.jsonl'))
+ '\nAll named caller sources are first-party authored runtime code. Inspect them directly, including any Git/path boundary, before deciding whether the previous review decision can be reused. The fixture contains no generated caller sources.';
expect(calls.find(call => call[0] === fixture)).toEqual([fixture, name, expected, 'skip']);
expect(adapter.rows.find(row => row.scenario === kind)?.row.passed).toBe(false);
expect(adapter.removed).toContain(fixture.root);
}
});
test('the actual path callback rejects max-turns after a correctly answered native Skip', async () => {
const question = pathsNative.events[0].message.content[0];
const answer = pathsNative.events[1].message.content[0];
expect(question.name).toBe('AskUserQuestion');
expect(answer.tool_use_id).toBe(question.id);
expect(answer.is_error).not.toBe(true);
expect(answer.content).toContain('="Skip".');
expect(pathsNative.terminal).toMatchObject({ subtype: 'error_max_turns', is_error: true, num_turns: 31 });
const questions: any[] = [];
const answers: any[] = [];
const adapter = pathCaptureAdapter(async (_fixture, _name, _prompt, choose) => {
const permission = createSharedInteractiveToolHandler(choose, {
nonQuestion: () => { throw new Error('Only the captured native question is expected'); },
onQuestion: input => { questions.push(input); },
onAnswer: (_input, values) => { answers.push(values); },
});
const decision = await permission(question.name, question.input);
expect(decision).toEqual({ behavior: 'allow', updatedInput: { ...question.input,
answers: { [question.input.questions[0].question]: 'Skip' } } });
return { questions, result: { exitReason: pathsNative.terminal.subtype,
turnsUsed: pathsNative.terminal.num_turns, durationMs: pathsNative.terminal.duration_ms,
costUsd: pathsNative.terminal.total_cost_usd, costKnown: true,
events: [...pathsNative.events, pathsNative.terminal],
toolCalls: [{ tool: question.name, input: question.input }], output: '' } };
});
await expect(adapter.exercise('shared-libs-review-index-flags', ['skip-worktree'])).rejects.toThrow('error_max_turns');
expect(answers).toEqual([{ [question.input.questions[0].question]: 'Skip' }]);
expect(adapter.rows).toHaveLength(1);
expect(adapter.rows[0]).toMatchObject({ scenario: 'skip-worktree', row: {
passed: false, exit_reason: 'error_max_turns', turns_used: 31,
} });
expect(adapter.rows[0].row.transcript).toContainEqual(pathsNative.terminal);
expect(adapter.rows[0].row.transcript).toContainEqual(pathsNative.events[1]);
expect(adapter.removed).toEqual([adapter.fixtures.get('skip-worktree')!.root]);
});
});