mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-03 01:46:55 +02:00
* test: delete test-infrastructure dead code (G) - exit-propagation drives the runner's real strict verdict (BunTestOutputClassifier + strictTestExitCode); delete the unused shardRunLooksTruncated predicate. - delete skill-coverage-matrix registry + its gate (nothing reads it; the floor already iterates skillCensus()). - delete touchfiles-facade export-parity tests (Bun fails missing imports at link time) and the duplicated E2E_TIERS tier-value test. - delete brain-cache-spec TRANSPORT_DEFAULT_POLICY, SKILL_RUN_RETENTION_DAYS and the now-unused BrainTrustPolicy type with their literal tests. AUTOPLAN_PREFLIGHT_BUDGET_BYTES stays: skill-preflight-budget enforces it against real resolver output. - delete audit-compliance's JSDoc-comment grep. * test: replace product tests that fake the product with real-boundary tests (F) - design: serve.test.ts drove an inline mirror server; now two tests run the real serve() on an ephemeral port (reload confinement, submit exit 0). - setup-gbrain: rollback + voyage tests execute the template-extracted init blocks (3 sites) instead of drifted local bash copies. - terminal-agent: internalHandler source greps replaced by a behavioral /internal/grant + /internal/revoke auth matrix (no/wrong/valid token). - /health: server-security-surface and the server-auth / security-audit-r2 / sidebar-tabs source greps fold into one liveness-only check on the real body; the L4 sidecar wiring gets a behavioral /pty-inject-scan test. - delete tautologies (browser-manager onDisconnect, memory-command #12), ios swiftui tap fixture self-check, memory-ingest put_page grep, detach source greps, sidebar-agent absence pins, dead-CSS pins + the dead CSS, security-audit-r2 Task 1 + the test-only meta-commands re-export, duplicate generated-SKILL.md checks. - make-pdf coverage-gaps cases move into their owner test files. * test: delete tests of dead eval code (A) - A1: the retired Eng lexical oracle (evaluateEngSeedCoverage, isEngSeedDecisionAUQ), the completion-handoff detector and the retained corpus had no paid caller since v1.87.6; delete their 26 replay files, ~2.6k helper LOC and fixtures, and the dead blocks in 8 mixed files (live hasNativePlanTerminal / batching assertions stay). - A2: dead viewport approvers in autoplan-artifact-permission and their 11 replay files + fixtures; recorder/launcher cases stay. - A3: never-wired oracles and seeders (autoplan-phase-order, eng-finding-fixture, ceo-paired-fixture, design-ui-scope, plan-skill-completion, pty-current-screen, required-reads, transcript-section-logger); plan-seed-submission now decodes through the production createPtyScreen; section manifests name their actual guard. - A4: zero-reference helper exports, plus execGit and invokeAndObserve found by the reachability pass. - 52 fixtures orphaned by the deletions; touchfile and selection-table entries for every deleted path. * test: clean up the paid eval lane (B1-B4, B6, B7) - B1: delete paid files that assert nothing or cannot pass meaningfully: skill-llm-eval-spec and skill-e2e-spec-execute (test.todo), gemini-e2e (+ gemini-session-runner; no gemini CLI in CI), ship-idempotency (red since v1.63), the two opus-4-7 *-sonnet overlay wrappers, conductor-prose (+ its source-evaluation replay), codex-e2e-plan-format; drop their keys, scripts and census rows. - B2: skill-llm-eval grades browse/sections/command-list.md with one union judge that also carries the baseline score pin; regression-vs-baseline deleted (paid run: pass, c4/c4/a4). - B3: memory-pipeline, ios-qa, ios-qa-swift-build and plan-tune-cathedral make no model calls; renamed out of the paid glob so they run on every PR. Swift builds need GSTACK_TEST_SWIFT=1; device stub deleted. - B4: codex-e2e*, outside-voice, aside and ios-device cannot run in the CI image; excluded from the weekly lane with a tracked re-entry condition. - B6: fold opus-47's negative routing controls into skill-routing-e2e journey-negatives (paid run: 3/3 unrouted) and delete the file. - B7: delete the never-green brain-privacy-gate eval; a free gstack-skill-start test now proves consent precedes artifacts egress. * test: retire the finding-count cluster and trim its helpers (C) - C0/C1: the five never-green evals (skill-e2e-autoplan-chain and skill-e2e-plan-{ceo,eng,design,devex}-finding-count) failed on harness and budget, never on skill behavior; delete them, their touchfile/tier ids, AUTOPLAN_CHAIN_BUDGET and the dedicated eighth periodic slice (--slices 7). - C2: delete the helper groups whose only paid consumers were those files (11 modules), trim claude-pty-runner and eng-seeded-coverage to the paid closure, and delete the free replay tests whose assertions exercised only that dead code (89 files, 135 orphaned fixtures). Blocks that used dead code only as input for a live subject keep their assertions: the multiSelect default moved to plan-review-decisions, runner PTY tests use inline caller policies, and the timer-safe budget checks moved to eng-finding-retry-budget. - The eight production-touching files stay except ceo-current-decision-record (its template read only feeds the retired counter). - CARVE_GUARDS.autoplan is behavioral 'none'; TODOS records the lost chain and per-finding cadence coverage with their re-entry tests. * test: fold per-incident replay series into their detector owners (D) Twelve detector families move into one owner test each: 73 incident files become describe blocks in ceo-section-loading-fixture (stale-fill race), model-overlays, coverage-audit-evidence, autoplan-phase-observer, native-auto-decide, outside-voice-evidence, eng-first-review, plan-count-completion, plan-count-file-permission, ceo-mode-option, plan-scope-selection and plan-count-prerequisite. Each block keeps its original code and fixture, so every case still runs; only tests asserting the incident file's own touchfile registration are dropped (41). Touchfile lists that named an incident now name its owner. * test: start the plan-count history PTY on its readiness marker (H) The fake CLI prints a startup marker and the runner waits for it instead of the fixed 8 s startup sleep (8.6 s -> 0.9 s locally). eng-semantic-terminal's sleeping registration cases went with C; plan-count-timeout keeps the fixed wait because it asserts deadline behavior. * test: derive paid touchfiles from each eval's static closure (E) touchfiles.test.ts now checks, per key, that the paid file's static test/helpers and test/fixtures closure (plus fixture paths it names in string literals) is covered, and names the file, path, chain and key to fix when it is not. Free *.test.ts files are no longer touchfiles, so editing a free replay test stops selecting paid evals: 950 entries removed, 653 real closure paths added. The hand-copied inventories go: periodic-fixture-selection, fake-impeccable-touchfiles and 45 per-file selection examples. Selection for the sample edits (plan-eng-review template, claude-pty-runner, plan-count-fixture, gstack-config) loses no case under either profile. CONTRIBUTING documents the rule and its lower bound. * test: skip hollow tier shards and census judges in the paid planner (B5) A paid file is now skipped for a tier lane only when every E2E id it registers is known statically and none has that tier; ids come from the touchfile registrations and literal testName/*IfSelected arguments, so a comment or skill path that quotes another id cannot unschedule it, and computed names keep today's scheduling. --list and the manifest show each skip as "skipped: no E2E_TIERS id has tier <tier>". The weekly gate census drops the LLM judges (--skip-judges); they still run in the periodic census and PR gate lanes. Gate lane 52 -> 42 files, census 41; periodic 77 -> 69. * test: run seven paid evals on the current default capture model (B8) skill-e2e-{auq-matrix,plan-format,qa-bugs,retro,workflow} pinned claude-opus-4-7 and skill-e2e-office-hours plus -brain-writeback pinned claude-sonnet-4-6; none tests a historical model, so they now capture with resolveEvalModel('capture'), and the free harness tests that execute these registrations receive the same resolver. The paid re-pin run passed all of them. skill-e2e-{design,office-hours-phase4,plan-prosons,plan} keep claude-opus-4-7: six of their cases failed on the default model (three timeouts, a missing report file, a format miss and a posture score of 3), so per the plan's fallback they keep their pins with a TODOS entry. The pre-spend estimate and drop threshold are in docs/test-audit-2026-09.md. * test: guard the reduced suite against new test-of-test files - test/test-of-test-ratchet.test.ts records the 228 free tests that import only test/ code and fails on a new one, naming the owner test to extend instead; a stale baseline entry fails with the remove instruction. - test/helpers/resolve-repo-path.ts is the one specifier/literal resolver for the ratchet and the touchfile closure invariant, with its own unit tests. - CONTRIBUTING "Test tiers" describes the paid-failure workflow (fix, then one row in the detector's owner test) and the ratchet; TEST_PORTFOLIO gains the detector -> owner-test table and no longer claims an Autoplan chain eval. - TODOS: automatic exclusion policy for chronically red periodic files (P3), the deferred native-completion table collapse, the unused CEO payment seeder; the PTY readiness item is narrowed to the paid runner. - docs/test-audit-2026-09.md collects the triage, security mapping, inventories, selection proof, behavior-commit decisions and retained false positives. * v1.91.8.0 test: smaller suite, derived paid selection, retired never-green evals Release metadata for the test-reduction branch: VERSION 1.91.8.0 (1.91.7.0 is claimed by #2983), CHANGELOG with the measured before/after table and a contributor section, durations re-recorded on Ubicloud standard-16 (857 files, 0 failures), the agents digest, CONTRIBUTING's after-measurement row, the B8 fallback TODOS entry, and the after metrics, kept-vs-plan notes, B8 run and census estimate in docs/test-audit-2026-09.md. * fix(ubicloud): skip retrieval globs that match nothing instead of reporting a failed pull * test: count issue-numbered Design findings in the UI-scope gate eval
206 lines
16 KiB
TypeScript
206 lines
16 KiB
TypeScript
import { expect, test } from 'bun:test';
|
||
import * as fs from 'node:fs';
|
||
import * as os from 'node:os';
|
||
import * as path from 'node:path';
|
||
import { pathToFileURL } from 'node:url';
|
||
import { execFileSync } from 'node:child_process';
|
||
import { nextCeoPostureContinuation, hasNativePostAnswerCeoPosture } from './helpers/ceo-mode-option';
|
||
import type { NativePlanQuestionCall, PlanCountTranscript } from './helpers/plan-count-transcript';
|
||
import { createPendingQuestionRecorder, recordPendingQuestion, pendingQuestionRecorderStatus } from './helpers/plan-count-pending-question';
|
||
|
||
const packet = JSON.parse(fs.readFileSync(path.join(import.meta.dir, 'fixtures/autoplan-setup-packet-o-call.json'), 'utf8')) as NativePlanQuestionCall;
|
||
const captured = fs.readFileSync(path.join(import.meta.dir, 'fixtures/autoplan-setup-packet-o-screen.txt'), 'utf8');
|
||
|
||
test('bounded content-free status distinguishes incomplete publication from permanently invalid capture', () => {
|
||
const cwd=fs.mkdtempSync(path.join(os.tmpdir(),'gstack-pending-status-')), config=path.join(cwd,'.claude');
|
||
const native=path.join(config,'projects','fixture',packet.sessionId+'.jsonl');
|
||
fs.mkdirSync(path.dirname(native),{recursive:true});fs.writeFileSync(native,'');
|
||
const event={hook_event_name:'PreToolUse',tool_name:'AskUserQuestion',session_id:packet.sessionId,
|
||
tool_use_id:packet.toolUseId,cwd,transcript_path:native,tool_input:{questions:packet.questions}};
|
||
const recorder=createPendingQuestionRecorder(cwd,config);
|
||
try {
|
||
expect(pendingQuestionRecorderStatus(undefined,cwd,config)).toEqual({status:'disabled'});
|
||
expect(pendingQuestionRecorderStatus(path.join(cwd,'missing'),cwd,config)).toEqual({status:'missing'});
|
||
expect(pendingQuestionRecorderStatus(recorder.file,cwd,config)).toEqual({status:'idle'});
|
||
fs.writeFileSync(recorder.file+'.lock','');
|
||
expect(pendingQuestionRecorderStatus(recorder.file,cwd,config)).toEqual({status:'busy'});
|
||
fs.unlinkSync(recorder.file+'.lock');
|
||
recordPendingQuestion(JSON.stringify(event),recorder.file,cwd,config);
|
||
expect(pendingQuestionRecorderStatus(recorder.file,cwd,config)).toEqual({status:'pending'});
|
||
recordPendingQuestion(JSON.stringify({...event,tool_use_id:'another-pending'}),recorder.file,cwd,config);
|
||
const retained=pendingQuestionRecorderStatus(recorder.file,cwd,config);
|
||
expect(retained).toEqual({status:'invalid',reason:'concurrent_pending'});
|
||
expect(JSON.stringify(retained)).not.toContain(cwd);
|
||
expect(JSON.stringify(retained)).not.toContain(packet.questions[0]!.question);
|
||
recorder.dispose();
|
||
expect(retained).toEqual({status:'invalid',reason:'concurrent_pending'});
|
||
for (const [input,reason] of [['{','invalid_event'],['x'.repeat(128*1024+1),'input_overflow']]) {
|
||
const bad=createPendingQuestionRecorder(cwd,config);
|
||
try { recordPendingQuestion(input!,bad.file,cwd,config);
|
||
expect(pendingQuestionRecorderStatus(bad.file,cwd,config)).toEqual({status:'invalid',reason});
|
||
recordPendingQuestion(JSON.stringify(event),bad.file,cwd,config);
|
||
expect(pendingQuestionRecorderStatus(bad.file,cwd,config)).toEqual({status:'invalid',reason});
|
||
} finally { bad.dispose(); }
|
||
}
|
||
} finally {recorder.dispose();fs.rmSync(cwd,{recursive:true,force:true});}
|
||
});
|
||
|
||
test('pending mode continuation does not stand in for a successful mode answer or posture', () => {
|
||
const question = {header:'Review mode', question:'Which review mode?', options:[
|
||
{label:'SCOPE EXPANSION'}, {label:'SELECTIVE EXPANSION'}, {label:'HOLD SCOPE'}, {label:'SCOPE REDUCTION'}]};
|
||
const selected: NativePlanQuestionCall = {sessionId:'owned', toolUseId:'mode', questions:[question], answered:true,
|
||
failed:false, answers:{[question.question]:'HOLD SCOPE'}, unansweredQuestionIndices:[], answeredAt:new Date(1000).toISOString()};
|
||
const pending = {sessionId:'owned', toolUseId:'followup', answered:false, failed:false, source:'pre_tool_use' as const,
|
||
questions:[{header:'Current behavior', question:'Which contract should remain?', options:[{label:'Keep scope'}, {label:'Expand scope'}]}]};
|
||
const screen = '☐ Current behavior\nWhich contract should remain?\n❯ 1. Keep scope\n 2. Expand scope\nEnter to select · ↑/↓ to navigate · Esc to cancel';
|
||
const transcript: PlanCountTranscript = {status:'ready', calls:[selected], assistantMessages:[]};
|
||
expect(nextCeoPostureContinuation(screen, {...transcript, calls:[]}, 'HOLD SCOPE', 999, new Set(), false, screen, pending)).toBeNull();
|
||
expect(nextCeoPostureContinuation(screen, {...transcript, calls:[{...selected, answered:false}]}, 'HOLD SCOPE', 999, new Set(), false, screen, pending)).toBeNull();
|
||
expect(hasNativePostAnswerCeoPosture(transcript, 'HOLD SCOPE', /rigor/, 999)).toBe(false);
|
||
expect(nextCeoPostureContinuation(screen, transcript, 'HOLD SCOPE', 999, new Set(), false, screen, pending)).toBe('question');
|
||
expect(nextCeoPostureContinuation(screen, transcript, 'HOLD SCOPE', 999, new Set(), false, screen,
|
||
{...pending, sessionId:'foreign'})).toBeNull();
|
||
expect(transcript.calls).toEqual([selected]);
|
||
expect(hasNativePostAnswerCeoPosture(transcript, 'HOLD SCOPE', /rigor/, 999)).toBe(false);
|
||
|
||
const batch = {...pending, questions:[pending.questions[0]!,
|
||
{header:'Validation', question:'Which check should remain?', options:[{label:'Keep tests'}, {label:'Expand tests'}]}]};
|
||
const pane = (index: number) => {
|
||
const bar = '← ' + batch.questions.map((q,i)=>(i<index?'☒ ':'☐ ')+q.header).join(' ') + ' ✔ Submit →';
|
||
const body = index < 2 ? batch.questions[index]!.question + '\n' + batch.questions[index]!.options.map((o,i)=>(i===0?'❯':' ')+' '+(i+1)+'. '+o.label).join('\n')
|
||
: 'Review your answers\nReady to submit your answers?\n❯ 1. Submit answers\n 2. Cancel';
|
||
return bar+'\n'+body+'\nEnter to select · Tab/Arrow keys to navigate · Esc to cancel';
|
||
};
|
||
const seen = new Set<string>();
|
||
expect(nextCeoPostureContinuation(pane(0), transcript, 'HOLD SCOPE', 999, seen, false, pane(0), batch)).toBe('question');
|
||
expect(nextCeoPostureContinuation(pane(1), transcript, 'HOLD SCOPE', 999, seen, true, pane(1))).toBeNull();
|
||
expect(nextCeoPostureContinuation(pane(1), transcript, 'HOLD SCOPE', 999, seen, true, pane(1), structuredClone(batch))).toBe('question');
|
||
expect(nextCeoPostureContinuation(pane(2), transcript, 'HOLD SCOPE', 999, seen, true, pane(2), structuredClone(batch))).toBe('submission');
|
||
expect(nextCeoPostureContinuation(pane(2), transcript, 'HOLD SCOPE', 999, seen, true, pane(2), batch)).toBeNull();
|
||
expect(transcript.calls).toEqual([selected]);
|
||
});
|
||
|
||
function identity(pid: number): string | null {
|
||
try { return execFileSync('ps', ['-p',String(pid),'-o','lstart=','-o','command='], {encoding:'utf8',timeout:5000}).trim(); }
|
||
catch { return null; }
|
||
}
|
||
|
||
test.skipIf(process.platform === 'win32')('opt-in hook supplies full pending packet before publication; only actual JSONL results add answered coverage', async () => {
|
||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-pending-question-pty-'));
|
||
const fake = path.join(dir, 'fake-claude'), worker = path.join(dir, 'worker.ts'), result = path.join(dir, 'results.json');
|
||
const workerTemp = path.join(dir, 'tmp'); fs.mkdirSync(workerTemp);
|
||
const helper = (name: string) => pathToFileURL(path.join(import.meta.dir, 'helpers', name)).href;
|
||
fs.writeFileSync(fake, `#!${process.execPath}\n` + String.raw`
|
||
import * as fs from 'node:fs'; import * as path from 'node:path'; import {execFileSync} from 'node:child_process';
|
||
const item=JSON.parse(process.env.QUESTION_REPLAY), cwd=process.cwd(), call=item.call;
|
||
const record=value=>fs.appendFileSync(path.join(cwd,'events.jsonl'),JSON.stringify(value)+'\n');
|
||
record({kind:'pid',pid:process.pid,identity:execFileSync('ps',['-p',String(process.pid),'-o','lstart=','-o','command='],{encoding:'utf8',timeout:5000}).trim()});
|
||
const config=process.env.CLAUDE_CONFIG_DIR, native=path.join(config,'projects',path.basename(cwd),call.sessionId+'.jsonl');
|
||
fs.mkdirSync(path.dirname(native),{recursive:true});
|
||
const persist=(role,content,extra={})=>fs.appendFileSync(native,JSON.stringify({cwd,sessionId:call.sessionId,isSidechain:false,timestamp:new Date().toISOString(),message:{role,content},...extra})+'\n');
|
||
persist('assistant',[{type:'text',text:'I am preparing the repository setup questions.'}]);
|
||
const at=process.argv.indexOf('--settings'); const settings=at<0?null:JSON.parse(process.argv[at+1]);
|
||
record({kind:'settings',settings});
|
||
async function hook(event) {
|
||
const entries=settings?.hooks[event]?.filter(e=>e.matcher==='^AskUserQuestion$')??[];
|
||
if(!entries.length)return;
|
||
if(entries.length!==1||entries[0].hooks.length!==1||entries[0].hooks[0].timeout!==5)throw Error('wrong AUQ hook scope');
|
||
const payload={hook_event_name:event,tool_name:'AskUserQuestion',session_id:call.sessionId,tool_use_id:call.toolUseId,cwd,transcript_path:native,tool_input:{questions:call.questions}};
|
||
const p=Bun.spawn(['bash','-c',entries[0].hooks[0].command],{stdin:new Blob([JSON.stringify(payload)]),stdout:'pipe',stderr:'pipe'});
|
||
const [code,out,err]=await Promise.all([p.exited,new Response(p.stdout).text(),new Response(p.stderr).text()]);
|
||
record({kind:'hook',event,code,out,err}); if(code||out||err)throw Error('observer changed tool response');
|
||
}
|
||
await hook('PreToolUse');
|
||
if(item.crash)process.exit(19);
|
||
let index=0,done=false;const answers={};
|
||
function render(){const q=call.questions;let screen=item.first;
|
||
if(index){const bar='← '+q.map(question=>(answers[question.question]?'☒ ':'☐ ')+question.header).join(' ')+' ✔ Submit →';
|
||
screen=index<q.length?bar+'\n│ '+q[index].question+'\n'+q[index].options.map((o,i)=>(i===0?'❯':' ')+' '+(i+1)+'. '+o.label).join('\n')+'\n 3. Type something.\n 4. Chat about this':bar+'\nReview your answers\nReady to submit your answers?\n❯ 1. Submit answers\n 2. Cancel';
|
||
screen+='\nEnter to select · Tab/Arrow keys to navigate · Esc to cancel\n';}
|
||
process.stdout.write('\x1b[2J\x1b[H'+screen.replace(/\n/g,'\r\n'));}
|
||
process.stdin.setRawMode?.(true);process.stdin.resume();
|
||
process.stdin.on('data',async data=>{const input=data.toString();record({kind:'input',input,index});
|
||
if(!settings||done)throw Error('unexpected input');
|
||
if(index<call.questions.length){if(input!=='1')throw Error('wrong native digit');answers[call.questions[index].question]=call.questions[index].options[0].label;index++;render();return;}
|
||
if(input!=='\r')throw Error('Submit must be one Enter');done=true;
|
||
await hook('PostToolUse');await hook('PreToolUse');
|
||
persist('assistant',[{type:'tool_use',id:call.toolUseId,name:'AskUserQuestion',input:{questions:call.questions}}]);
|
||
persist('user',[{type:'tool_result',tool_use_id:call.toolUseId,content:'Answered.'}],{toolUseResult:{answers}});
|
||
process.stdout.write('\x1b[2J\x1b[HNATIVE_PACKET_COMPLETE\r\n');});
|
||
render();process.on('SIGINT',()=>process.exit(0));
|
||
`, {mode:0o755});
|
||
fs.writeFileSync(worker, `
|
||
import * as fs from 'node:fs'; import * as path from 'node:path'; import * as os from 'node:os';
|
||
import {launchClaudePty,resolveClaudeBinary} from ${JSON.stringify(helper('claude-pty-runner.ts'))};
|
||
import {readPlanCountTranscript} from ${JSON.stringify(helper('plan-count-transcript.ts'))};
|
||
import {readPendingQuestion} from ${JSON.stringify(helper('plan-count-pending-question.ts'))};
|
||
if(resolveClaudeBinary()!==${JSON.stringify(fake)})throw Error('fake CLI binding failed');
|
||
const root=${JSON.stringify(dir)},results=[];
|
||
for(const enabled of [false,true]){
|
||
const cwd=path.join(root,String(enabled));fs.mkdirSync(cwd);const startedAt=Date.now();
|
||
const session=await launchClaudePty({cwd,observeScreen:true,observeSetupQuestions:enabled,observePlanReady:enabled,
|
||
observeFilePermissions:enabled?[path.join(os.tmpdir(),'report.md')]:undefined,timeoutMs:10000,
|
||
env:{QUESTION_REPLAY:JSON.stringify({call:${JSON.stringify(packet)},first:${JSON.stringify(captured)}})}});
|
||
const owned=session.pendingQuestionFile;
|
||
try{await session.waitFor('Enter to select',{timeoutMs:5000,pollMs:20});
|
||
const transcript=()=>readPlanCountTranscript(session.hermeticConfigDir,cwd);
|
||
const pending=()=>readPendingQuestion(owned,cwd,session.hermeticConfigDir,startedAt,transcript());
|
||
if(transcript().calls.length)throw Error('unpublished packet manufactured JSONL coverage');
|
||
const inputs=[];
|
||
if(enabled){
|
||
if(pending()?.source!=='pre_tool_use'||pending()?.answered)throw Error('pending source was lost or counted as answer');
|
||
for(const [step,input] of ['1','1','\\r'].entries()){
|
||
const call=pending();
|
||
if(!call||transcript().calls.length)throw Error('pending identity lost or premature coverage');
|
||
inputs.push(input);session.send(input);
|
||
await session.waitFor(step===0?'☒ '+call.questions[0].header:step===1?'Ready to submit your answers?':'NATIVE_PACKET_COMPLETE',{timeoutMs:3000,pollMs:20});
|
||
}
|
||
if(pending())throw Error('completed replay reopened pending identity');
|
||
if(transcript().calls.length!==1||!transcript().calls[0].answered)throw Error('actual successful native result absent');
|
||
}else if(owned||pending())throw Error('recorder enabled by default');
|
||
results.push({enabled,inputs,native:transcript()});
|
||
}finally{await session.close();}
|
||
if(owned&&fs.existsSync(path.dirname(owned)))throw Error('normal close leaked recorder');
|
||
}
|
||
const cwd=path.join(root,'crash');fs.mkdirSync(cwd);
|
||
const crashed=await launchClaudePty({cwd,observeSetupQuestions:true,timeoutMs:5000,
|
||
env:{QUESTION_REPLAY:JSON.stringify({call:${JSON.stringify(packet)},first:${JSON.stringify(captured)},crash:true})}});
|
||
const owned=crashed.pendingQuestionFile;
|
||
while(!crashed.exited())await Bun.sleep(20);
|
||
if(crashed.exitCode()!==19||!fs.existsSync(owned))throw Error('crash did not execute recorder');
|
||
await crashed.close();if(fs.existsSync(path.dirname(owned)))throw Error('crashed close leaked recorder');
|
||
const spawn=Bun.spawn;Bun.spawn=()=>{throw Error('simulated spawn failure');};let rejected=false;
|
||
try{await launchClaudePty({cwd,observeSetupQuestions:true});}catch(e){rejected=String(e).includes('simulated spawn failure');}finally{Bun.spawn=spawn;}
|
||
if(!rejected||fs.readdirSync(os.tmpdir()).some(n=>n.startsWith('gstack-pending-question-')))throw Error('spawn failure leaked recorder');
|
||
fs.writeFileSync(${JSON.stringify(result)},JSON.stringify(results));
|
||
`);
|
||
const child = Bun.spawn([process.execPath, worker], {env:{...process.env,TMPDIR:workerTemp,
|
||
BROWSE_TERMINAL_BINARY:fake,EVALS_HERMETIC:'1'},stdout:'pipe',stderr:'pipe'});
|
||
const timer = setTimeout(() => child.kill('SIGKILL'), 22000);
|
||
try {
|
||
const [code,out,err] = await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);
|
||
expect(code,out+err).toBe(0);
|
||
const results=JSON.parse(fs.readFileSync(result,'utf8'));
|
||
expect(results.map((r:any)=>({enabled:r.enabled,inputs:r.inputs,calls:r.native.calls.length}))).toEqual([
|
||
{enabled:false,inputs:[],calls:0},{enabled:true,inputs:['1','1','\r'],calls:1}]);
|
||
for(const enabled of [false,true]) {
|
||
const events=fs.readFileSync(path.join(dir,String(enabled),'events.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
|
||
const settings=events.find(e=>e.kind==='settings').settings;
|
||
expect(settings?.hooks.PreToolUse.map((h:any)=>h.matcher)??[]).toEqual(enabled?['^ExitPlanMode$','^(Write|Edit)$','^AskUserQuestion$']:[]);
|
||
expect(events.filter(e=>e.kind==='hook').every(e=>e.code===0&&e.out===''&&e.err==='')).toBe(true);
|
||
expect(events.filter(e=>e.kind==='input').map(e=>e.input)).toEqual(enabled?['1','1','\r']:[]);
|
||
expect(identity(events[0].pid)).toBeNull();
|
||
}
|
||
} finally {
|
||
clearTimeout(timer);child.kill('SIGKILL');
|
||
for(const name of ['false','true','crash']) {
|
||
const file=path.join(dir,name,'events.jsonl');if(!fs.existsSync(file))continue;
|
||
const first=JSON.parse(fs.readFileSync(file,'utf8').split('\n')[0]!);
|
||
if(first.kind==='pid'&&first.identity?.includes(fake)&&identity(first.pid)===first.identity) {
|
||
try{process.kill(first.pid,'SIGKILL');}catch{/* already exited */}
|
||
}
|
||
}
|
||
fs.rmSync(dir,{recursive:true,force:true});
|
||
}
|
||
},25000);
|