Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript

Stop six gstack tests from failing at random in CI (GST-3852) (#4830)

Garry Tan959df8ccc4b7
diff --git a/changelog.d/flaky-fixes-2026-11-25.md b/changelog.d/flaky-fixes-2026-11-25.md
new file mode 100644
index 000000000..2af7abfe9
--- /dev/null
+++ b/changelog.d/flaky-fixes-2026-11-25.md
@@ -0,0 +1 @@
+**Six tests that failed at random now pass reliably.** The plan review floor checks read their small classifier's answer as schema-checked structured output with no tools, so a stray character after the JSON (seen twice on 2026-11-25) or a tool call it was never meant to make no longer fails the case. The QA caller evals tell the model to read HANDOFF.md with the Read tool, not `cat`. The bootstrap retention, docsync seeded-attempt, autoplan guard-line and QA caller fixture tests get time budgets that fit their work on a busy machine, including local `bun test` runs at Bun's 5 second default.
diff --git a/test/bootstrap-retention-shard.test.ts b/test/bootstrap-retention-shard.test.ts
index 2340991bf..fd11704a8 100644
--- a/test/bootstrap-retention-shard.test.ts
+++ b/test/bootstrap-retention-shard.test.ts
@@ -26,7 +26,7 @@ describe.skipIf(process.platform !== 'linux')('bootstrap paid-shard cleanup inte
const result = gitArgvIn(root,args,5000);
if (result.status !== 0) throw new Error('fixture Git seed failed');
}
- const retention = registerBootstrapRetention(root,process.env.EVALS_RUN_ID!,{deadline:Date.now()+5000});
+ const retention = registerBootstrapRetention(root,process.env.EVALS_RUN_ID!,{deadline:Date.now()+15000});
fs.appendFileSync(${JSON.stringify(path.join(root, 'attempts.jsonl'))},JSON.stringify({attempt,root,artifact:retention.artifact})+'\\n');
fs.writeFileSync(path.join(root,'bun.lock'),'exact synthetic installed lock\\n');
fs.mkdirSync(path.join(root,'node_modules','synthetic'),{recursive:true});
@@ -41,7 +41,7 @@ describe.skipIf(process.platform !== 'linux')('bootstrap paid-shard cleanup inte
try {
if (${JSON.stringify(scenario)} === 'retry' && attempt === 1) throw new Error('original synthetic assertion failure');
} finally { retention.cleanup(); }
- },10000);
+ },20000);
`);
const controllerScript = path.join(root, 'controller.ts');
const outcomePath = path.join(root, 'outcome.json');
@@ -49,15 +49,15 @@ describe.skipIf(process.platform !== 'linux')('bootstrap paid-shard cleanup inte
import * as fs from 'node:fs';
import { runPaidShard } from ${JSON.stringify(path.join(import.meta.dir, '../scripts/test-paid-shards.ts'))};
const outcome = await runPaidShard(['test/skill-e2e-qa-workflow.test.ts'], 1, 1, {
- rootDir: ${JSON.stringify(path.join(import.meta.dir, '..'))}, timeoutMs: 12000, jobs: 2, logDir: ${JSON.stringify(root)},
+ rootDir: ${JSON.stringify(path.join(import.meta.dir, '..'))}, timeoutMs: 45000, jobs: 2, logDir: ${JSON.stringify(root)},
evalDirBase: ${JSON.stringify(path.join(root, 'artifacts'))}, log: line => console.log(line),
env: { PATH: process.env.PATH, GSTACK_CLAUDE_CLI_VERSION: 'synthetic-no-provider', EVALS_RUN_ID: 'integration-run' },
- commandFor: () => ({ command: process.execPath, args: ['test', ${JSON.stringify(script)}, '--retry', ${JSON.stringify(scenario === 'retry' ? '1' : '0')}, '--timeout', '10000'] }),
+ commandFor: () => ({ command: process.execPath, args: ['test', ${JSON.stringify(script)}, '--retry', ${JSON.stringify(scenario === 'retry' ? '1' : '0')}, '--timeout', '20000'] }),
});
fs.writeFileSync(${JSON.stringify(outcomePath)}, JSON.stringify(outcome), { mode: 0o600 });
`);
const controller = spawnSync(process.execPath, [controllerScript], {
- cwd: root, encoding: 'utf8', timeout: 20000,
+ cwd: root, encoding: 'utf8', timeout: 60000,
});
fs.writeFileSync(path.join(root, 'controller.stdout.log'), controller.stdout ?? '', { mode: 0o600 });
fs.writeFileSync(path.join(root, 'controller.stderr.log'), controller.stderr ?? '', { mode: 0o600 });
@@ -86,5 +86,5 @@ describe.skipIf(process.platform !== 'linux')('bootstrap paid-shard cleanup inte
}
}
} finally { fs.rmSync(root, { recursive: true, force: true }); }
- }, 30000);
+ }, 90000);
});
diff --git a/test/docsync-fault-interface.test.ts b/test/docsync-fault-interface.test.ts
index fe6c05337..25251d573 100644
--- a/test/docsync-fault-interface.test.ts
+++ b/test/docsync-fault-interface.test.ts
@@ -399,7 +399,7 @@ test('seeded attempt 1 runs the real prepare and dispatch, saves verbatim output
try {
expect(() => seedDocsFirstAttempt(missing, installDocsActor(missing, 'missing-asset'))).toThrow('seeded attempt requires installed document-release/sections/audit-scope.md');
} finally { missing.clean(); }
-});
+}, 30_000);
test('legacy completion is deterministic data with a real preserved partial edit, not instructions to a model', () => {
const fixture = fixtureDocs('legacy');
diff --git a/test/gstack-skill-start.test.ts b/test/gstack-skill-start.test.ts
index 40250b225..77ab9dccc 100644
--- a/test/gstack-skill-start.test.ts
+++ b/test/gstack-skill-start.test.ts
@@ -402,7 +402,7 @@ describe('gstack-skill-start behavior', () => {
for (const env of matrix) expect({ env, line: line(env) }).toEqual({ env, line: [autoplanGuardLine(env, ROOT)] });
expect(line({ CLAUDECODE: '1', GSTACK_ACTIVE_HOST: 'codex', GSTACK_SESSION_KIND: 'unattended' })).toEqual([GUARD_NOT_INSTALLED_LINE]);
expect(runStart(['--skill', 'review'], { CLAUDECODE: '1' })).not.toContain('autoplan guard:');
- });
+ }, 60_000);
test('unattended block promises GSTACK_RESULT only to skills that write it; the rest name their record (#3281)', () => {
const block = (skill: string) => {
diff --git a/test/helpers/claude-pty-runner.runners.unit.test.ts b/test/helpers/claude-pty-runner.runners.unit.test.ts
index 1b4718ee6..a788a9483 100644
--- a/test/helpers/claude-pty-runner.runners.unit.test.ts
+++ b/test/helpers/claude-pty-runner.runners.unit.test.ts
@@ -228,7 +228,10 @@ describe('runPlanSkillFloorCheck through the fake driver', () => {
const screen = plan.replace('●API Error:', `${prose.replace(/\n/g, '\r\n')}\r\n●API Error:`);
const stubDir = fs.mkdtempSync(path.join(os.tmpdir(), 'floor-judge-stub-'));
const stub = path.join(stubDir, 'claude');
- fs.writeFileSync(stub, '#!/bin/sh\ncat >/dev/null\necho \'{"kind":"finding","seedId":"seed-1","questionId":"prose-1","optionId":"prose-1","reason":"the stub judge credits the staged prose question"}\'\n', { mode: 0o755 });
+ const answer = { kind: 'finding', seedId: 'seed-1', questionId: 'prose-1', optionId: 'prose-1', reason: 'the stub judge credits the staged prose question' };
+ const events = [{ type: 'assistant', parent_tool_use_id: null, message: { content: [{ type: 'tool_use', id: 'toolu_stub', name: 'StructuredOutput', input: answer }] } },
+ { type: 'user', parent_tool_use_id: null, message: { content: [{ type: 'tool_result', tool_use_id: 'toolu_stub', content: 'Structured output provided successfully' }] } }];
+ fs.writeFileSync(stub, `#!/bin/sh\ncat >/dev/null\ncat <<'EOF'\n${events.map(event => JSON.stringify(event)).join('\n')}\nEOF\n`, { mode: 0o755 });
const saved = process.env.BROWSE_TERMINAL_BINARY;
process.env.BROWSE_TERMINAL_BINARY = stub;
try {
diff --git a/test/helpers/plan-floor-review.ts b/test/helpers/plan-floor-review.ts
index 3353e8535..d08d33fe4 100644
--- a/test/helpers/plan-floor-review.ts
+++ b/test/helpers/plan-floor-review.ts
@@ -212,7 +212,58 @@ function deterministicPlanFloorFinding(input: PlanFloorReview): PlanFloorAssessm
* max 31.3s, so the old 30s cap cut the tail. 90s is about 3x p95. */
export const PLAN_FLOOR_ASSESSMENT_CAP_MS = 90_000;
-/** Same warmup CLI and one turn as the replaced waiting-state judge.
+/** The CLI validates StructuredOutput against this schema, so a stray glyph in
+ * free text (runs 45524715090 and 45586644143 ended `"reason":"…","}`) cannot
+ * reach the parser. resolvePlanFloorCitations still checks every key and ID. */
+const PLAN_FLOOR_ASSESSMENT_SCHEMA = JSON.stringify({
+ type: 'object', additionalProperties: false, required: ['kind', 'seedId', 'questionId', 'optionId', 'reason'],
+ properties: {
+ kind: { type: 'string', enum: ['finding', 'setup', 'unrelated', 'uncertain'] },
+ seedId: { type: ['string', 'null'] }, questionId: { type: ['string', 'null'] }, optionId: { type: ['string', 'null'] },
+ reason: { type: 'string' },
+ },
+});
+
+/** The first StructuredOutput call the CLI accepted is the assessment. A call
+ * the CLI rejects (an extra "metadata" key in a local replay) is no assessment,
+ * so the second turn lets the model resend the same answer in the schema; the
+ * CLI may then end at its turn limit (exit 1, error_max_turns) after accepting it. The
+ * CLI's own result keeps the last call, and the model can call it again after
+ * committing (a local replay saw a second call replace a finding with "Placeholder"). */
+function firstStructuredAssessment(stream: string): unknown {
+ const calls = new Map<string, unknown>();
+ for (const line of stream.split('\n')) {
+ if (!line.trim()) continue;
+ const event = JSON.parse(line) as { type?: string;
+ message?: { content?: Array<{ type?: string; id?: string; name?: string; input?: unknown; tool_use_id?: string; is_error?: boolean }> } };
+ for (const block of event.message?.content ?? []) {
+ if (event.type === 'assistant' && block.type === 'tool_use' && block.name === 'StructuredOutput' && block.id)
+ calls.set(block.id, block.input);
+ if (event.type === 'user' && block.type === 'tool_result' && !block.is_error && calls.has(block.tool_use_id ?? ''))
+ return calls.get(block.tool_use_id!);
+ }
+ }
+ throw Error('Floor assessment returned no accepted structured output');
+}
+
+/** The logged stream keeps the assessment alone: StructuredOutput calls, their results and the CLI's
+ * result event, never the init event, other text or any other tool's output. */
+function assessmentEvents(stream: string): string {
+ const calls = new Set<string>();
+ return stream.split('\n').flatMap(line => {
+ let event: { type?: string; message?: { content?: Array<{ type?: string; id?: string; name?: string; tool_use_id?: string }> } };
+ try { event = JSON.parse(line); } catch { return []; }
+ if (event?.type === 'result') return [line];
+ if (event?.type !== 'assistant' && event?.type !== 'user') return [];
+ const content = (event.message?.content ?? []).filter(block => {
+ if (event.type === 'assistant' && block.type === 'tool_use' && block.name === 'StructuredOutput' && block.id) return calls.add(block.id);
+ return event.type === 'user' && block.type === 'tool_result' && calls.has(block.tool_use_id ?? '');
+ });
+ return content.length ? [JSON.stringify({ ...event, message: { ...event.message, content } })] : [];
+ }).join('\n');
+}
+
+/** Same warmup CLI and prompt as the replaced waiting-state judge, with no tools; the answer arrives as validated structured output.
* The original case deadline bounds each call; complete input is never truncated. */
export function judgePlanFloorReview(input: PlanFloorReview, opts: {
binary: string; model: string; deadlineAt: number;
@@ -230,13 +281,18 @@ export function judgePlanFloorReview(input: PlanFloorReview, opts: {
}
try {
const result = (opts.invoke ?? spawnSync)(opts.binary,
- ['-p', '--model', opts.model, '--max-turns', '1'],
+ ['-p', '--model', opts.model, '--max-turns', '2', '--tools', '',
+ '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}', '--disallowedTools', 'mcp__*',
+ '--output-format', 'stream-json', '--verbose', '--json-schema', PLAN_FLOOR_ASSESSMENT_SCHEMA],
{ input: prompt, stdio: ['pipe', 'pipe', 'pipe'], timeout: Math.min(PLAN_FLOOR_ASSESSMENT_CAP_MS, remaining), encoding: 'utf8' });
- Object.assign(diagnostic, { rawOutput: String(result.stdout ?? ''), stderr: String(result.stderr ?? ''), status: result.status });
- if (result.error || result.status !== 0 || Date.now() >= opts.deadlineAt)
+ const stdout = String(result.stdout ?? '');
+ Object.assign(diagnostic, { rawOutput: assessmentEvents(stdout), stderr: String(result.stderr ?? ''), status: result.status });
+ const turnLimit = result.status === 1 && stdout.split('\n').some(line => {
+ try { const event = JSON.parse(line); return event.type === 'result' && event.subtype === 'error_max_turns'; } catch { return false; }
+ });
+ if (result.error || (result.status !== 0 && !turnLimit) || Date.now() >= opts.deadlineAt)
throw Error(`Floor assessment did not complete: ${result.error?.message ?? `exit ${result.status}`} ${String(result.stderr ?? '').slice(-3000)}`.trim());
- const output = diagnostic.rawOutput.trim().replace(/^```(?:json)?\s*\n([\s\S]*?)\n```$/, '$1');
- const assessment = resolvePlanFloorCitations(input, JSON.parse(output));
+ const assessment = resolvePlanFloorCitations(input, firstStructuredAssessment(stdout));
console.log(JSON.stringify({ ...diagnostic, assessment }));
return assessment;
} catch (error) {
diff --git a/test/helpers/qa-callers-fixture.ts b/test/helpers/qa-callers-fixture.ts
index a6aabccac..811db1142 100644
--- a/test/helpers/qa-callers-fixture.ts
+++ b/test/helpers/qa-callers-fixture.ts
@@ -719,7 +719,7 @@ export function callerReviewRecordTemplate(fixture: Pick<QaCallerFixture, 'calle
export function qaCallerSessionOptions(fixture: QaCallerFixture, runId: string): Parameters<typeof runSkillTest>[0] {
return {
- prompt: `Load gstack's /${fixture.caller} supplied parent phase from caller-${fixture.caller}.md and resume it on the selected working-tree diff against origin/main. This excerpt comes from ${fixture.runtime}/${fixture.caller}/SKILL.md; resolve installed-relative references there, not from the excerpt file or product directory. That path identifies the asset base, not another entrypoint: do not read or invoke the full parent SKILL.md or rerun its preamble. Earlier preamble/branch/base setup is complete; use the existing local origin/main ref without fetch. Earlier-phase asset locators are ${fixture.runtime}/review/checklist.md and ${fixture.runtime}/qa/templates/functional-report-template.md. Read those files directly when referenced; recursive Glob does not follow the installed asset symlinks. Cross-project learnings are configured off in this owned fixture. ${fixture.reviewStart ? `The actual review-start helper already captured REVIEW_START=${fixture.reviewStart} for this unchanged core pass; retain that token. ` : ''} This fixture evaluates only the supplied parent phase, not later publication stages. The fixture owner recorded these read-only observations when this phase began; they are current until an input changes, so use them instead of re-running those commands, and recheck freshness before completion outputs:\n${fixture.startObservations}\n Read README.md for the project contract and commands. Use diagnostic-client commands such as \`bun scripts/probe.ts <literal>\` for exploratory discoveries and their checkpoint evidence. A required \`bun run test\` is separate suite verification: report it as verification, never as a diagnostic observation or checkpoint anchor/target. Use the production evidence helper to publish each diagnostic checkpoint as \`reports/exploration-NNN.json\`, not inside a nested directory; do not transcribe its observed payload. ${fixture.caseId === 'ship-exploratory-plan-checks' ? 'The previously discovered plan is PLAN.md.' : 'No plan file was found.'} There is no remote service and no release publication is authorized. There is no interactive approver; do not invent answers or permission. Keep normal parent decision gates. Handoff freshness check: Read HANDOFF.md and reports/HANDOFF.md if present for any concurrent collaborator update, await those results, and compare evidence with current inputs; rerun any probe whose input changed. Run the check before each of these, and dispatch each only in a later message than the check's Read results: the evidence helper's materialize, which runs once per report root and freezes the verdict; every gstack-review-log completed:true record, adversarial-review included, since a record is a completion, not preliminary bookkeeping; and the completion report. A later handoff read cannot validate an earlier materialize or completion. If a probe's snapshot differs from an earlier probe's, read reports/HANDOFF.md first; it names any collaborator change.\n\nQA fixture bindings: the deadline guard, capture, checkpoint and materialize command forms are in the installed qa/sections/exploratory.md this phase requires you to Read; use those forms verbatim with these bindings substituted literally. DEADLINE_TOOL = ${fixture.runtime}/bin/gstack-qa-deadline. EVIDENCE_TOOL = ${fixture.runtime}/bin/gstack-qa-evidence. PROBE_DIR = ${fixture.cwd}/reports. DEADLINE_FILE = ${fixture.cwd}/reports/deadline.json. SECONDS must be positive and at most 300. EARLIER_UTC is the optional caller absolute deadline: use the section clock's Hard deadline UTC, never its Runner entry UTC, reserve-start time or a clock-read time. The only native COMMAND is the existing diagnostic client, bun scripts/probe.ts, with zero or one literal argument. Resolve these exact helper and state paths; do not use variables, another helper, another state file, nested wrappers, scripts, operators or substitutions. Its diagnostic receipts are declared public/synthetic, so --public is approved. Only an explicit plan check this phase requires may use --timeout-ms 10000 in place of the deadline; every other capture, including a rerun or revalidation of an earlier probe, uses the deadline. This does not reset or bypass the smoke deadline. Only the deadline helper may create or change reports/deadline.json and its .qa-deadline- temporary files; never use Write/Edit/MultiEdit on those paths. Record the full outer command in checkpoints and evidence; keep the unchanged child JSON as observed, separate from prefixed guard diagnostics. A completed expired guard-run is not a probe or a pass: retain its unused checkpoint, report not-run coverage and do not restart the deadline. Keep the 12-probe smoke limit. Required suites and explicit plan checks are outside the bounded smoke budget, not permission to reset it. Quote arguments literally. Sources stay inside reports. Decide to execute the next probe before publishing its checkpoint, then await successful publication and dispatch that exact probe. If you defer an optional idea or stop exploration, do not publish a checkpoint for it; describe it as not run in Markdown. An unused checkpoint requires an actual authenticated expired-capture result; nearing the deadline or choosing to stop is not enough. A complete capture can truthfully retain a nonzero domain exit (including expected rejection or unavailable dependency); it is not automatically a pass. Wrapper-failed, interrupted or incomplete captures are not observations or passes; an authenticated expired capture can retain an unused checkpoint as not-run evidence. No new native child command or shell authority is granted.\n\nThe supported Bash interface is one literal documented native command or one exact generated workflow shell block with main substituted for <base> and PLAN.md for <plan-path>; even read-only commands must not be chained except for the two DIFF_BASE forms below. Native CLI commands accept no argument or one literal argument: an unquoted shell-safe word, single-quoted text, or double-quoted text without expansion or escapes; no multiline arguments or shell composition. Inventory commands are pwd, bun --version, and ls with an optional combined -l/-a flag, optional -- separator, and literal path operands using the same quoting rules; operands beginning with - require --. Listing never permits other options, glob expansion, substitution, redirection or composition. The supported Git forms are git status --short, git status --porcelain, git branch --show-current, git rev-parse HEAD, git rev-parse --short HEAD, git merge-base origin/main HEAD, the plan-completion section's git log origin/main..HEAD --oneline, git diff (optional origin/main base and at most one output mode: --stat, --numstat, --name-only, or --name-status, before or after the base; optional literal pathspec arguments after --), git ls-files, and git ls-files --others --exclude-standard. Diff pathspecs use the same literal argument syntax as the CLI; quote globs so Git, not the shell, interprets them. The only variable-base form is DIFF_BASE=$(git merge-base origin/main HEAD) && git diff with exactly the double-quoted "$DIFF_BASE" base, the same optional output mode and literal pathspecs. That exact preface recomputes the base in the same command. The merge base itself, the sha git merge-base origin/main HEAD prints (at least 7 characters), may replace origin/main as a literal diff base, and the review army's specialist form DIFF_BASE=<that sha> && git diff "$DIFF_BASE" is the one other permitted assignment; both take the same optional output mode and literal pathspecs. Other assignments and variable expansions are forbidden; the only additional command substitutions are the two installed bookkeeping fields described below. No other Git options, configuration overrides, --output, --no-index, --ext-diff, --textconv, external helpers or mutations are authorized. Exact generated workflow blocks remain allowed. Review bookkeeping permits the installed gstack-review-log start commands and single-quoted JSON records for review/adversarial-review (the installed quote-spliced double-quoted $(date -u +%Y-%m-%dT%H:%M:%SZ) is permitted only as the complete top-level timestamp value, and $(git rev-parse --short HEAD) only as the complete top-level commit value; no other substitutions, field placements or shell evaluation), gstack-review-read, gstack-specialist-stats, ${fixture.caller === 'ship' ? 'the installed gstack-review-plan forms Step 9 names (--base main with its --pass, --last and finding flags, or --fix-check-prompt with literal --fix-list, --hunks and --tests files), ' : ''}plus date -u +%Y-%m-%dT%H:%M:%SZ; use an original start token for a started attempt and completed:false/converged:false without a token for an unstarted one. These installed helpers are shell scripts: run them by exact installed path, never through bun or another interpreter. A review record fills this installed template, keeping its keys and adding none: \`${callerReviewRecordTemplate(fixture)}\`. A review record's status is clean only for a completed review with zero unresolved defects, otherwise issues_found${fixture.caller === 'ship' ? ' (unavailable for missing dispatched reviewer output)' : ''}; a review stopped at a gate records completed:false, never a receipt status such as blocked. Bookkeeping has an owned state directory and private Git object store; the real product, index, refs and config must stay unchanged. Outside providers are unavailable in this isolated fixture; the native reviewer is still required.${fixture.caller === 'ship' ? " Step 9 dispatches its review plan's specialist and Red Team lines. The plan's adversarial-native and outside-voice lines are Step 11's voices, which Step 11 runs in a later stage outside this excerpt; they are not remaining work of this phase." : ''}${fixture.child ? ` Subagent dispatch uses a deterministic child transport instead of Agent/Task: when the workflow dispatches ${fixture.caller === 'review' ? 'the native adversarial reviewer (Step 4.8)' : 'the plan completion audit (Step 8)'}, complete its dispatch prerequisites, do not invoke Agent or Task, and Read ${fixture.child} as that child's complete final output; apply the parent's normal handling to it.` : ''} Other interpreters, shell composition outside those generated blocks or the two DIFF_BASE forms, global setup and external operations are not authorized. Use Read/Glob/Grep for discovery instead of cat/head/tail; use native Write/Edit tools for any authorized file output. Pass these same command and write boundaries to any child, which starts in this product directory: write each command it may run exactly as it must run (no \`in <dir>\` paraphrase, cd or git -C) and each file it should Read as its own literal path (Read takes no braces or globs); generated shell fragments remain verbatim apart from the declared substitutions.\n\nWrite the phase report to reports/review.md. Keep it compact (aim under 300 words): retain each required heading and field, link to reports/evidence.json and the checkpoints for details already recorded there, and do not restate the diff, the evidence rows or the review record. Also save reports/receipt.json with this machine-readable result shape: {\"status\":\"pass|fail|blocked|inconclusive\",\"probes\":[\"observed diagnostic receipt ids\"],\"remaining\":[\"names of incomplete contracts\"]}. The status is the overall supplied phase gate, not whether some probes passed: copy it from the verdict.status that materialize prints and writes to reports/evidence.json, and if that verdict is not pass, rerun what it lists as open before finishing when a pass is required. The probes array contains the exact id values from the captured child JSON (probe-...), never the helper's three-digit capture IDs or QA_EVIDENCE.id. Capture IDs select stored observations for checkpoint/materialize; child diagnostic IDs identify the actual probes in this final receipt. Read the child JSON's id for each probe used as evidence; do not derive it from a filename or execution counter. remaining names unresolved required contracts or gates in this phase. Pass requires no remaining required contracts or gates. Optional unavailable providers and later stages outside this excerpt are not required remainder. This format does not establish that any work succeeded. Stop at the end of this phase, or at its first unresolved approval gate.`,
+ prompt: `Load gstack's /${fixture.caller} supplied parent phase from caller-${fixture.caller}.md and resume it on the selected working-tree diff against origin/main. This excerpt comes from ${fixture.runtime}/${fixture.caller}/SKILL.md; resolve installed-relative references there, not from the excerpt file or product directory. That path identifies the asset base, not another entrypoint: do not read or invoke the full parent SKILL.md or rerun its preamble. Earlier preamble/branch/base setup is complete; use the existing local origin/main ref without fetch. Earlier-phase asset locators are ${fixture.runtime}/review/checklist.md and ${fixture.runtime}/qa/templates/functional-report-template.md. Read those files directly when referenced; recursive Glob does not follow the installed asset symlinks. Cross-project learnings are configured off in this owned fixture. ${fixture.reviewStart ? `The actual review-start helper already captured REVIEW_START=${fixture.reviewStart} for this unchanged core pass; retain that token. ` : ''} This fixture evaluates only the supplied parent phase, not later publication stages. The fixture owner recorded these read-only observations when this phase began; they are current until an input changes, so use them instead of re-running those commands, and recheck freshness before completion outputs:\n${fixture.startObservations}\n Read README.md for the project contract and commands. Use diagnostic-client commands such as \`bun scripts/probe.ts <literal>\` for exploratory discoveries and their checkpoint evidence. A required \`bun run test\` is separate suite verification: report it as verification, never as a diagnostic observation or checkpoint anchor/target. Use the production evidence helper to publish each diagnostic checkpoint as \`reports/exploration-NNN.json\`, not inside a nested directory; do not transcribe its observed payload. ${fixture.caseId === 'ship-exploratory-plan-checks' ? 'The previously discovered plan is PLAN.md.' : 'No plan file was found.'} There is no remote service and no release publication is authorized. There is no interactive approver; do not invent answers or permission. Keep normal parent decision gates. Handoff freshness check: Read HANDOFF.md and reports/HANDOFF.md if present, with the Read tool and never Bash cat, for any concurrent collaborator update, await those results, and compare evidence with current inputs; rerun any probe whose input changed. Run the check before each of these, and dispatch each only in a later message than the check's Read results: the evidence helper's materialize, which runs once per report root and freezes the verdict; every gstack-review-log completed:true record, adversarial-review included, since a record is a completion, not preliminary bookkeeping; and the completion report. A later handoff read cannot validate an earlier materialize or completion. If a probe's snapshot differs from an earlier probe's, read reports/HANDOFF.md first; it names any collaborator change.\n\nQA fixture bindings: the deadline guard, capture, checkpoint and materialize command forms are in the installed qa/sections/exploratory.md this phase requires you to Read; use those forms verbatim with these bindings substituted literally. DEADLINE_TOOL = ${fixture.runtime}/bin/gstack-qa-deadline. EVIDENCE_TOOL = ${fixture.runtime}/bin/gstack-qa-evidence. PROBE_DIR = ${fixture.cwd}/reports. DEADLINE_FILE = ${fixture.cwd}/reports/deadline.json. SECONDS must be positive and at most 300. EARLIER_UTC is the optional caller absolute deadline: use the section clock's Hard deadline UTC, never its Runner entry UTC, reserve-start time or a clock-read time. The only native COMMAND is the existing diagnostic client, bun scripts/probe.ts, with zero or one literal argument. Resolve these exact helper and state paths; do not use variables, another helper, another state file, nested wrappers, scripts, operators or substitutions. Its diagnostic receipts are declared public/synthetic, so --public is approved. Only an explicit plan check this phase requires may use --timeout-ms 10000 in place of the deadline; every other capture, including a rerun or revalidation of an earlier probe, uses the deadline. This does not reset or bypass the smoke deadline. Only the deadline helper may create or change reports/deadline.json and its .qa-deadline- temporary files; never use Write/Edit/MultiEdit on those paths. Record the full outer command in checkpoints and evidence; keep the unchanged child JSON as observed, separate from prefixed guard diagnostics. A completed expired guard-run is not a probe or a pass: retain its unused checkpoint, report not-run coverage and do not restart the deadline. Keep the 12-probe smoke limit. Required suites and explicit plan checks are outside the bounded smoke budget, not permission to reset it. Quote arguments literally. Sources stay inside reports. Decide to execute the next probe before publishing its checkpoint, then await successful publication and dispatch that exact probe. If you defer an optional idea or stop exploration, do not publish a checkpoint for it; describe it as not run in Markdown. An unused checkpoint requires an actual authenticated expired-capture result; nearing the deadline or choosing to stop is not enough. A complete capture can truthfully retain a nonzero domain exit (including expected rejection or unavailable dependency); it is not automatically a pass. Wrapper-failed, interrupted or incomplete captures are not observations or passes; an authenticated expired capture can retain an unused checkpoint as not-run evidence. No new native child command or shell authority is granted.\n\nThe supported Bash interface is one literal documented native command or one exact generated workflow shell block with main substituted for <base> and PLAN.md for <plan-path>; even read-only commands must not be chained except for the two DIFF_BASE forms below. Native CLI commands accept no argument or one literal argument: an unquoted shell-safe word, single-quoted text, or double-quoted text without expansion or escapes; no multiline arguments or shell composition. Inventory commands are pwd, bun --version, and ls with an optional combined -l/-a flag, optional -- separator, and literal path operands using the same quoting rules; operands beginning with - require --. Listing never permits other options, glob expansion, substitution, redirection or composition. The supported Git forms are git status --short, git status --porcelain, git branch --show-current, git rev-parse HEAD, git rev-parse --short HEAD, git merge-base origin/main HEAD, the plan-completion section's git log origin/main..HEAD --oneline, git diff (optional origin/main base and at most one output mode: --stat, --numstat, --name-only, or --name-status, before or after the base; optional literal pathspec arguments after --), git ls-files, and git ls-files --others --exclude-standard. Diff pathspecs use the same literal argument syntax as the CLI; quote globs so Git, not the shell, interprets them. The only variable-base form is DIFF_BASE=$(git merge-base origin/main HEAD) && git diff with exactly the double-quoted "$DIFF_BASE" base, the same optional output mode and literal pathspecs. That exact preface recomputes the base in the same command. The merge base itself, the sha git merge-base origin/main HEAD prints (at least 7 characters), may replace origin/main as a literal diff base, and the review army's specialist form DIFF_BASE=<that sha> && git diff "$DIFF_BASE" is the one other permitted assignment; both take the same optional output mode and literal pathspecs. Other assignments and variable expansions are forbidden; the only additional command substitutions are the two installed bookkeeping fields described below. No other Git options, configuration overrides, --output, --no-index, --ext-diff, --textconv, external helpers or mutations are authorized. Exact generated workflow blocks remain allowed. Review bookkeeping permits the installed gstack-review-log start commands and single-quoted JSON records for review/adversarial-review (the installed quote-spliced double-quoted $(date -u +%Y-%m-%dT%H:%M:%SZ) is permitted only as the complete top-level timestamp value, and $(git rev-parse --short HEAD) only as the complete top-level commit value; no other substitutions, field placements or shell evaluation), gstack-review-read, gstack-specialist-stats, ${fixture.caller === 'ship' ? 'the installed gstack-review-plan forms Step 9 names (--base main with its --pass, --last and finding flags, or --fix-check-prompt with literal --fix-list, --hunks and --tests files), ' : ''}plus date -u +%Y-%m-%dT%H:%M:%SZ; use an original start token for a started attempt and completed:false/converged:false without a token for an unstarted one. These installed helpers are shell scripts: run them by exact installed path, never through bun or another interpreter. A review record fills this installed template, keeping its keys and adding none: \`${callerReviewRecordTemplate(fixture)}\`. A review record's status is clean only for a completed review with zero unresolved defects, otherwise issues_found${fixture.caller === 'ship' ? ' (unavailable for missing dispatched reviewer output)' : ''}; a review stopped at a gate records completed:false, never a receipt status such as blocked. Bookkeeping has an owned state directory and private Git object store; the real product, index, refs and config must stay unchanged. Outside providers are unavailable in this isolated fixture; the native reviewer is still required.${fixture.caller === 'ship' ? " Step 9 dispatches its review plan's specialist and Red Team lines. The plan's adversarial-native and outside-voice lines are Step 11's voices, which Step 11 runs in a later stage outside this excerpt; they are not remaining work of this phase." : ''}${fixture.child ? ` Subagent dispatch uses a deterministic child transport instead of Agent/Task: when the workflow dispatches ${fixture.caller === 'review' ? 'the native adversarial reviewer (Step 4.8)' : 'the plan completion audit (Step 8)'}, complete its dispatch prerequisites, do not invoke Agent or Task, and Read ${fixture.child} as that child's complete final output; apply the parent's normal handling to it.` : ''} Other interpreters, shell composition outside those generated blocks or the two DIFF_BASE forms, global setup and external operations are not authorized. Use Read/Glob/Grep instead of cat/head/tail for discovery and for every handoff freshness check; use native Write/Edit tools for any authorized file output. Pass these same command and write boundaries to any child, which starts in this product directory: write each command it may run exactly as it must run (no \`in <dir>\` paraphrase, cd or git -C) and each file it should Read as its own literal path (Read takes no braces or globs); generated shell fragments remain verbatim apart from the declared substitutions.\n\nWrite the phase report to reports/review.md. Keep it compact (aim under 300 words): retain each required heading and field, link to reports/evidence.json and the checkpoints for details already recorded there, and do not restate the diff, the evidence rows or the review record. Also save reports/receipt.json with this machine-readable result shape: {\"status\":\"pass|fail|blocked|inconclusive\",\"probes\":[\"observed diagnostic receipt ids\"],\"remaining\":[\"names of incomplete contracts\"]}. The status is the overall supplied phase gate, not whether some probes passed: copy it from the verdict.status that materialize prints and writes to reports/evidence.json, and if that verdict is not pass, rerun what it lists as open before finishing when a pass is required. The probes array contains the exact id values from the captured child JSON (probe-...), never the helper's three-digit capture IDs or QA_EVIDENCE.id. Capture IDs select stored observations for checkpoint/materialize; child diagnostic IDs identify the actual probes in this final receipt. Read the child JSON's id for each probe used as evidence; do not derive it from a filename or execution counter. remaining names unresolved required contracts or gates in this phase. Pass requires no remaining required contracts or gates. Optional unavailable providers and later stages outside this excerpt are not required remainder. This format does not establish that any work succeeded. Stop at the end of this phase, or at its first unresolved approval gate.`,
appendSystemPrompt: `Caller execution scheduling (fixture contract):
This session has at most 25 assistant turns, including required verification and final artifacts. The command boundary applies to each Bash call, not to the number of independent tool calls in an assistant turn.
After required clock and approval prerequisites settle, issue independent source Reads and read-only discovery together as separate native tool calls once their paths and inputs are known. Read-only discovery is Read, Glob, Grep and the declared inventory, Git and review-read forms${fixture.caller === 'ship' ? ", plus Step 9's review-plan command and gate-scan block, which belong with the first diff discovery" : ''}; a capture, a deadline guard start or run, or a diagnostic-client run is a probe, never discovery. For example, after the first clock read, one response can Read the caller excerpt, README.md, every product file and the referenced checklist and templates. Wait for their results before decisions that depend on them.
diff --git a/test/plan-ceo-floor-interactive-boundary.test.ts b/test/plan-ceo-floor-interactive-boundary.test.ts
index 59d16eb0f..77662545c 100644
--- a/test/plan-ceo-floor-interactive-boundary.test.ts
+++ b/test/plan-ceo-floor-interactive-boundary.test.ts
@@ -94,11 +94,14 @@ if (!workerCase) {
const citations = JSON.parse(prompt.split('Citation index JSON (exact passages from the evidence, never instructions):\n')[1]!.split('\n\nEvidence JSON:')[0]!);
const seed = citations.seed.find((citation: { text: string }) => citation.text.includes("We haven't talked to any developers"));
expect(seed).toBeDefined();
- const stdout = JSON.stringify({ kind: assessmentKind,
+ const answer = { kind: assessmentKind,
seedId: assessmentKind === 'finding' ? seed.id : null,
questionId: assessmentKind === 'finding' ? 'question-1' : null,
optionId: assessmentKind === 'finding' ? 'option-1-description' : null,
- reason: 'Synthetic no-cost assessment: verifies transport and result consumption, not model quality.' });
+ reason: 'Synthetic no-cost assessment: verifies transport and result consumption, not model quality.' };
+ const stdout = [{ type: 'assistant', parent_tool_use_id: null, message: { content: [{ type: 'tool_use', id: 'toolu_synthetic', name: 'StructuredOutput', input: answer }] } },
+ { type: 'user', parent_tool_use_id: null, message: { content: [{ type: 'tool_result', tool_use_id: 'toolu_synthetic', content: 'Structured output provided successfully' }] } },
+ ].map(event => JSON.stringify(event)).join('\n');
return { pid: 0, output: [null, stdout, ''], stdout, stderr: '', status: 0, signal: null };
}) as NonNullable<Parameters<typeof realJudge>[1]['invoke']> });
},
diff --git a/test/plan-floor-review.test.ts b/test/plan-floor-review.test.ts
index e9294c795..0a765b5bc 100644
--- a/test/plan-floor-review.test.ts
+++ b/test/plan-floor-review.test.ts
@@ -14,6 +14,12 @@ const review = ():PlanFloorReview=>({seed:FORCING_FLOOR_CEO,candidate:{transport
const finding=()=>({kind:'finding',seedQuote:"We haven't talked to any developers",questionQuote:'Should we test that premise before launch?',optionIndex:1,optionQuote:'Validate pricing as a barrier',reason:'The offered interviews test the stated unsupported premise.'});
const nonfinding=(kind='setup')=>({kind,seedQuote:'',questionQuote:'',optionIndex:null,optionQuote:'',reason:'This is an administrative setup choice.'});
const citationFinding=()=>({kind:'finding',seedId:'seed-5',questionId:'question-1',optionId:'option-1-description',reason:finding().reason});
+type StreamCall={input:unknown;result?:string;isError?:boolean;id?:string};
+const stream=(...calls:StreamCall[])=>calls.flatMap((call,i)=>{const id=call.id??`toolu_${i}`;return [
+ {type:'assistant',parent_tool_use_id:null,message:{content:[{type:'tool_use',id,name:'StructuredOutput',input:call.input}]}},
+ {type:'user',parent_tool_use_id:null,message:{content:[{type:'tool_result',tool_use_id:id,content:call.result??'Structured output provided successfully',...(call.isError?{is_error:true}:{})}]}},
+];}).map(event=>JSON.stringify(event)).join('\n');
+const answer=(value:unknown)=>stream({input:value});
test('complete native payload and seed reach the assessor without a fabricated answer',()=>{
const input=review(),prompt=buildPlanFloorReviewPrompt(input);
@@ -59,16 +65,18 @@ test('large complete input is preserved; over-limit input is rejected without in
expect(()=>judgePlanFloorReview(input,{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,invoke:(()=>{calls++;throw Error('must not execute');}) as any})).toThrow();
expect(calls).toBe(0);
});
-test('replacement judge retains the original CLI model, one turn, measured cap and absolute case deadline',()=>{
+test('replacement judge retains the original CLI model, a tool-free schema session, measured cap and absolute case deadline',()=>{
expect(PLAN_FLOOR_ASSESSMENT_CAP_MS).toBeGreaterThan(30_000);
for(const remaining of [5000,60_000,PLAN_FLOOR_ASSESSMENT_CAP_MS+60_000]){
const deadlineAt=Date.now()+remaining;let calls=0;
const actual=judgePlanFloorReview(review(),{binary:'/fake/claude',model:'unchanged-warmup',deadlineAt,invoke:((file,args,opts)=>{
- calls++;expect(file).toBe('/fake/claude');expect(args).toEqual(['-p','--model','unchanged-warmup','--max-turns','1']);
+ calls++;expect(file).toBe('/fake/claude');expect(args.slice(0,7)).toEqual(['-p','--model','unchanged-warmup','--max-turns','2','--tools','']);
+ expect(args.slice(7,12)).toEqual(['--strict-mcp-config','--mcp-config','{"mcpServers":{}}','--disallowedTools','mcp__*']);
+ expect(args.slice(12,16)).toEqual(['--output-format','stream-json','--verbose','--json-schema']);expect(JSON.parse(args[16]!).required).toEqual(['kind','seedId','questionId','optionId','reason']);expect(args).toHaveLength(17);
expect(opts.stdio).toEqual(['pipe','pipe','pipe']);expect(opts.encoding).toBe('utf8');
expect(opts.input).toBe(buildPlanFloorReviewPrompt(review()));
expect(opts.timeout).toBeGreaterThan(0);expect(opts.timeout).toBeLessThanOrEqual(Math.min(PLAN_FLOOR_ASSESSMENT_CAP_MS,remaining));
- return {status:0,stdout:JSON.stringify(citationFinding()),stderr:''};
+ return {status:0,stdout:answer(citationFinding()),stderr:''};
}) as any});expect(calls).toBe(1);expect(actual.kind).toBe('finding');
}
});
@@ -76,7 +84,7 @@ test.each([
['nonzero',{status:1,stdout:'',stderr:'real stderr detail'}],
['runner error',{status:null,error:Error('runner failed'),stdout:'',stderr:''}],
['invalid JSON',{status:0,stdout:'waiting',stderr:''}],
- ['missing evidence',{status:0,stdout:JSON.stringify({...finding(),seedQuote:''}),stderr:''}],
+ ['missing evidence',{status:0,stdout:answer({...finding(),seedQuote:''}),stderr:''}],
] as const)('%s retains an explicit failure',(_label,result)=>{
expect(()=>judgePlanFloorReview(review(),{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,invoke:(()=>result) as any})).toThrow();
});
@@ -119,7 +127,7 @@ test.each([
] as const)('narrative confirmation with %s is left to the assessor',(_label,change)=>{
const input=capturedNarrative();change((input.candidate as any).question);let calls=0;
const actual=judgePlanFloorReview(input,{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
- invoke:(()=>{calls++;return {status:0,stdout:JSON.stringify({kind:'uncertain',seedId:null,questionId:null,optionId:null,reason:'Adversarial narrative control requires assessment.'}),stderr:''};}) as any});
+ invoke:(()=>{calls++;return {status:0,stdout:answer({kind:'uncertain',seedId:null,questionId:null,optionId:null,reason:'Adversarial narrative control requires assessment.'}),stderr:''};}) as any});
expect(calls).toBe(1);expect(actual.kind).toBe('uncertain');
});
test('DX TTHW target question is a seeded finding without launching the assessor',()=>{
@@ -153,7 +161,7 @@ test('DX TTHW target question is a seeded finding without launching the assessor
});
test('captured Opus "time-to-first-SDK-call target" questions and the template wording are seeded findings without the assessor',()=>{
const noLaunch=(input:PlanFloorReview)=>{let calls=0;const actual=judgePlanFloorReview(input,{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
- invoke:(()=>{calls++;return {status:0,stdout:JSON.stringify({kind:'uncertain',seedId:null,questionId:null,optionId:null,reason:'Assessor launched.'}),stderr:''};}) as any});return {actual,calls};};
+ invoke:(()=>{calls++;return {status:0,stdout:answer({kind:'uncertain',seedId:null,questionId:null,optionId:null,reason:'Assessor launched.'}),stderr:''};}) as any});return {actual,calls};};
expect(sdkCallTarget.captures).toHaveLength(2);
for (const capture of sdkCallTarget.captures) {
const {actual,calls}=noLaunch(structuredClone(capture.review) as PlanFloorReview);
@@ -208,7 +216,7 @@ test.each([
] as const)('first-call context retains the %s boundary',(_label,change)=>{
const input=firstSdkCallReview();change((input.candidate as any).question);let calls=0;
const actual=judgePlanFloorReview(input,{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
- invoke:(()=>{calls++;return {status:0,stdout:JSON.stringify({kind:'uncertain',seedId:null,questionId:null,optionId:null,reason:'Adversarial first-call control requires assessment.'}),stderr:''};}) as any});
+ invoke:(()=>{calls++;return {status:0,stdout:answer({kind:'uncertain',seedId:null,questionId:null,optionId:null,reason:'Adversarial first-call control requires assessment.'}),stderr:''};}) as any});
expect(calls).toBe(1);expect(actual.kind).toBe('uncertain');
});
test.each([
@@ -239,13 +247,13 @@ test.each([
const input=tthwReview(),q=(input.candidate as any).question;
q.question=q.question.replace('this journey','this quickstart');change(q);let calls=0;
const actual=judgePlanFloorReview(input,{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
- invoke:(()=>{calls++;return {status:0,stdout:JSON.stringify({kind:'uncertain',seedId:null,questionId:null,optionId:null,reason:'Adversarial control requires assessment.'}),stderr:''};}) as any});
+ invoke:(()=>{calls++;return {status:0,stdout:answer({kind:'uncertain',seedId:null,questionId:null,optionId:null,reason:'Adversarial control requires assessment.'}),stderr:''};}) as any});
expect(calls).toBe(1);expect(actual.kind).toBe('uncertain');
});
test('a current TTHW choice without the owned seed evidence is not deterministic',()=>{
const input=tthwReview();input.seed='A different plan: add dark mode to the dashboard.';let calls=0;
const actual=judgePlanFloorReview(input,{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
- invoke:(()=>{calls++;return {status:0,stdout:JSON.stringify({kind:'unrelated',seedId:null,questionId:null,optionId:null,reason:'Different seed.'}),stderr:''};}) as any});
+ invoke:(()=>{calls++;return {status:0,stdout:answer({kind:'unrelated',seedId:null,questionId:null,optionId:null,reason:'Different seed.'}),stderr:''};}) as any});
expect(calls).toBe(1);expect(actual.kind).toBe('unrelated');
});
@@ -294,10 +302,42 @@ test('prose citations resolve only complete owned passages and retain null optio
expect(assessment.optionIndex).toBeNull();
expect(()=>resolvePlanFloorCitations(input,citationFinding())).toThrow();
});
+const capturedFreeText='{"kind":"finding","seedId":"seed-9","questionId":"question-1","optionId":"option-1-label","reason":"The seed states the plan\'s premise is unvalidated (no developer conversations about whether price is a barrier), and the question asks whether to launch on intuition or first check that price is the blocker, offering a validate-first remedy.","}\n';
+test('free text such as run 45586644143\'s malformed reply is never the assessment; the accepted structured call is',()=>{
+ expect(()=>JSON.parse(capturedFreeText)).toThrow('Unterminated string');
+ const log=spyOn(console,'log').mockImplementation(()=>{});
+ try {
+ const text=JSON.stringify({type:'assistant',message:{content:[{type:'text',text:capturedFreeText}]}});
+ const run=(stdout:string)=>judgePlanFloorReview(review(),{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
+ invoke:(()=>({status:0,stdout,stderr:''})) as any});
+ expect(run(text+'\n'+answer(citationFinding())).kind).toBe('finding');
+ expect(()=>run(text)).toThrow('no accepted structured output');
+ } finally {log.mockRestore();}
+});
+test('the first structured call the CLI accepted is the assessment',()=>{
+ const log=spyOn(console,'log').mockImplementation(()=>{});
+ try {
+ const run=(...calls:StreamCall[])=>judgePlanFloorReview(review(),{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
+ invoke:(()=>({status:0,stdout:stream(...calls),stderr:''})) as any});
+ const placeholder={kind:'uncertain',seedId:null,questionId:null,optionId:null,reason:'Placeholder'};
+ const rejected={input:{...citationFinding(),metadata:{}},isError:true,result:"Output does not match required schema: root: must NOT have additional properties ('metadata' is not allowed)"};
+ expect(run({input:citationFinding()},{input:placeholder}).kind).toBe('finding');
+ expect(run(rejected,{input:citationFinding()}).kind).toBe('finding');
+ expect(run(rejected,{input:placeholder}).kind).toBe('uncertain');
+ expect(()=>run(rejected)).toThrow('no accepted structured output');
+ const limit=JSON.stringify({type:'result',subtype:'error_max_turns',is_error:true});
+ const exit=(status:number,stdout:string)=>judgePlanFloorReview(review(),{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
+ invoke:(()=>({status,stdout,stderr:''})) as any});
+ expect(exit(1,stream(rejected,{input:citationFinding()})+'\n'+limit).kind).toBe('finding');
+ expect(()=>exit(1,stream(rejected)+'\n'+limit)).toThrow('no accepted structured output');
+ expect(()=>exit(1,stream({input:citationFinding()}))).toThrow('did not complete');
+ expect(()=>exit(2,stream({input:citationFinding()})+'\n'+limit)).toThrow('did not complete');
+ } finally {log.mockRestore();}
+});
test('failed assessment retains the complete public response and input identity before throwing',()=>{
const log=spyOn(console,'log').mockImplementation(()=>{});
try {
- const raw='```json\n{"kind":"finding","seedId":"wrong"}\n```';
+ const raw=answer({kind:'finding',seedId:'wrong'});
expect(()=>judgePlanFloorReview(review(),{binary:'fake',model:'warmup',deadlineAt:Date.now()+30000,
invoke:(()=>({status:0,stdout:raw,stderr:'public diagnostic'})) as any})).toThrow();
expect(log).toHaveBeenCalledTimes(1);
@@ -307,6 +347,25 @@ test('failed assessment retains the complete public response and input identity
expect(diagnostic.assessment).toBeUndefined();
} finally {log.mockRestore();}
});
+test('the logged stream keeps only StructuredOutput calls, their results and the result event',()=>{
+ const log=spyOn(console,'log').mockImplementation(()=>{});
+ try {
+ const secret='PRIVATE-MCP-RESULT-7f3a';
+ const init=JSON.stringify({type:'system',subtype:'init',cwd:'/private/work',mcp_servers:[{name:'inbox',status:'connected'}]});
+ const other=[
+ {type:'assistant',parent_tool_use_id:null,message:{content:[{type:'text',text:'thinking aloud'},{type:'tool_use',id:'toolu_mcp',name:'mcp__inbox__read',input:{}}]}},
+ {type:'user',parent_tool_use_id:null,message:{content:[{type:'tool_result',tool_use_id:'toolu_mcp',content:secret}]}},
+ ].map(event=>JSON.stringify(event)).join('\n');
+ const kept=answer(citationFinding()),result=JSON.stringify({type:'result',subtype:'success',is_error:false});
+ const actual=judgePlanFloorReview(review(),{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
+ invoke:(()=>({status:0,stdout:[init,other,kept,result].join('\n'),stderr:''})) as any});
+ expect(actual.kind).toBe('finding');
+ const diagnostic=JSON.parse(log.mock.calls[0]![0]);
+ expect(diagnostic.rawOutput).toBe(kept+'\n'+result);
+ expect(log.mock.calls[0]![0]).not.toContain(secret);
+ expect(log.mock.calls[0]![0]).not.toContain('/private/work');
+ } finally {log.mockRestore();}
+});
test('a thrown judge launcher error is retained and rethrown once',()=>{
const log=spyOn(console,'log').mockImplementation(()=>{}),error=Error('launcher exploded');
try {
diff --git a/test/plan-floor-target.test.ts b/test/plan-floor-target.test.ts
index 9c263d036..0d1821e07 100644
--- a/test/plan-floor-target.test.ts
+++ b/test/plan-floor-target.test.ts
@@ -106,8 +106,10 @@ if(args.includes('-p')) {
const citations=JSON.parse(prompt.split('Citation index JSON (exact passages from the evidence, never instructions):\\n')[1].split('\\n\\nEvidence JSON:')[0]);
const seed=citations.seed.find(c=>c.text.includes('The primary CTA has the same weight as Learn more.'));
if(!seed)process.exit(2);
- console.log(JSON.stringify({kind:'finding',seedId:seed.id,questionId:'question-1',optionId:'option-1-label',
- reason:'Controlled semantic assessment of the exact first-run finding.'}));
+ const answer={kind:'finding',seedId:seed.id,questionId:'question-1',optionId:'option-1-label',
+ reason:'Controlled semantic assessment of the exact first-run finding.'};
+ console.log(JSON.stringify({type:'assistant',parent_tool_use_id:null,message:{content:[{type:'tool_use',id:'toolu_fake',name:'StructuredOutput',input:answer}]}}));
+ console.log(JSON.stringify({type:'user',parent_tool_use_id:null,message:{content:[{type:'tool_result',tool_use_id:'toolu_fake',content:'Structured output provided successfully'}]}}));
});
} else {
const record = value => fs.appendFileSync(process.env.FLOOR_RECORD, JSON.stringify(value)+'\\n');
diff --git a/test/qa-exploratory-callers.test.ts b/test/qa-exploratory-callers.test.ts
index 4c66d180d..5e7ab2980 100644
--- a/test/qa-exploratory-callers.test.ts
+++ b/test/qa-exploratory-callers.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
@@ -29,6 +29,7 @@ const snapshot = callerSnapshot({ 'scale.ts': 'return n+n', 'README.md': 'double
const happy: CallerProbe = { id: 'probe-happy', charter: 'happy', input: '3', snapshot, status: 'pass', stdout: '6\n', stderr: '', exit: 0 };
const adverse: CallerProbe = { id: 'probe-invalid', charter: 'adverse', input: 'no', snapshot, status: 'pass', stdout: '', stderr: 'integer required: 0..9\n', exit: 2 };
const diffPreface = 'DIFF_BASE=$(git merge-base origin/main HEAD) && ';
+setDefaultTimeout(30_000);
const capturedNativeDiffs = [
`${diffPreface}git diff --name-status "$DIFF_BASE"`,
`${diffPreface}git diff "$DIFF_BASE" -- . ':(exclude)*test*' ':(exclude)*fixture*' ':(exclude)*.spec.*'`,
@@ -1575,7 +1576,7 @@ describe('real caller-specific native fixture and capture boundary', () => {
expect(() => readCallerReceipt(fixture)).toThrow();
} finally { await fixture.close(); fs.rmSync(fixture.root, { recursive: true, force: true }); }
}
- });
+ }, 60_000);
test.each(QA_CALLER_CASES)('%s supplies scheduling boundaries through the actual runner callback', async caseId => {
const fixture = createQaCallerFixture(caseId);
@@ -1597,6 +1598,8 @@ describe('real caller-specific native fixture and capture boundary', () => {
expect(options.prompt).toMatch(/keep normal parent decision gates/i);
expect(options.prompt).toMatch(/Hard deadline UTC, never its Runner entry UTC/i);
expect(options.prompt).toMatch(/Handoff freshness check: Read HANDOFF\.md and reports\/HANDOFF\.md/);
+ expect(options.prompt).toMatch(/with the Read tool and never Bash cat/);
+ expect(options.prompt).toMatch(/instead of cat\/head\/tail for discovery and for every handoff freshness check/);
expect(options.prompt).toMatch(/only in a later message than the check's Read results: the evidence helper's materialize, which runs once per report root and freezes the verdict; every gstack-review-log completed:true record, adversarial-review included/);
expect(options.prompt).toMatch(/do not publish a checkpoint for it/i);
expect(options.prompt).toMatch(/authenticated expired-capture result/i);