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

Make the plan-review test judge reject failed sessions and steady two flaky tests (#4849)

Garry Tan89825888c57e
diff --git a/changelog.d/flaky-tests-and-stricter-plan-review-judge.md b/changelog.d/flaky-tests-and-stricter-plan-review-judge.md
new file mode 100644
index 000000000..e8b15cf8e
--- /dev/null
+++ b/changelog.d/flaky-tests-and-stricter-plan-review-judge.md
@@ -0,0 +1,5 @@
+### Fixed
+
+- **The plan-review test judge no longer accepts an answer from a session that reported an error.** When Claude Code exits 0 but its final result says `is_error: true`, the finding-floor judge now treats the assessment as failed instead of using the answer it saw earlier. The judge session also runs with hooks and slash commands turned off, like gstack's other Claude Code calls, and skips a plain notice line in the output while still failing on a broken JSON event.
+- **The `gstack-question-log` Bun-config test no longer sees a record left by the test before it.** Each write used to start a background profile update that kept writing into the test's state folder after the test ended; the test now turns that update off.
+- **A brain-sync merge test that failed at random now shows the sync status message when it fails,** so the next failure names its cause.
diff --git a/test/brain-sync.test.ts b/test/brain-sync.test.ts
index 88d5e4a83..7fae6fd12 100644
--- a/test/brain-sync.test.ts
+++ b/test/brain-sync.test.ts
@@ -1269,7 +1269,7 @@ describe('gstack-brain-sync per-file hold', () => {
write(CLEAN, '# a plan\n');
expect(drain().status).toBe(0);
const s = statusJson();
- expect(s.status).toBe('ok');
+ expect(s).toMatchObject({ status: 'ok' });
expect(remoteShow(SHARED).stdout).toBe('{"note":"shared from the peer"}\n');
expect(fs.readFileSync(path.join(tmpHome, SHARED), 'utf-8')).toBe('{"note":"shared from the peer"}\n');
expect(unmerged()).toBe('');
diff --git a/test/bun-config-shell-bins.test.ts b/test/bun-config-shell-bins.test.ts
index 9eefc12eb..b4d8174df 100644
--- a/test/bun-config-shell-bins.test.ts
+++ b/test/bun-config-shell-bins.test.ts
@@ -16,6 +16,13 @@
* nothing written instead of exiting 0. An OSTYPE=msys inherited by a POSIX
* bash with no cygpath keeps /dev/null, so a file named NUL in the repository
* is never read as Bun's config.
+ *
+ * gstack-question-log starts a detached gstack-developer-profile --derive after
+ * each write, and that process keeps writing into the state root after its
+ * test returns, while the next test resets it (Trunk 4c32732f: a control then
+ * saw the previous test's record). Every call here sets
+ * GSTACK_QUESTION_LOG_NO_DERIVE, the bin's test opt-out, so no process outlives
+ * the test that started it.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
@@ -47,7 +54,7 @@ function env(pathPrefix?: string, extra: Record<string, string> = {}): NodeJS.Pr
for (const [k, v] of Object.entries(process.env)) if (!/^(GSTACK_|MSYS|OSTYPE$)/.test(k)) out[k] = v;
const PATH = Object.keys(out).find(k => k.toUpperCase() === 'PATH') ?? 'PATH';
if (pathPrefix) out[PATH] = pathPrefix + path.delimiter + (out[PATH] ?? '');
- return { ...out, HOME: path.join(tmp, 'home'), GSTACK_STATE_ROOT: stateRoot, MSYS_NO_PATHCONV: '1', MSYS2_ARG_CONV_EXCL: '*', ...extra };
+ return { ...out, HOME: path.join(tmp, 'home'), GSTACK_STATE_ROOT: stateRoot, GSTACK_QUESTION_LOG_NO_DERIVE: '1', MSYS_NO_PATHCONV: '1', MSYS2_ARG_CONV_EXCL: '*', ...extra };
}
function run(bin: string, input: string, pathPrefix?: string, extra: Record<string, string> = {}, rest: string[] = []) {
diff --git a/test/helpers/plan-floor-review.ts b/test/helpers/plan-floor-review.ts
index d08d33fe4..f9ebc9484 100644
--- a/test/helpers/plan-floor-review.ts
+++ b/test/helpers/plan-floor-review.ts
@@ -224,7 +224,8 @@ const PLAN_FLOOR_ASSESSMENT_SCHEMA = JSON.stringify({
},
});
-/** The first StructuredOutput call the CLI accepted is the assessment. A call
+/** The first StructuredOutput call the CLI accepted is the assessment. Lines
+ * that are not JSON events (CLI notices) are skipped; a broken event fails. 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
@@ -233,8 +234,10 @@ const PLAN_FLOOR_ASSESSMENT_SCHEMA = JSON.stringify({
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;
+ if (!line.trimStart().startsWith('{')) continue;
+ let parsed: unknown;
+ try { parsed = JSON.parse(line); } catch { throw Error('Floor assessment stream has a malformed JSON event'); }
+ const event = parsed 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)
@@ -283,14 +286,17 @@ export function judgePlanFloorReview(input: PlanFloorReview, opts: {
const result = (opts.invoke ?? spawnSync)(opts.binary,
['-p', '--model', opts.model, '--max-turns', '2', '--tools', '',
'--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}', '--disallowedTools', 'mcp__*',
+ '--disable-slash-commands', '--settings', '{"disableAllHooks":true}',
'--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' });
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; }
+ const results = stdout.split('\n').flatMap(line => {
+ try { const event = JSON.parse(line); return event?.type === 'result' ? [event] : []; } catch { return []; }
});
- if (result.error || (result.status !== 0 && !turnLimit) || Date.now() >= opts.deadlineAt)
+ const turnLimit = result.status === 1 && results.some(event => event.subtype === 'error_max_turns');
+ const failedResult = result.status === 0 && results.some(event => event.is_error === true);
+ if (result.error || (result.status !== 0 && !turnLimit) || failedResult || Date.now() >= opts.deadlineAt)
throw Error(`Floor assessment did not complete: ${result.error?.message ?? `exit ${result.status}`} ${String(result.stderr ?? '').slice(-3000)}`.trim());
const assessment = resolvePlanFloorCitations(input, firstStructuredAssessment(stdout));
console.log(JSON.stringify({ ...diagnostic, assessment }));
diff --git a/test/plan-floor-review.test.ts b/test/plan-floor-review.test.ts
index 0a765b5bc..11cc9ae45 100644
--- a/test/plan-floor-review.test.ts
+++ b/test/plan-floor-review.test.ts
@@ -72,7 +72,8 @@ test('replacement judge retains the original CLI model, a tool-free schema sessi
const actual=judgePlanFloorReview(review(),{binary:'/fake/claude',model:'unchanged-warmup',deadlineAt,invoke:((file,args,opts)=>{
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(args.slice(12,15)).toEqual(['--disable-slash-commands','--settings','{"disableAllHooks":true}']);
+ expect(args.slice(15,19)).toEqual(['--output-format','stream-json','--verbose','--json-schema']);expect(JSON.parse(args[19]!).required).toEqual(['kind','seedId','questionId','optionId','reason']);expect(args).toHaveLength(20);
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));
@@ -334,6 +335,28 @@ test('the first structured call the CLI accepted is the assessment',()=>{
expect(()=>exit(2,stream({input:citationFinding()})+'\n'+limit)).toThrow('did not complete');
} finally {log.mockRestore();}
});
+test('an exit 0 whose result event reports an error is no assessment, even after an accepted call',()=>{
+ const log=spyOn(console,'log').mockImplementation(()=>{});
+ try {
+ const run=(result:object)=>judgePlanFloorReview(review(),{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
+ invoke:(()=>({status:0,stdout:answer(citationFinding())+'\n'+JSON.stringify({type:'result',...result}),stderr:''})) as any});
+ expect(()=>run({subtype:'success',is_error:true})).toThrow('did not complete');
+ expect(()=>run({subtype:'error_during_execution',is_error:true})).toThrow('did not complete');
+ expect(run({subtype:'success',is_error:false}).kind).toBe('finding');
+ } finally {log.mockRestore();}
+});
+test('a CLI notice line is skipped, but a broken JSON event still fails the assessment',()=>{
+ const log=spyOn(console,'log').mockImplementation(()=>{});
+ try {
+ const run=(stdout:string)=>judgePlanFloorReview(review(),{binary:'fake',model:'warmup',deadlineAt:Date.now()+30_000,
+ invoke:(()=>({status:0,stdout,stderr:''})) as any});
+ const kept=answer(citationFinding());
+ expect(run('Note: update available\n'+kept).kind).toBe('finding');
+ expect(()=>run('{"type":"assistant","message":\n'+kept)).toThrow('malformed JSON event');
+ expect(()=>run(kept.split('\n')[0]!+'\n'+kept.split('\n')[1]!.slice(0,-2))).toThrow('malformed JSON event');
+ expect(()=>run('Note: update available')).toThrow('no accepted structured output');
+ } finally {log.mockRestore();}
+});
test('failed assessment retains the complete public response and input identity before throwing',()=>{
const log=spyOn(console,'log').mockImplementation(()=>{});
try {