diff --git a/changelog.d/flaky-fixes-2026-11-24.md b/changelog.d/flaky-fixes-2026-11-24.md new file mode 100644 index 000000000..a00b68e4e --- /dev/null +++ b/changelog.d/flaky-fixes-2026-11-24.md @@ -0,0 +1 @@ +**Three tests that failed at random now pass reliably.** The review-exploratory-small-cli eval no longer fails when the model re-reads HANDOFF.md with `offset: 1` after writing its review record, because a read from line 1 with no limit is the whole file. QA-only browser cleanup no longer fails when it runs before a headless browse daemon has started its terminal agent, and it starts over if that agent appears mid-cleanup; it still keeps the fixture whenever an agent it can't identify is running. The Office Hours abort test gives the killed background process up to 2 seconds to leave the process table. diff --git a/test/fixtures/qa-caller-handoff-order-public.json b/test/fixtures/qa-caller-handoff-order-public.json index 65ff82354..dfa026d91 100644 --- a/test/fixtures/qa-caller-handoff-order-public.json +++ b/test/fixtures/qa-caller-handoff-order-public.json @@ -297,5 +297,277 @@ } ] } - ] -} \ No newline at end of file + ], + "passingAttempts": [ + { + "source": "run 45216872389 paid-slice-9-a1 review-exploratory-small-cli", + "head": "c4cfe6d", + "sourceEventIndices": [ + 28, + 29, + 52, + 53, + 58, + 59, + 62, + 63, + 64, + 65, + 66, + 67 + ], + "events": [ + { + "type": "assistant", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "id": "msg_011ChLBP6BTgcACvAQj6gFHC", + "content": [ + { + "type": "tool_use", + "id": "toolu_0171qJUK1UCLNzmy1JzJ6qSt", + "name": "Read", + "input": { + "file_path": "/fixture-root/product/HANDOFF.md" + }, + "caller": { + "type": "direct" + } + } + ] + } + }, + { + "type": "user", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "content": [ + { + "tool_use_id": "toolu_0171qJUK1UCLNzmy1JzJ6qSt", + "type": "tool_result", + "content": "1\tNo concurrent input update.\n2\t" + } + ] + }, + "tool_use_result": { + "type": "text", + "file": { + "filePath": "/fixture-root/product/HANDOFF.md", + "content": "No concurrent input update.\n", + "numLines": 2, + "startLine": 1, + "totalLines": 2 + } + } + }, + { + "type": "assistant", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "id": "msg_011ChLBRwcbXVHTGxs2bFfZA", + "content": [ + { + "type": "tool_use", + "id": "toolu_017g8BPgyNwYbnzdQMF41WEk", + "name": "Read", + "input": { + "file_path": "/fixture-root/product/HANDOFF.md" + }, + "caller": { + "type": "direct" + } + } + ] + } + }, + { + "type": "user", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "content": [ + { + "tool_use_id": "toolu_017g8BPgyNwYbnzdQMF41WEk", + "type": "tool_result", + "content": "Wasted call \u2014 file unchanged since your last Read. Refer to that earlier tool_result instead." + } + ] + }, + "tool_use_result": { + "type": "file_unchanged", + "file": { + "filePath": "/fixture-root/product/HANDOFF.md" + } + } + }, + { + "type": "assistant", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "id": "msg_011ChLBT5LyZHRN7xKc3yHKN", + "content": [ + { + "type": "tool_use", + "id": "toolu_014Q9GJoAaCdzutYNVd69RxD", + "name": "Read", + "input": { + "file_path": "/fixture-root/product/HANDOFF.md" + }, + "caller": { + "type": "direct" + } + } + ] + } + }, + { + "type": "user", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "content": [ + { + "tool_use_id": "toolu_014Q9GJoAaCdzutYNVd69RxD", + "type": "tool_result", + "content": "Wasted call \u2014 file unchanged since your last Read. Refer to that earlier tool_result instead." + } + ] + }, + "tool_use_result": { + "type": "file_unchanged", + "file": { + "filePath": "/fixture-root/product/HANDOFF.md" + } + } + }, + { + "type": "assistant", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "id": "msg_011ChLBTX6H4QsDVgySnzydc", + "content": [ + { + "type": "tool_use", + "id": "toolu_01T8qK4ZSjgJS3pB4p7HDSEN", + "name": "Bash", + "input": { + "command": "/fixture-root/host/runtime/bin/gstack-review-log '{\"skill\":\"adversarial-review\",\"timestamp\":\"'\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"'\",\"status\":\"issues_found\",\"source\":\"in-host\",\"host\":\"claude\",\"outside_provider\":\"codex\",\"outside_status\":\"unavailable\",\"phase\":\"adversarial\",\"tier\":\"always\",\"gate\":\"informational\",\"commit\":\"'\"$(git rev-parse --short HEAD)\"'\",\"completed\":true,\"converged\":true}' --finish df3af407-565f-48a1-9255-0661b3061fed", + "description": "Record native adversarial review result" + }, + "caller": { + "type": "direct" + } + } + ] + } + }, + { + "type": "user", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "content": [ + { + "tool_use_id": "toolu_01T8qK4ZSjgJS3pB4p7HDSEN", + "type": "tool_result", + "content": "(Bash completed with no output)", + "is_error": false + } + ] + }, + "tool_use_result": { + "interrupted": false + } + }, + { + "type": "assistant", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "id": "msg_011ChLBTX6H4QsDVgySnzydc", + "content": [ + { + "type": "tool_use", + "id": "toolu_01TDZUTrW3LVs4Bv7LxZjGRo", + "name": "Bash", + "input": { + "command": "/fixture-root/host/runtime/bin/gstack-review-log '{\"skill\":\"review\",\"timestamp\":\"'\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"'\",\"status\":\"issues_found\",\"issues_found\":1,\"critical\":1,\"informational\":0,\"quality_score\":10,\"specialists\":{},\"findings\":[{\"severity\":\"CRITICAL\",\"confidence\":10,\"path\":\"scale.ts\",\"line\":3,\"category\":\"functional-contract\",\"fingerprint\":\"scale.ts:3:functional-contract\",\"action\":\"open\",\"summary\":\"!n guard rejects documented valid input 0\"}],\"commit\":\"'\"$(git rev-parse --short HEAD)\"'\",\"completed\":false,\"converged\":false,\"cycles\":1}' --finish e1bfd809-db4d-4d1a-b7b9-64c7d086b385", + "description": "Record review result stopped at gate" + }, + "caller": { + "type": "direct" + } + } + ] + } + }, + { + "type": "user", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "content": [ + { + "tool_use_id": "toolu_01TDZUTrW3LVs4Bv7LxZjGRo", + "type": "tool_result", + "content": "(Bash completed with no output)", + "is_error": false + } + ] + }, + "tool_use_result": { + "interrupted": false + } + }, + { + "type": "assistant", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "id": "msg_011ChLBU4AoRK5WzApS9ZYfD", + "content": [ + { + "type": "tool_use", + "id": "toolu_01BbTrEf5s4mXH7iZXJrvuA8", + "name": "Read", + "input": { + "file_path": "/fixture-root/product/HANDOFF.md", + "offset": 1 + }, + "caller": { + "type": "direct" + } + } + ] + } + }, + { + "type": "user", + "parent_tool_use_id": null, + "session_id": "68631ee2-56e5-4978-989b-9837ceaefd0f", + "message": { + "content": [ + { + "tool_use_id": "toolu_01BbTrEf5s4mXH7iZXJrvuA8", + "type": "tool_result", + "content": "Wasted call \u2014 file unchanged since your last Read. Refer to that earlier tool_result instead." + } + ] + }, + "tool_use_result": { + "type": "file_unchanged", + "file": { + "filePath": "/fixture-root/product/HANDOFF.md" + } + } + } + ] + } + ], + "passingNote": "Public events (native-events.json indices) from a review-exploratory-small-cli attempt that read HANDOFF.md in full, wrote its completed:true records after unchanged re-reads, then re-read it with {offset: 1} and no limit; fixture paths are rewritten to /fixture-root." +} diff --git a/test/helpers/qa-callers-fixture.ts b/test/helpers/qa-callers-fixture.ts index 4e7897c41..a6aabccac 100644 --- a/test/helpers/qa-callers-fixture.ts +++ b/test/helpers/qa-callers-fixture.ts @@ -90,7 +90,8 @@ export function callerTools(transcript: unknown[]): CallerTool[] { tools.push(tool); const native = event.tool_use_result; if (!tool.failed && tool.name === 'Read' && typeof tool.input.file_path === 'string' - && tool.input.file_path.endsWith('/HANDOFF.md') && Object.keys(tool.input).length === 1 + && tool.input.file_path.endsWith('/HANDOFF.md') + && Object.keys(tool.input).every(key => key === 'file_path' || key === 'offset' && tool.input.offset === 1) && typeof tool.sessionId === 'string' && event.session_id === tool.sessionId && event.message.content.length === 1 && native?.file?.filePath === tool.input.file_path) { if (native.type === 'text' && typeof native.file.content === 'string') { diff --git a/test/helpers/qa-only-cleanup.ts b/test/helpers/qa-only-cleanup.ts index be6a69243..74ed64a5f 100644 --- a/test/helpers/qa-only-cleanup.ts +++ b/test/helpers/qa-only-cleanup.ts @@ -22,6 +22,8 @@ export async function stopQaOnlyBrowser(directory: string, timeoutMs: number): P } finally { clearTimeout(timer); } } +const TERMINAL_PUBLISHED = Symbol('terminal published during identification'); + async function settleOwnedBrowser(directory: string, deadlineEpochMs: number): Promise { const started = performance.now(); const timeoutMs = deadlineEpochMs - Date.now(); @@ -53,30 +55,50 @@ async function settleOwnedBrowser(directory: string, deadlineEpochMs: number): P || typeof state.instanceId !== 'string' || !state.instanceId) fail('invalid daemon identity'); const agentRaw = fs.existsSync(agentFile) ? fs.readFileSync(agentFile, 'utf8') : undefined; const agent = readAgentRecord(stateDir); + if (agent?.pid === 0) { + // spawnTerminalAgent holds a pid-0 reservation for the instant between spawn and its real record. + await Bun.sleep(Math.min(25, remaining())); + throw TERMINAL_PUBLISHED; + } + const processCwd = (pid: number): string => { + if (process.platform === 'linux') { + try { return fs.realpathSync(`/proc/${pid}/cwd`); } catch { return ''; } + } + const result = spawnSync('lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'], { + encoding: 'utf8', timeout: Math.min(1000, remaining()), + }); + return result.error || result.status !== 0 ? '' : result.stdout.split('\n').find(line => line.startsWith('n'))?.slice(1) ?? ''; + }; if (!agentRaw || !agent) { - // Qa-only-no-fix (census 41962523474) failed here once with nothing else to go on; name what was there instead. - const log = path.join(stateDir, 'browse-daemon.log'); - const agentLines = fs.existsSync(log) && fs.lstatSync(log).isFile() - ? fs.readFileSync(log, 'utf8').split('\n').filter(line => /terminal-agent/i.test(line)).slice(-3).map(line => line.slice(0, 160)) : []; - fail(`terminal identity is unavailable (record ${agentRaw === undefined ? 'absent' : `unparsed, ${agentRaw.length} bytes`}; ` - + `terminal-port ${fs.existsSync(path.join(stateDir, 'terminal-port')) ? 'present' : 'absent'}; daemon ${state.pid} ` - + `${isProcessAlive(state.pid) ? 'alive' : 'exited'}, state written ${Math.round((Date.now() - fs.statSync(stateFile).mtimeMs) / 1000)}s ago; ` - + `daemon log terminal-agent lines: ${agentLines.length ? agentLines.join(' | ') : 'none'})`); + // A headless daemon starts its terminal agent only on its first watchdog tick (60 s by default), so a record that + // was never written is not a lost agent. Settle without one only when no agent of this fixture is running. + const matches = spawnSync('pgrep', ['-f', '--', '--agent-gen='], { encoding: 'utf8', timeout: Math.min(1000, remaining()) }); + if (matches.error || ![0, 1].includes(matches.status ?? -1)) fail('terminal agent identities are unavailable'); + const fixtureAgents = matches.stdout.split('\n').map(Number).filter(pid => { + if (!Number.isSafeInteger(pid) || pid <= 1 || !/terminal-agent/.test(readPidCmdline(pid))) return false; + const cwd = processCwd(pid); + if (!cwd && isProcessAlive(pid)) fail(`terminal agent ${pid} has no readable working directory`); + return cwd === root; + }); + const port = fs.existsSync(path.join(stateDir, 'terminal-port')); + if (agentRaw !== undefined || port || fixtureAgents.length) { + // Qa-only-no-fix (census 41962523474) failed here once with nothing else to go on; name what was there instead. + const log = path.join(stateDir, 'browse-daemon.log'); + const agentLines = fs.existsSync(log) && fs.lstatSync(log).isFile() + ? fs.readFileSync(log, 'utf8').split('\n').filter(line => /terminal-agent/i.test(line)).slice(-3).map(line => line.slice(0, 160)) : []; + fail(`terminal identity is unavailable (record ${agentRaw === undefined ? 'absent' : `unparsed, ${agentRaw.length} bytes`}; ` + + `terminal-port ${port ? 'present' : 'absent'}; running fixture agents: ${fixtureAgents.length ? fixtureAgents.join(', ') : 'none'}; ` + + `daemon ${state.pid} ${isProcessAlive(state.pid) ? 'alive' : 'exited'}, state written ${Math.round((Date.now() - fs.statSync(stateFile).mtimeMs) / 1000)}s ago; ` + + `daemon log terminal-agent lines: ${agentLines.length ? agentLines.join(' | ') : 'none'})`); + } } if (!isProcessAlive(state.pid)) fail('daemon exited before its owned processes could be identified'); const daemonStart = readPidStartTime(state.pid); const command = readPidCmdline(state.pid); if (!daemonStart || !(typeof state.serverPath === 'string' && command.includes(state.serverPath) || command.includes('--server') && /browse/.test(command))) fail('daemon identity is unavailable'); - let cwd: string; - if (process.platform === 'linux') cwd = fs.realpathSync(`/proc/${state.pid}/cwd`); - else { - const result = spawnSync('lsof', ['-a', '-p', String(state.pid), '-d', 'cwd', '-Fn'], { - encoding: 'utf8', timeout: Math.min(1000, remaining()), - }); - if (result.error || result.status !== 0) fail('daemon working directory is unavailable'); - cwd = result.stdout.split('\n').find(line => line.startsWith('n'))?.slice(1) ?? ''; - } + const cwd = processCwd(state.pid); + if (!cwd) fail('daemon working directory is unavailable'); if (cwd !== root) fail('daemon belongs to another fixture'); if (agent && (agent.ownerPid !== state.pid || agent.ownerStartTime !== daemonStart || !isAgentRecordGone(agent) && !isOurAgent(agent, state.pid))) fail('terminal ownership is unconfirmed'); @@ -103,12 +125,17 @@ async function settleOwnedBrowser(directory: string, deadlineEpochMs: number): P const state = current(stateFile); if (state !== undefined && state !== raw) fail('daemon state was replaced'); const terminal = current(agentFile); - if (terminal !== undefined && terminal !== agentRaw) fail('terminal state was replaced'); + if (terminal === undefined || terminal === agentRaw) return; + // The first watchdog tick can publish the terminal while the daemon is still unsignalled: identify it from the top. + if (agentRaw === undefined && !signalled) throw TERMINAL_PUBLISHED; + fail('terminal state was replaced'); }; + let signalled = false; unchanged(); if (readPidStartTime(state.pid) !== daemonStart || readPidCmdline(state.pid) !== command) fail('daemon identity changed before stop'); unchanged(); remaining(); + signalled = true; try { process.kill(state.pid, 'SIGINT'); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error; } const settled = (pid: number, start: string) => { @@ -149,8 +176,12 @@ async function settleOwnedBrowser(directory: string, deadlineEpochMs: number): P } if (import.meta.main) { - try { await settleOwnedBrowser(process.argv[2], Number(process.argv[3])); } - catch (error) { + try { + for (;;) { + try { await settleOwnedBrowser(process.argv[2], Number(process.argv[3])); break; } + catch (error) { if (error !== TERMINAL_PUBLISHED) throw error; } + } + } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; } diff --git a/test/office-hours-attempt.test.ts b/test/office-hours-attempt.test.ts index f52199b39..525961f5f 100644 --- a/test/office-hours-attempt.test.ts +++ b/test/office-hours-attempt.test.ts @@ -295,8 +295,12 @@ describe('Office Hours real session runner with fake processes', () => { expect(captured.output).toBe('captured output'); expect(captured.costEstimate.estimatedCost).toBe(0.12); expect(captured.duration).toBeLessThan(5_000); + // The runner waits for the provider's exit; the group SIGKILL reaches the backgrounded child at the same time, + // but nothing orders its teardown before that exit, so a loaded runner can still list it for a moment. for (const file of ['parent.pid', 'child.pid']) { - expect(running(Number(fs.readFileSync(path.join(dir, file), 'utf8')))).toBe(false); + const pid = Number(fs.readFileSync(path.join(dir, file), 'utf8')); + for (const until = performance.now() + 2_000; running(pid) && performance.now() < until;) await Bun.sleep(20); + expect(running(pid)).toBe(false); } } finally { clearTimeout(timer); } }); diff --git a/test/qa-exploratory-callers.test.ts b/test/qa-exploratory-callers.test.ts index 6b64047f2..4c66d180d 100644 --- a/test/qa-exploratory-callers.test.ts +++ b/test/qa-exploratory-callers.test.ts @@ -263,6 +263,25 @@ describe('caller native-event observer controls', () => { expect(validateCallerEvidence(observed)).toEqual([]); }); + // Gate census 45216872389 paid-slice-9-a1: after full and unchanged HANDOFF.md Reads, the completed:true records came + // first and a Read {offset: 1} with no limit followed, which the runtime answered file_unchanged. Offset 1 with no + // limit reads the whole file, so the captured order passes; any other range stays a partial read and is flagged. + test.each(capturedHandoffOrder.passingAttempts.map(attempt => [attempt.source, attempt] as const)) + ('captured offset-1 handoff re-read after the completion record is a full read: %s', (_, attempt) => { + const observed = evidence(); + const base = observed.result.transcript; + const lastRead = (events: any[]) => events.findLast(event => event.message.content[0].name === 'Read').message.content[0]; + observed.result.transcript = [...base, ...structuredClone(attempt.events)]; + expect(lastRead(observed.result.transcript as any[]).input).toEqual({ file_path: '/fixture-root/product/HANDOFF.md', offset: 1 }); + expect(validateCallerEvidence(observed)).toEqual([]); + for (const partial of [{ offset: 2 }, { offset: 1, limit: 1 }, { offset: '1' }, { limit: 2000 }]) { + const events = structuredClone(attempt.events) as any[]; + lastRead(events).input = { file_path: '/fixture-root/product/HANDOFF.md', ...partial }; + observed.result.transcript = [...base, ...events]; + expect(validateCallerEvidence(observed)).toEqual(['review completion preceded handoff freshness decision']); + } + }); + test('captured gate-census-5 review record: bun-wrapped helper and receipt status are outside the interface', () => { // ci-36629958451-1-gate-census-5 review-exploratory-small-cli, native events 68 and 70 (fixture paths shortened). const record = (status: string) => `/runtime/bin/gstack-review-log '{"skill":"review","timestamp":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'","commit":"'"$(git rev-parse --short HEAD)"'","branch":"caller-change","status":"${status}","completed":false,"converged":false,"critical":1,"informational":0,"findings":[{"path":"scale.ts","line":3,"category":"functional-contract","severity":"CRITICAL","fingerprint":"scale.ts:3:functional-contract","action":"ask-pending"}]}' --finish d45404cf-ba19-4bc6-a505-9801e9322f54`; diff --git a/test/qa-only-cleanup.test.ts b/test/qa-only-cleanup.test.ts index 3ee38b900..08ef76725 100644 --- a/test/qa-only-cleanup.test.ts +++ b/test/qa-only-cleanup.test.ts @@ -5,7 +5,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { stopQaOnlyBrowser } from './helpers/qa-only-cleanup'; import { isAgentRecordGone, isOurAgent, readAgentRecord, spawnTerminalAgent, stopAgentByRecord } from '../browse/src/terminal-agent-control'; -import { readPidStartTime } from '../browse/src/xvfb'; +import { readPidCmdline, readPidStartTime } from '../browse/src/xvfb'; const ROOT = path.resolve(import.meta.dir, '..'); const waitFor = async (check: () => boolean, timeout = 10_000) => { @@ -45,7 +45,7 @@ test('linked owned state cannot redirect cleanup to a sibling', async () => { } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); -test.each(['ack-only', 'replaced-state', 'terminal-mismatch', 'chromium-mismatch', 'missing-terminal', 'blocked-identity'])('cleanup refuses unconfirmed settlement: %s', async scenario => { +test.each(['ack-only', 'replaced-state', 'terminal-mismatch', 'chromium-mismatch', 'missing-terminal', 'unrecorded-terminal', 'unlisted-agents', 'blocked-identity'])('cleanup refuses unconfirmed settlement: %s', async scenario => { const dir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'qa-clean-')); const stateDir = path.join(dir, '.gstack'); fs.mkdirSync(stateDir); @@ -75,6 +75,7 @@ fs.writeFileSync(${JSON.stringify(path.join(dir, 'port'))}, String(server.port)) let agent: ReturnType; let restore: (() => void) | undefined; let worker: ReturnType | undefined; + let stray: ReturnType | undefined; try { await waitFor(() => fs.existsSync(path.join(dir, 'port'))); const port = Number(fs.readFileSync(path.join(dir, 'port'), 'utf8')); @@ -87,6 +88,23 @@ fs.writeFileSync(${JSON.stringify(path.join(dir, 'port'))}, String(server.port)) chromiumPid, chromiumStartTime: scenario === 'chromium-mismatch' ? 'stale start' : readPidStartTime(chromiumPid) })); const agentFile = path.join(stateDir, 'terminal-agent-pid'); if (scenario === 'terminal-mismatch') fs.writeFileSync(agentFile, JSON.stringify({ ...agent, ownerPid: process.pid })); + if (scenario === 'unrecorded-terminal') { + expect(stopAgentByRecord(agent!, 300)).toBe(true); + for (const file of [agentFile, path.join(stateDir, 'terminal-port')]) fs.rmSync(file, { force: true }); + stray = Bun.spawn([process.execPath, '-e', 'setInterval(() => {}, 1000)', 'browse/src/terminal-agent.ts', '--agent-gen=unrecorded'], { cwd: dir }); + await waitFor(() => /terminal-agent/.test(readPidCmdline(stray!.pid))); + } + if (scenario === 'unlisted-agents') { + expect(stopAgentByRecord(agent!, 300)).toBe(true); + for (const file of [agentFile, path.join(stateDir, 'terminal-port')]) fs.rmSync(file, { force: true }); + const bin = path.join(dir, 'bin'); + fs.mkdirSync(bin); + fs.writeFileSync(path.join(bin, 'pgrep'), '#!/bin/sh\nexit 2\n', { mode: 0o755 }); + const original = Bun.spawn; + const spy = spyOn(Bun, 'spawn').mockImplementation(((args: string[], options: any) => + original(args, { ...options, env: { ...process.env, PATH: bin + path.delimiter + process.env.PATH } })) as typeof Bun.spawn); + restore = () => spy.mockRestore(); + } if (scenario === 'missing-terminal') { fs.unlinkSync(agentFile); fs.writeFileSync(path.join(stateDir, 'browse-daemon.log'), '[browse] terminal-agent exit remains unconfirmed: fixture\n'); @@ -116,7 +134,10 @@ Bun.spawnSync = (...args) => { const started = performance.now(); const errors = { 'ack-only': 'settlement deadline exceeded', 'replaced-state': 'daemon state was replaced', 'terminal-mismatch': 'terminal ownership is unconfirmed', 'chromium-mismatch': 'Chromium ownership is unconfirmed', - 'missing-terminal': /terminal identity is unavailable \(record absent; terminal-port .*daemon log terminal-agent lines: \[browse\] terminal-agent exit remains unconfirmed: fixture\)/, 'blocked-identity': 'owned worker settlement deadline exceeded' }; + 'missing-terminal': /terminal identity is unavailable \(record absent; terminal-port .*daemon log terminal-agent lines: \[browse\] terminal-agent exit remains unconfirmed: fixture\)/, + 'unrecorded-terminal': new RegExp(`terminal identity is unavailable \\(record absent; terminal-port absent; running fixture agents: ${stray?.pid}; daemon ${daemon.pid} alive`), + 'unlisted-agents': 'terminal agent identities are unavailable', + 'blocked-identity': 'owned worker settlement deadline exceeded' }; await expect(stopQaOnlyBrowser(dir, 1000)).rejects.toThrow(errors[scenario]); expect(performance.now() - started).toBeLessThan(2000); expect(daemon.exitCode).toBeNull(); @@ -132,6 +153,7 @@ Bun.spawnSync = (...args) => { expect(fs.existsSync(requestFile)).toBe(false); } finally { restore?.(); + stray?.kill('SIGKILL'); if (agent) expect(stopAgentByRecord(agent, 300)).toBe(true); daemon.kill(); await daemon.exited; @@ -139,6 +161,63 @@ Bun.spawnSync = (...args) => { } }, 15_000); +// Census 45122546426 (qa-only-no-fix): cleanup ran 58 s after a headless daemon started, before its first 60 s watchdog +// tick spawned a terminal agent, and failed on the record that had never been written ("daemon log terminal-agent +// lines: none"). The same daemon before its first tick settles with Chromium and no terminal. +test.each(['no-terminal', 'published-mid-cleanup'])('a real headless daemon settles before its first watchdog tick has started a terminal: %s', async scenario => { + const dir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'qa-tick-')); + const stateDir = path.join(dir, '.gstack'); + const stateFile = path.join(stateDir, 'browse.json'); + let restore: (() => void) | undefined; + const child = Bun.spawn([process.execPath, path.join(ROOT, 'browse/src/server.ts')], { + cwd: dir, stdout: Bun.file(path.join(dir, 'server.log')), stderr: Bun.file(path.join(dir, 'server-error.log')), + env: { ...process.env, PATH: path.dirname(process.execPath) + path.delimiter + process.env.PATH, + BROWSE_STATE_FILE: stateFile, BROWSE_PORT: '0', BROWSE_PARENT_PID: '0', BROWSE_HEADED: '0', BROWSE_HEADLESS_SKIP: '0', + GSTACK_AGENT_WATCHDOG_TICK_MS: '600000', TMPDIR: dir, TMP: dir, TEMP: dir, CHROMIUM_PROFILE: path.join(dir, 'profile') }, + }); + try { + await waitFor(() => fs.existsSync(stateFile) && JSON.parse(fs.readFileSync(stateFile, 'utf8')).chromiumPid !== undefined); + expect(fs.existsSync(path.join(stateDir, 'terminal-agent-pid'))).toBe(false); + expect(fs.existsSync(path.join(stateDir, 'terminal-port'))).toBe(false); + const { pid, port, chromiumPid, chromiumStartTime } = JSON.parse(fs.readFileSync(stateFile, 'utf8')); + if (scenario === 'published-mid-cleanup') { + // The tick fires after cleanup read the missing record and before it signals the daemon. + const preload = path.join(dir, 'publish-terminal.ts'); + fs.writeFileSync(preload, ` +import { spawnTerminalAgent } from ${JSON.stringify(path.join(ROOT, 'browse/src/terminal-agent-control.ts'))}; +const original = Bun.spawnSync; +let published = false; +Bun.spawnSync = (...args) => { + if (!published && args[0][0] === 'ps') { + published = true; + const agent = spawnTerminalAgent({ stateFile: ${JSON.stringify(stateFile)}, serverPort: ${port}, ownerPid: ${pid}, cwd: ${JSON.stringify(dir)} }); + require('node:fs').writeFileSync(${JSON.stringify(path.join(dir, 'published-pid'))}, String(agent)); + } + return original(...args); +}; +`); + const original = Bun.spawn; + const spy = spyOn(Bun, 'spawn').mockImplementation(((args: string[], options: any) => + original([args[0], '--preload', preload, ...args.slice(1)], options)) as typeof Bun.spawn); + restore = () => spy.mockRestore(); + } + await stopQaOnlyBrowser(dir, 4000); + restore?.(); + expect([0, 137]).toContain(await child.exited); + expect(readPidStartTime(chromiumPid) === chromiumStartTime).toBe(false); + if (scenario === 'published-mid-cleanup') { + const published = Number(fs.readFileSync(path.join(dir, 'published-pid'), 'utf8')); + expect(published).toBeGreaterThan(0); + expect(readPidCmdline(published)).not.toContain('terminal-agent'); + } + expect(readAgentRecord(stateDir)).toBeNull(); + } finally { + restore?.(); + if (child.exitCode === null) { child.kill('SIGKILL'); await child.exited; } + fs.rmSync(dir, { recursive: true, force: true }); + } +}, 30_000); + test.each(['owned-endpoint', 'sibling-endpoint'])('real Chromium and terminal settle before removal without harming a live sibling or recreating state: %s', async scenario => { const page = Bun.serve({ port: 0, fetch: () => new Response('

Owned QA fixture

', { headers: { 'Content-Type': 'text/html' } }) }); const fixtures: Array<{ dir: string; child: ReturnType; state?: any; agent?: ReturnType }> = [];