Tests that copy their own bun no longer trip the review fetch check (GST-4112) (#4876)

A test that copies the host's own `bun` binary into a temp folder no
longer stops `/gstack-ship` with a fetch violation, and Codex prompt
files from `/plan-ceo-review` and `/plan-eng-review` can no longer be
committed by accident.

It keeps shipping runs from stopping for no reason and keeps scratch
files out of commits; the `/autoplan` guard now also treats Claude Code
2.1.326, the version CI runs, as checked.

Nothing to do after merge.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=testing
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p2/outside-voice#2 reader=outside-voice
Review-Finding: p2/adversarial-native#3 reader=adversarial-native
Review-Finding: p2/outside-voice#3 reader=outside-voice
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-28 15:09:08 +00:00
1 parent 44df37961b
commit dfbdccf4c1
15 files changed
+283 -23

No files matched your search

+2 -2
View File
@@ -21,9 +21,9 @@ describe('guard reason inventory', () => {
test('no denial advises a retry; transients say what to wait for; fallbacks print the runnable fallback', () => {
for (const [code, reason] of Object.entries(REASONS)) {
const text = reasonText(code, sample, '2.1.292');
const text = reasonText(code, sample, '2.1.292'); // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' a sample version string for the reason text, not the checked pin
expect({ code, retry: /\bretry/i.test(text) }).toEqual({ code, retry: false });
expect(text).toContain(`(code ${code}, Claude Code 2.1.292)`);
expect(text).toContain(`(code ${code}, Claude Code 2.1.292)`); // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' echoes the sample version passed in above
expect(text).toContain(`${GUIDE}#${anchor(code)}`);
if (reason.disposition === 'transient') expect(text).toMatch(/\bWait for\b/);
if (reason.disposition === 'fallback') expect(text).toContain(FALLBACK);
+31 -11
View File
@@ -14,6 +14,7 @@ import { AGENT_KEYS, CHECKED_CLAUDE_CODE, evaluatePayloadPublication, nativeTool
import { readOwnedClaudePublicTranscript } from '../lib/claude-owned-journal';
import { nativePathSpelling } from '../lib/claude-public-transcript';
import captured from './fixtures/claude-agent-payload-2.1.292.json';
import latest from './fixtures/claude-agent-payload-2.1.326.json';
import { OWNED_READ_APPROVAL } from '../autoplan/bin/owned-read';
const fixtures: GuardFixture[] = [];
@@ -21,7 +22,7 @@ afterEach(() => { for (const f of fixtures.splice(0)) f.cleanup(); });
const make = (...args: Parameters<typeof guardFixture>) => { const f = guardFixture(...args); fixtures.push(f); return f; };
const dispatch = (f: GuardFixture, extra: Record<string, unknown> = {}) =>
({ description: 'CEO review', subagent_type: 'general-purpose', prompt: f.snapshot.nativeDispatchPrompt, ...extra });
/** The schema-parsed payload: what Claude Code 2.1.292 with the fork-subagent gate hands PreToolUse. */
/** The schema-parsed payload: what Claude Code 2.1.292 with the fork-subagent gate hands PreToolUse. */ // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' names the release the original #3062 capture came from
const parsed = (input: Record<string, unknown>) => { const { run_in_background: _drop, ...rest } = input; return rest; };
describe('Cause A: the Agent schema strips run_in_background', () => {
@@ -32,7 +33,7 @@ describe('Cause A: the Agent schema strips run_in_background', () => {
f.use('review', 'Agent', raw); f.journal();
const output = await f.hook(f.input('review', 'Agent', parsed(raw)));
expect(output).toEqual({});
expect(f.log().at(-1)).toMatchObject({ decision: 'allow', path: 'journal', claude_code_version: '2.1.292' });
expect(f.log().at(-1)).toMatchObject({ decision: 'allow', path: 'journal', claude_code_version: '2.1.292' }); // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' the fixture journal's default version, echoed into the log
});
test('journal-path negative controls stay denied: changed prompt, added model, changed description', async () => {
@@ -62,18 +63,37 @@ describe('Cause A: the Agent schema strips run_in_background', () => {
expect(JSON.stringify(f.log())).not.toContain('claude-opus-secret-value');
});
test('the allowlist covers every Agent key Claude Code 2.1.292 hands PreToolUse', () => {
for (const payload of captured.agentPayloads) for (const key of Object.keys(payload.tool_input)) expect(AGENT_KEYS).toContain(key);
expect(CHECKED_CLAUDE_CODE).toBe(captured.claudeCodeVersion);
test('the allowlist covers every Agent key Claude Code 2.1.292 and 2.1.326 hand PreToolUse, and the checked release is the newest capture', () => { // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' names the older capture beside the checked one
for (const payload of [...captured.agentPayloads, ...latest.agentPayloads]) for (const key of Object.keys(payload.tool_input)) expect(AGENT_KEYS).toContain(key);
expect(CHECKED_CLAUDE_CODE).toBe(latest.claudeCodeVersion);
expect(nativeToolInput({ prompt: 'p', run_in_background: 'false' }, '/', 'Agent')).toEqual({ prompt: 'p' });
expect(nativeToolInput({ file_path: 'x', run_in_background: true }, '/', 'Read'))
.toEqual({ file_path: nativePathSpelling(path.resolve('/', 'x')), run_in_background: true });
});
// Value: protects=the guard on Claude Code 2.1.326 as captured (#4822 moved CI to it): its PreToolUse payload, with the new effort key beside the
// schema-parsed Agent input, passes for the forced run_in_background dispatch, and a strip of any other key is denied, not waved through as an
// unseen version; fails_when=the pin still reads 2.1.292, so every 2.1.326 strip is only a warning, or the new payload key breaks the hook; // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' describes the old pin this test guards against
// why_new=GST-4112 (#4822 follow-up); seam=runPublicationHook journal path; no_claim=interactive flush timing on 2.1.326
test('2.1.326 as captured: the forced dispatch passes the hook, and any other strip is denied', async () => {
const shape = Object.fromEntries(latest.payloadKeys.filter(key => !['session_id', 'transcript_path', 'cwd', 'hook_event_name', 'tool_name', 'tool_input', 'tool_use_id'].includes(key))
.map(key => [key, key === 'effort' ? { level: 'medium' } : key === 'permission_mode' ? 'default' : 'prompt-1']));
expect(Object.keys(shape).sort()).toEqual(['effort', 'permission_mode', 'prompt_id']);
const allowed = make('ceo', { version: '2.1.326' });
const raw = dispatch(allowed, { run_in_background: latest.forcedRunInBackground.journalInput.run_in_background });
allowed.use('review', 'Agent', raw); allowed.journal();
expect(await allowed.hook({ ...allowed.input('review', 'Agent', parsed(raw)), ...shape })).toEqual({});
expect(allowed.log().at(-1)).toMatchObject({ decision: 'allow', path: 'journal', claude_code_version: '2.1.326' });
const denied = make('ceo', { version: '2.1.326' });
const sent = dispatch(denied); denied.use('review', 'Agent', sent); denied.journal();
const { description: _gone, ...stripped } = sent;
expect(codeOf(await denied.hook({ ...denied.input('review', 'Agent', stripped), ...shape }))).toBe('current_mismatch');
});
test('UC1: a pure strip by a newer, unchecked Claude Code is unverified; the same strip on a checked version is denied', async () => {
expect(newerThanChecked('2.1.300')).toBe(true);
expect(newerThanChecked('2.1.400')).toBe(true);
expect(newerThanChecked(CHECKED_CLAUDE_CODE)).toBe(false);
for (const [version, expected] of [['2.1.300', 'unseen_version'], ['2.1.292', 'current_mismatch']] as const) {
for (const [version, expected] of [['2.1.400', 'unseen_version'], [CHECKED_CLAUDE_CODE, 'current_mismatch'], ['2.1.292', 'current_mismatch']] as const) { // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' an older known release, an input on purpose
const f = make('ceo', { version });
const raw = dispatch(f); f.use('review', 'Agent', raw); f.journal();
const { description: _gone, ...stripped } = raw;
@@ -82,7 +102,7 @@ describe('Cause A: the Agent schema strips run_in_background', () => {
if (expected === 'unseen_version') {
expect(output.hookSpecificOutput.permissionDecision).toBeUndefined();
expect(output.systemMessage).toContain('description');
expect(f.log().at(-1)).toMatchObject({ decision: 'allow', disposition: 'unverified', code: 'unseen_version', claude_code_version: '2.1.300' });
expect(f.log().at(-1)).toMatchObject({ decision: 'allow', disposition: 'unverified', code: 'unseen_version', claude_code_version: '2.1.400' });
} else expect(denial(output)).toBeDefined();
}
});
@@ -152,7 +172,7 @@ describe('Publication flush: a report counts only once a later journaled record
test('ENG-2: the same publish-separately cause seen twice in one invocation switches to the fallback', async () => {
// The first report never reached the journal; after its denial the republished report is still the last record.
const f = make(); f.use('denied', 'Read', { file_path: section('design-phase.md') });
f.result('denied', { isError: true, content: '[autoplan] The Phase 1 report ... (code publication_unflushed, Claude Code 2.1.292).' });
f.result('denied', { isError: true, content: '[autoplan] The Phase 1 report ... (code publication_unflushed, Claude Code 2.1.292).' }); // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' a recorded denial text from the older release
f.report(f.nextMessage()); f.journal();
const output = await f.hook(next(f));
expect(codeOf(output)).toBe('publication_repeat');
@@ -162,7 +182,7 @@ describe('Publication flush: a report counts only once a later journaled record
test('a denied call after the report proves the report was journaled, so the next attempt counts it', async () => {
const f = make(); const m = f.nextMessage(); f.report(m);
f.use('denied', 'Read', { file_path: section('design-phase.md') }, m);
f.result('denied', { isError: true, content: '(code publication_unflushed, Claude Code 2.1.292)' }); f.journal();
f.result('denied', { isError: true, content: '(code publication_unflushed, Claude Code 2.1.292)' }); f.journal(); // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' a recorded denial text from the older release
expect(await f.hook(next(f))).toEqual(OWNED_READ_APPROVAL);
});
@@ -297,7 +317,7 @@ describe('Cause C: the hook runs before Claude Code flushes the turn it acts in
});
});
test('the captured 2.1.292 evidence fixture records Cause A exactly', () => {
test('the captured 2.1.292 evidence fixture records Cause A exactly', () => { // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' names the 2.1.292 evidence fixture
const forced = captured.forcedRunInBackground;
expect(forced.journalInput.run_in_background).toBe('false');
expect('run_in_background' in forced.payloadInput).toBe(false);
+7 -1
View File
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test';
import { schemaDrift, type HookPayload } from './helpers/schema-canary';
import { SCHEMA_STRIPPED, nativeToolInput } from '../autoplan/bin/phase-publication-hook.ts';
import captured from './fixtures/claude-agent-payload-2.1.292.json';
import latest from './fixtures/claude-agent-payload-2.1.326.json';
const cwd = '/repo';
const read: HookPayload = { tool_name: 'Read', tool_use_id: 'toolu_read', cwd, tool_input: { file_path: '/repo/note.txt' } };
@@ -18,11 +19,16 @@ describe('autoplan-schema-canary comparison', () => {
expect(nativeToolInput(journalInput, cwd, 'Read')).not.toEqual(nativeToolInput(payloadInput, cwd, 'Read'));
});
test('2.1.292 as captured: run_in_background stripped from the payload is the documented strip', () => {
test('2.1.292 as captured: run_in_background stripped from the payload is the documented strip', () => { // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' the older capture, kept beside the 2.1.326 one
const { payloadInput, journalInput } = captured.forcedRunInBackground;
expect(schemaDrift([read, agent(payloadInput)], journal(journalInput))).toEqual([]);
});
test('2.1.326 as captured: the same documented strip, and nothing else', () => {
const { payloadInput, journalInput } = latest.forcedRunInBackground;
expect(schemaDrift([read, agent(payloadInput)], journal(journalInput))).toEqual([]);
});
test('an injected strip of another key fails', () => {
const { payloadInput, journalInput } = captured.forcedRunInBackground;
const { description: _gone, ...stripped } = payloadInput;
+65
View File
@@ -0,0 +1,65 @@
{
"claudeCodeVersion": "2.1.326",
"captured": "2026-11-28, headless claude -p of the npm 2.1.326 linux-x64 binary (registry signatures verified, installed with --ignore-scripts), default permission mode, CLAUDE_CODE_FORK_SUBAGENT=1 as autoplan-schema-canary sets it, against a local scripted Messages API stub (no model call). The stub chose each tool call; Claude Code's own schema parse, PreToolUse payload and session journal are recorded as it wrote them. A PreToolUse hook recorded each payload and whether the journal held the call at hook entry.",
"payloadKeys": [
"session_id",
"transcript_path",
"cwd",
"prompt_id",
"permission_mode",
"effort",
"hook_event_name",
"tool_name",
"tool_input",
"tool_use_id"
],
"agentSchemaProperties": [
"description",
"prompt",
"subagent_type",
"model",
"effort",
"isolation"
],
"agentPayloads": [
{
"case": "lone dispatch, no run_in_background",
"tool_input": {
"description": "probe",
"prompt": "Reply with the single word OK.",
"subagent_type": "general-purpose"
}
},
{
"case": "forced run_in_background false",
"tool_input": {
"description": "probe2",
"prompt": "Reply with the single word OK.",
"subagent_type": "general-purpose"
}
}
],
"forcedRunInBackground": {
"payloadInput": {
"description": "probe2",
"prompt": "Reply with the single word OK.",
"subagent_type": "general-purpose"
},
"journalInput": {
"description": "probe2",
"prompt": "Reply with the single word OK.",
"subagent_type": "general-purpose",
"run_in_background": "false"
}
},
"readPayload": {
"tool_input": {
"file_path": "<project>/note.txt",
"offset": 1,
"limit": 5
}
},
"journalAtHookEntry": {
"present": false
}
}
+1 -1
View File
@@ -85,7 +85,7 @@ export function guardFixture(phase: Phase = 'ceo', opts: { methodologyLines?: nu
let parent: string | null = null, clock = Date.parse('2026-10-07T09:04:00Z');
const record = (type: string, message: Record_, extra: Record_ = {}) => {
const uuid = randomUUID(); const r = { uuid, parentUuid: parent, cwd, sessionId, isSidechain: false,
version: opts.version ?? '2.1.292', timestamp: new Date(clock += 100).toISOString(), type, message, ...extra };
version: opts.version ?? '2.1.292', timestamp: new Date(clock += 100).toISOString(), type, message, ...extra }; // pregate-literal: CHECKED_CLAUDE_CODE='2.1.292' the journal's default version, an older checked release the guard must still judge normally
parent = uuid; return r;
};
const assistant = (messageId: string | undefined, content: unknown[], extra: Record_ = {}) =>
+1
View File
@@ -56,6 +56,7 @@ export const FREE_FIXTURES: Readonly<Record<string, readonly string[]>> = {
'test/fixtures/ci-carry-rerun/**': ['test/ci-carry-rerun.test.ts'],
'test/fixtures/ci-gate/**': ['test/gstack-ci-gate.test.ts'],
'test/fixtures/claude-agent-payload-2.1.292.json': ['test/autoplan-publication-payload.test.ts', 'test/autoplan-schema-canary-compare.test.ts'],
'test/fixtures/claude-agent-payload-2.1.326.json': ['test/autoplan-publication-payload.test.ts', 'test/autoplan-schema-canary-compare.test.ts'],
'test/fixtures/claude-native-journal-roots-2.1.284.json': ['test/autoplan-publication-hook.test.ts', 'test/plan-count-transcript.test.ts'],
'test/fixtures/codex-boundary-commands.json': ['test/codex-boundary-evidence.test.ts'],
'test/fixtures/codex-host/**': ['test/codex-host.test.ts'],
+62
View File
@@ -104,3 +104,65 @@ describe.skipIf(process.platform === 'win32')('plan-review prompt file lives in
});
}
});
// Value: protects=the plan-review prompt file #4851 writes under .gstack/tmp/ is git-excluded by the Codex helper its own block runs
// (gstack-codex-probe role-ready), wherever the session runs: the repository root, a subdirectory, and a linked worktree (whose exclude file
// is the main checkout's), with each exclude line written once and an exclude file missing its final newline kept intact; outside git it does
// nothing; fails_when=a leftover prompt shows in git status and can be committed; why_new=#4851 follow-up (GST-4112);
// seam=the generated create command and gstack-codex-probe role-ready; no_claim=a .gitignore negation that overrides info/exclude
describe.skipIf(process.platform === 'win32')('plan-review prompt file is git-excluded (#4851 follow-up)', () => {
const stub = path.join(scratch, 'stub-bin');
fs.mkdirSync(stub, { recursive: true });
fs.writeFileSync(path.join(stub, 'codex'), '#!/bin/sh\nexit 1\n', { mode: 0o755 });
const home = path.join(scratch, 'probe-home');
fs.mkdirSync(home, { recursive: true });
const env = { ...process.env, PATH: stub + path.delimiter + process.env.PATH, _TEL: 'off', HOME: home, GSTACK_HOME: path.join(home, '.gstack'), GSTACK_STATE_ROOT: path.join(home, '.gstack') };
const status = (cwd: string) => git(cwd, 'status', '--porcelain', '--untracked-files=all');
const session = (create: string, cwd: string) => {
const made = spawnSync('bash', ['-c', create], { cwd, env, encoding: 'utf8', timeout: 30_000 });
expect(made.status, made.stderr).toBe(0);
const prompt = made.stdout.trim();
expect(path.dirname(prompt)).toBe(path.join(cwd, '.gstack', 'tmp'));
fs.writeFileSync(prompt, 'review this plan');
spawnSync(path.join(ROOT, 'bin', 'gstack-codex-probe'), ['role-ready', 'exec'], { cwd, env, encoding: 'utf8', timeout: 30_000 });
};
for (const skill of ['plan-ceo-review', 'plan-eng-review']) {
test(skill, () => {
const text = fs.readFileSync(path.join(ROOT, skill, 'sections', 'review-sections.md'), 'utf8');
const at = text.indexOf('gstack-plan-prompt');
const create = [...text.matchAll(/`([^`\n]+)`/g)].map(m => m[1]).filter(s => s.includes('gstack-plan-prompt'))[0]!;
expect(text.slice(at, text.indexOf('\n```\n', text.indexOf('```bash', at)))).toContain(' role-ready exec');
const base = path.join(scratch, `excluded-${skill}`);
const main = path.join(base, 'main');
fs.mkdirSync(path.join(main, 'sub', 'dir'), { recursive: true });
git(main, 'init', '-q');
git(main, '-c', 'user.name=t', '-c', 'user.email=t@example.invalid', 'commit', '-q', '--allow-empty', '-m', 'base');
const excludeFile = path.join(main, '.git', 'info', 'exclude');
fs.writeFileSync(excludeFile, '*.log');
const lines = () => fs.readFileSync(excludeFile, 'utf8').split('\n');
session(create, main); session(create, main);
expect(status(main)).toBe('');
expect(lines().filter(l => l === '/.gstack/tmp/')).toHaveLength(1);
expect(lines()).toContain('*.log');
session(create, path.join(main, 'sub', 'dir'));
expect(status(main)).toBe('');
expect(lines().filter(l => l === '/sub/dir/.gstack/tmp/')).toHaveLength(1);
fs.mkdirSync(path.join(main, 'pkg[1]', 'a*b'), { recursive: true });
session(create, path.join(main, 'pkg[1]', 'a*b'));
expect(status(main)).toBe('');
expect(lines()).toContain('/pkg\\[1\\]/a\\*b/.gstack/tmp/');
git(main, 'worktree', 'add', '-q', path.join(base, 'wt'));
session(create, path.join(base, 'wt')); session(create, path.join(base, 'wt'));
expect(status(path.join(base, 'wt'))).toBe('');
expect(lines().filter(l => l === '/.gstack/tmp/')).toHaveLength(1);
const plain = path.join(base, 'not-a-repo');
fs.mkdirSync(plain);
session(create, plain);
expect(fs.existsSync(path.join(plain, '.git'))).toBe(false);
});
}
});
+45
View File
@@ -140,6 +140,30 @@ describe('review-sweep inventory diff', () => {
expect(later.ignored ?? []).toEqual([]);
});
// Value: protects=a byte-identical copy of the runtime running the sweep (process.execPath; gstack-evals#463 copies its own bun to /tmp/hm-hold-*/.bun/bin/bun)
// is printed as FETCH_IGNORED host-runtime, not a download; fails_when=a test that copies the host's bun stops /ship with FETCH_VIOLATION and FETCH_RERUN_BLOCKED,
// or the exemption lets through a binary named bun whose bytes differ (one flipped byte, one appended byte) or a copy swapped for other bytes later;
// why_new=GST-3959; seam=inventory; no_claim=a copy of any other runtime, an older bun or a runtime whose own path was rewritten during the stage
test.skipIf(fs.statSync(process.execPath).size < BIG_BYTES)('a byte-identical copy of the host runtime is ignored; a modified binary named bun is still a download', async () => {
const root = tmp();
const checkout = path.join(root, 'checkout');
repoAt(checkout);
const start = inventory([root], checkout, []);
await Bun.sleep(30);
const bun = (hold: string) => { const p = path.join(root, hold, '.bun', 'bin', 'bun'); fs.mkdirSync(path.dirname(p), { recursive: true }); fs.copyFileSync(process.execPath, p); return p; };
const copy = bun('hm-hold-a'), flipped = bun('hm-hold-b'), grown = bun('hm-hold-c');
const fd = fs.openSync(flipped, 'r+');
try { const b = Buffer.alloc(1); fs.readSync(fd, b, 0, 1, BIG_BYTES - 1); b[0] = b[0]! ^ 0xff; fs.writeSync(fd, b, 0, 1, BIG_BYTES - 1); } finally { fs.closeSync(fd); }
fs.appendFileSync(grown, Buffer.from([0]));
const r = sweepResult(start, inventory([root], checkout, []));
expect(r.found.map(f => [f.path, f.kind]).sort()).toEqual([[flipped, 'download'], [grown, 'download']].sort());
expect(r.ignored).toEqual([{ path: copy, reason: 'host-runtime' }]);
expect(ignoredLines('specialists', 1, r.ignored!)[0]).toContain('reason=host-runtime');
const mid = inventory([root], checkout, []);
fs.rmSync(copy); fs.writeFileSync(copy, ''); fs.truncateSync(copy, BIG_BYTES);
expect(sweepResult(mid, inventory([root], checkout, [])).found.map(f => f.path)).toEqual([copy]);
});
// Value: protects=a build output already on disk when a stage starts is never counted, as on main where it sat in start.big;
// fails_when=an uncommitted .gitignore edit or a git timeout at the end walk moves it from ignored to big and the stage is voided as FETCH_VIOLATION;
// why_new=ship-4672 p1/red-team#1; seam=sweepDiff; no_claim=files the stage itself wrote
@@ -340,4 +364,25 @@ describe('review-sweep and Capy platform state (GST-3359)', () => {
]);
expect(out).toContain('FETCH_SWEEP: violation stage=specialists attempt=1 found=3');
});
// Value: protects=through the registered sweep command, a stage during which a test copies the runtime the command runs on into the temp dir sweeps clean
// with a FETCH_IGNORED host-runtime line, while the same copy with one appended byte is still a violation; fails_when=gstack-evals#463's hold test
// (GST-3959) stops /ship again, or the exemption reaches a binary that is not byte-identical; seam=gstack-review-dispatch sweep --phase start/end;
// no_claim=a copy of a runtime other than the one the sweep command runs on
test.skipIf(fs.statSync(process.execPath).size < BIG_BYTES)('a copy of the runtime the sweep runs on is not a download; the same copy with one more byte is', () => {
const { dir, env } = repo();
made.push(dir);
const real = fs.realpathSync(dir);
const h = home(real);
const runEnv = { ...env, HOME: h, GSTACK_SWEEP_ROOTS: real };
const exe = spawnSync('bash', ['-c', 'exec bun --no-env-file --config=/dev/null -e "process.stdout.write(process.execPath)"'], { cwd: real, env: runEnv, encoding: 'utf8', timeout: 30_000 }).stdout;
expect(fs.statSync(exe).size).toBeGreaterThanOrEqual(BIG_BYTES);
const copy = (hold: string) => { const p = path.join(real, hold, '.bun', 'bin', 'bun'); fs.mkdirSync(path.dirname(p), { recursive: true }); fs.copyFileSync(exe, p); return p; };
const clean = sweepStage(real, runEnv, () => copy('hm-hold-a'));
expect(clean).toContain('FETCH_SWEEP: clean stage=specialists attempt=1 found=0');
expect(clean).toContain(`FETCH_IGNORED: stage=specialists attempt=1 path='${path.join(real, 'hm-hold-a', '.bun', 'bin', 'bun')}' reason=host-runtime`);
const dirty = sweepStage(real, runEnv, () => fs.appendFileSync(copy('hm-hold-b'), Buffer.from([0])));
expect(dirty).toContain(`kind=download path='${path.join(real, 'hm-hold-b', '.bun', 'bin', 'bun')}'`);
expect(dirty).toContain('FETCH_SWEEP: violation stage=specialists attempt=1 found=1');
});
});