From 1e66c112e0d380be95e1389bdf8be994086638f3 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Wed, 23 Sep 2026 12:49:13 -0500 Subject: [PATCH 01/13] fix(safe-bash): avoid repeated impossible sed snapshot scans packages/safe-bash: Reject subjects missing an unconditional literal run before restarting the NFA at every offset. Preserve match preference, captures, work limits and cooperative cancellation. Add regressions for a 20001-row browser snapshot, linear missing-literal work, matching semantics, explicit budgets and cancellation. Keep existing NFA limit tests on inputs that enter the matcher. Validation: reproduce-first failures; 941 text-program tests, 129 Playwright tests, workspace build, source/test and 26 consumer type groups pass. Guarded root lint exits 0 with two existing ls-inode warnings. Installed private candidate passes all four 1100/20001-row match and no-match controls. Tracks hey-boss poe-code #684. --- .../commands/text-programs/nfa-work.test.ts | 62 ++++++++++++++++++- .../tests/commands/text-programs/sed.cases.ts | 2 +- 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/packages/safe-bash/tests/commands/text-programs/nfa-work.test.ts b/packages/safe-bash/tests/commands/text-programs/nfa-work.test.ts index 505baf7ef4..bd0ff0630f 100644 --- a/packages/safe-bash/tests/commands/text-programs/nfa-work.test.ts +++ b/packages/safe-bash/tests/commands/text-programs/nfa-work.test.ts @@ -59,6 +59,47 @@ for (const source of ["(a*)b", String.raw`(a*)\1b`]) { }); } +test("sed scans large browser snapshots for links without exhausting its default work budget", async () => { + const lines = Array.from({ length: 20001 }, (_, index) => `- button "Item${index}" [ref=e${index}]`); + lines.push("- [Snapshot](.playwright-cli/page.yml)"); + const result = await runVirtual("sed", { + args: ["-n", String.raw`s/.*\[Snapshot\](\([^)]*\)).*/\1/p`], + stdin: lines.join("\n") + "\n", + }); + assert.equal(result.exitCode, 0, result.stderr.toString()); + assert.equal(result.stderr.length, 0); + assert.equal(result.stdout.toString(), ".playwright-cli/page.yml\n"); +}); + +test("missing mandatory literal scans grow linearly with subject length", async () => { + const pattern = new Pattern(String.raw`.*\[Snapshot\]\(([^)]*)\).*`); + const counts: number[] = []; + for (const length of [64, 128, 256]) { + let steps = 0; + assert.equal(await pattern.find("x".repeat(length), { + maxBufferBytes: 32768, + step(count = 1) { steps += count; }, + async checkpoint() {}, + }), undefined); + counts.push(steps); + } + assert.ok(counts[1]! <= counts[0]! * 3, `64/128 character work: ${counts}`); + assert.ok(counts[2]! <= counts[1]! * 3, `128/256 character work: ${counts}`); +}); + +test("literal scan optimization preserves alternatives, optional branches, offsets and case folding", async () => { + for (const [source, input, from, ignoreCase, expected] of [ + [".*foo(bar)", "xxfoobar", 0, false, { start: 0, end: 8, groups: ["xxfoobar", "bar"] }], + [".*foo|bar", "bar", 0, false, { start: 0, end: 3, groups: ["bar"] }], + ["(foo)?bar", "bar", 0, false, { start: 0, end: 3, groups: ["bar", undefined] }], + [".*foo", "foo xx", 3, false, undefined], + [".*foo", "xxFOO", 0, true, { start: 0, end: 5, groups: ["xxFOO"] }], + [".*foo\\.(bar)", "xxfoo.bar", 0, false, { start: 0, end: 9, groups: ["xxfoo.bar", "bar"] }], + ] as const) { + assert.deepEqual(await new Pattern(source, true, ignoreCase).find(input, makeBudget(100000), from), expected); + } +}); + test("NFA yields inside one find before its small work limit and preserves queued cancellation", async context => { let now = 0; context.mock.method(performance, "now", () => now); @@ -69,12 +110,13 @@ test("NFA yields inside one find before its small work limit and preserves queue context.mock.method(budget, "step", (count = 1) => { now += count; step(count); }); const abort = setImmediate(() => controller.abort(reason)); try { - await assert.rejects(async () => await new Pattern("(a*)(a*)b").find("aaaaaaaa", budget), error => error === reason); + // Include the required literal so the search must enter the NFA. + await assert.rejects(async () => await new Pattern("(a*)(a*)b").find("aaaaaaaab", budget), error => error === reason); } finally { clearImmediate(abort); } }); test("NFA combines visited and queued storage rather than admitting both independently", async () => { - await assert.rejects(async () => await new Pattern("(a*)(a*)b").find("aaaa", makeBudget(2048, 1450)), + await assert.rejects(async () => await new Pattern("(a*)(a*)b").find("aaaab", makeBudget(2048, 1450)), error => error instanceof ProgramError && error.message === "regular expression state buffer limit exceeded"); }); @@ -93,6 +135,22 @@ test("literal synchronous match awaits its started checkpoint before buffer refu assert.equal(calls, 2); }); +test("mandatory literal scans retain explicit work limits and queued cancellation", async context => { + const pattern = new Pattern(".*needle"); + await assert.rejects(pattern.find("x".repeat(128), makeBudget(64)), { message: "execution step limit exceeded" }); + let now = 0; + context.mock.method(performance, "now", () => now); + const controller = new AbortController(); + const budget = makeBudget(512, 8192, controller.signal); + const step = budget.step.bind(budget); + context.mock.method(budget, "step", (count = 1) => { now += count; step(count); }); + const reason = Object.freeze({ cancelled: "literal scan" }); + const abort = setImmediate(() => controller.abort(reason)); + try { + await assert.rejects(pattern.find("x".repeat(128), budget), error => error === reason); + } finally { clearImmediate(abort); } +}); + test("NFA refuses a capture state before serializing its key", async () => { const pattern = new Pattern("(a)"); const join = Array.prototype.join; diff --git a/packages/safe-bash/tests/commands/text-programs/sed.cases.ts b/packages/safe-bash/tests/commands/text-programs/sed.cases.ts index 3dd0182dfe..2d0f3283a5 100644 --- a/packages/safe-bash/tests/commands/text-programs/sed.cases.ts +++ b/packages/safe-bash/tests/commands/text-programs/sed.cases.ts @@ -218,7 +218,7 @@ test("sed branch and regex work are budgeted and failed in-place execution prese assert.equal(loop.exitCode, 2); assert.match(loop.stderr.toString(), /step limit/u); assert.deepEqual(loop.files, { input: Buffer.from("a\n") }); - const regex = await runVirtual("sed", { args: ["-E", "s/(a+)+b/X/"], stdin: "a".repeat(1000) }, { maxSteps: 2000 }); + const regex = await runVirtual("sed", { args: ["-E", "s/(a+)+b/X/"], stdin: "a".repeat(1000) + "b" }, { maxSteps: 2000 }); assert.equal(regex.exitCode, 2); assert.match(regex.stderr.toString(), /step limit/u); }); From 7df98c5abf27dac3b0e9509cc86cb805b8e05c13 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Wed, 23 Sep 2026 13:04:21 -0500 Subject: [PATCH 02/13] fix(safe-bash): bound literal-alternative grep scans packages/safe-bash: Route pure ASCII ERE literal alternatives through the existing bounded KMP matcher. Preserve per-pattern priority, leftmost-longest spans, UTF-8 validation, case/whole/word semantics, cancellation and resource limits. Add reproduce-first default-budget snapshot regressions, semantic controls, explicit budget checks and cancellation/worker-reuse coverage. Validation: 695 regex/search tests pass with one existing unavailable GNU-oracle skip; workspace build, source/test and 26 consumer type groups pass; guarded root lint exits 0 with two existing ls-inode warnings. Original 4/16 KiB differential reproductions match native grep; oversized input remains bounded. Tracks hey-boss poe-code #686. --- .../regex-execution/bounded-provider.test.ts | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/packages/safe-bash/tests/commands/regex-execution/bounded-provider.test.ts b/packages/safe-bash/tests/commands/regex-execution/bounded-provider.test.ts index 94d3c65d52..cdcce1a154 100644 --- a/packages/safe-bash/tests/commands/regex-execution/bounded-provider.test.ts +++ b/packages/safe-bash/tests/commands/regex-execution/bounded-provider.test.ts @@ -68,6 +68,63 @@ test("production provider supports bounded ASCII ERE selection", async () => { assert.deepEqual(spans(await run(request(grep(["[[:digit:]]+"]), ["x123y"]))), [[1, 4]]); }); +test("literal alternatives scan long snapshot rows within the default allocation budget", async () => { + const pattern = "blocked|security|network error|access denied|whoa there|request has been blocked|challenge|captcha|forbidden"; + for (const length of [4096, 16384]) { + const input = "- generic: " + "x".repeat(length); + assert.deepEqual(spans(await run(request(grep([pattern], { insensitive: true }), [input]))), [[]]); + assert.deepEqual(spans(await run(request(grep([pattern], { insensitive: true }), [input + " ACCESS DENIED"]))), [[input.length + 1, input.length + 14]]); + } +}); + +test("literal alternatives preserve longest matches, pattern priority and word boundaries", async () => { + for (const [patterns, input, overrides, expected] of [ + [["a|ab"], "zab", {}, [1, 3]], + [["b|bb", "a"], "abb", {}, [1, 3]], + [["none|absent", "a|ab"], "ab", {}, [0, 2]], + [["a|ab"], "AB", { whole: true, insensitive: true }, [0, 2]], + [["a|ab"], "abc", { whole: true }, []], + [["a|ab"], "xab ab!", { word: true }, [4, 6]], + [["a|ab"], "éAB", { insensitive: true }, [2, 4]], + [["a|ab"], "a|ab", { fixed: true }, [0, 4]], + [["a|ab"], "a|ab", { extended: false }, [0, 4]], + [["a||ab"], "zab", {}, [0, 0]], + [["a|a.b"], "aXb", {}, [0, 3]], + [[String.raw`a\|ab`], "a|ab", {}, [0, 4]], + ] as const) assert.deepEqual(spans(await run(request(grep([...patterns], overrides), [input]))), [expected]); + assert.deepEqual(spans(await run({ id: 1, descriptor: grep(["a|ab", "b|bc"]), rows: [row("zababc", true)] })), [[1, 3, 3, 5]]); + const invalid = await run({ id: 1, descriptor: grep(["a|b"]), rows: [{ ...row(""), bytes: Uint8Array.of(0xff) }] }); + assert.ok("error" in invalid); + assert.match(invalid.error, /UTF-8/); +}); + +test("literal alternatives retain explicit work, allocation, state and match limits", async () => { + for (const options of [{ maxWork: 128 }, { maxAllocationUnits: 128 }, { maxStates: 2 }]) { + const reply = await run(request(grep(["needle|other"], { insensitive: true }), ["x".repeat(256)]), options); + assert.ok("error" in reply); + assert.match(reply.error, /work|allocation|states/); + } + const reply = await run({ id: 1, descriptor: grep(["a|bb"]), rows: [row("abb", true)] }, { maxMatchesPerLine: 1 }); + assert.ok("error" in reply); + assert.match(reply.error, /matches per line/); +}); + +test("literal alternative scans preserve cancellation identity and worker reuse", async () => { + const executor = new RegexExecutor(createBoundedRegexProvider({ maxWorkers: 1 })); + const controller = new AbortController(); + const session = executor.open(controller.signal); + const descriptor = grep(["a".repeat(2048) + "z|" + "a".repeat(2048) + "y"], { insensitive: true }); + const pending = session.run(descriptor, [row("a".repeat(16384))]); + const rejected = assert.rejects(pending, reason => reason === false); + await new Promise(resolve => setTimeout(resolve, 0)); + controller.abort(false); + await rejected; + await session.close(); + const recovered = executor.open(new AbortController().signal); + try { assert.deepEqual(await recovered.run(grep(["a|ab"]), [row("ab")]), [[{ start: 0, end: 2 }]]); } + finally { await recovered.close(); await executor.dispose(); } +}); + test("fixed literals, BRE subset, pattern lists, whole and empty patterns retain exact spans", async () => { assert.deepEqual(spans(await run(request(grep(["a+b"], { fixed: true }), ["a+b"]))), [[0, 3]]); assert.deepEqual(spans(await run(request(grep(["ab*"], { extended: false }), ["zabb"]))), [[1, 4]]); From edf1b7efd5570ed547b3fad1181910d3df15c432 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Thu, 24 Sep 2026 00:17:30 -0500 Subject: [PATCH 03/13] test(safe-bash): exercise nl matcher budgets after literal fast path packages/safe-bash: keep the step-limit and in-match cancellation cases on a nonliteral NFA pattern. The literal no-match optimization legitimately finishes the old inputs before those boundaries. Preserve all assertions, limits and cancellation reasons. Validation: reproduced 3 failures in 9 tests; all 9 pass with character-class patterns. --- packages/safe-bash/tests/commands/stream-format/nl.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/safe-bash/tests/commands/stream-format/nl.test.ts b/packages/safe-bash/tests/commands/stream-format/nl.test.ts index 6891f8fea8..aba7c3ecd9 100644 --- a/packages/safe-bash/tests/commands/stream-format/nl.test.ts +++ b/packages/safe-bash/tests/commands/stream-format/nl.test.ts @@ -28,7 +28,7 @@ export const nlCases: readonly NativeCase[] = [ test("nl bounded matcher consumes the invocation's shared step budget", async () => { const instance = shell({ limits: { maxSteps: 1000 } }); - const result = await instance.exec("nl -bp'a*a*a*a*b'", { stdin: "a".repeat(200) + "\n" }); + const result = await instance.exec("nl -bp'a*a*a*a*[bc]'", { stdin: "a".repeat(200) + "\n" }); assert.equal(result.exitCode, 1); assert.match(result.stderr, /step limit/); await instance.dispose(); @@ -110,7 +110,7 @@ for (const reason of [false, Object.freeze({ cancelled: "nl match" })]) test(`nl return find.apply(this, args); }); try { - await assert.rejects(instance.exec("nl -bp'a*a*a*b'", { + await assert.rejects(instance.exec("nl -bp'a*a*a*[bc]'", { stdin: "aaaaaaaa\n", signal: controller.signal, stdout: { async write(bytes) { written += bytes.length; } }, }), error => error === reason); From 2436b5897973d7716fed3adc13bda9fb58d7c42f Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Thu, 24 Sep 2026 07:40:16 -0500 Subject: [PATCH 04/13] test(safe-bash): exercise recursive copies through retained readers packages/safe-bash: give the synthetic traversal host stable identities and explicit retained readers. Observe completed streaming writes so depth, partial-progress and output-backpressure assertions cover the current path. Verification: all 38 recursive admission tests pass, including falsey cancellation and depth boundaries. Maintained typecheck and guarded lint pass. --- .../tests/commands/recursive-filesystem-admission.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/safe-bash/tests/commands/recursive-filesystem-admission.test.ts b/packages/safe-bash/tests/commands/recursive-filesystem-admission.test.ts index 865e0daf3b..dfa373443b 100644 --- a/packages/safe-bash/tests/commands/recursive-filesystem-admission.test.ts +++ b/packages/safe-bash/tests/commands/recursive-filesystem-admission.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { CommandRegistry, FsError, toByteSource, type ByteSink, type CommandContext, type FileStat, type FileSystem } from "../../src/contracts/index.js"; +import { CommandRegistry, FsError, collectBytes, toByteSource, type ByteSink, type CommandContext, type FileStat, type FileSystem } from "../../src/contracts/index.js"; import { filesystemCommands } from "../../src/commands/filesystem.js"; import { createMemoryFileSystem } from "../../src/fs/memory/index.js"; import { Shell } from "../../src/shell/index.js"; From ae68ef16f7879e5955f5a3f09435184f065ca98a Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Thu, 24 Sep 2026 07:40:16 -0500 Subject: [PATCH 05/13] test(safe-bash): preserve device fixture capability boundaries packages/safe-bash: carry the permission-denial proxy into confined views and explicitly disable retained reads for buffered-only profiles. Verify diff's bounded retained reads and reader closure independently of pathname fallback. Verification: all 48 device-view tests pass. Maintained source/test and consumer typecheck passes; guarded lint completes with zero errors. --- .../tests/shell/virtual-null-device.test.ts | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/packages/safe-bash/tests/shell/virtual-null-device.test.ts b/packages/safe-bash/tests/shell/virtual-null-device.test.ts index b8426c1d12..3bbb8de032 100644 --- a/packages/safe-bash/tests/shell/virtual-null-device.test.ts +++ b/packages/safe-bash/tests/shell/virtual-null-device.test.ts @@ -486,6 +486,41 @@ for (const retained of [false, true]) test(`diff uses retained identity rather t for (const path of ["/input", "/other"]) assert.equal(new TextDecoder().decode(await backing.readFile(path)), "a\nb\n"); }); +test("diff retains bounded readers through the device view without pathname read fallbacks", async context => { + const backing = new MemoryFileSystem(); + await backing.writeFile("/input", new TextEncoder().encode("a\nb\n")); + let opened = 0, closed = 0, reads = 0; + const fs = new Proxy(backing, { + get(target, property) { + if (property === "capabilities") return { ...target.capabilities, streamingRead: false }; + if (property === "readStream" || property === "readFile") return () => { assert.fail("diff must use retained reads"); }; + if (property === "openReadFile") return async (path: string, options?: FsOptions) => { + const handle = await target.openReadFile(path, options); + opened++; + return { + stat: handle.stat.bind(handle), + async read(position: number, maxBytes: number, options?: FsOptions) { + assert.ok(Number.isSafeInteger(maxBytes) && maxBytes > 0 && maxBytes <= 16); + reads++; + return handle.read(position, maxBytes, options); + }, + async close() { closed++; await handle.close(); }, + }; + }; + const member = Reflect.get(target, property); + return typeof member === "function" ? member.bind(target) : member; + }, + }); + const shell = new Shell({ fs }).use(agentCommands({ diffPatch: { maxInputBytes: 16 } })); + context.after(() => shell.dispose()); + const result = await shell.exec("diff /input /input"); + assert.equal(result.exitCode, 0, result.stderr); + assert.equal(result.stdout, ""); + assert.equal(opened, 2); + assert.equal(reads, 2); + assert.equal(closed, opened); +}); + test("reserved null replacement and descendants cannot bypass the Shell device view", async context => { const { shell, fs } = fixture(context); await fs.mkdir("/dev"); From 2c3c1b6805f2f6be0f205789ee15d013dc999f3f Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Thu, 24 Sep 2026 21:51:39 -0500 Subject: [PATCH 06/13] test(safe-bash): align fixtures with current capability contracts packages/safe-bash: Update retained-copy/staged-move authority assertions and current regex cancellation checkpoints after upstream integration. Preserve exact refusal effects and supported transfer namespaces. packages/safe-playwright-cloudflare: Exercise the current process-inventory cleanup retry seam. packages/safe-playwright: Remove duplicate unlimited-default cases now covered upstream. Verification: affected browser/regex, copy/authority and core-ordering regressions pass. --- .../regex-execution/bounded-provider.test.ts | 8 ++++---- .../tests/commands/text-programs/nfa-work.test.ts | 8 ++++---- .../browser-process-lifetime-guardian.test.ts | 14 ++++++++------ 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/packages/safe-bash/tests/commands/regex-execution/bounded-provider.test.ts b/packages/safe-bash/tests/commands/regex-execution/bounded-provider.test.ts index cdcce1a154..b8231a9253 100644 --- a/packages/safe-bash/tests/commands/regex-execution/bounded-provider.test.ts +++ b/packages/safe-bash/tests/commands/regex-execution/bounded-provider.test.ts @@ -100,8 +100,8 @@ test("literal alternatives preserve longest matches, pattern priority and word b test("literal alternatives retain explicit work, allocation, state and match limits", async () => { for (const options of [{ maxWork: 128 }, { maxAllocationUnits: 128 }, { maxStates: 2 }]) { - const reply = await run(request(grep(["needle|other"], { insensitive: true }), ["x".repeat(256)]), options); - assert.ok("error" in reply); + const reply = await run(request(grep(["needle|other"], { insensitive: true }), ["needle" + "x".repeat(256)]), options); + assert.ok("error" in reply, JSON.stringify({ options, reply })); assert.match(reply.error, /work|allocation|states/); } const reply = await run({ id: 1, descriptor: grep(["a|bb"]), rows: [row("abb", true)] }, { maxMatchesPerLine: 1 }); @@ -362,8 +362,8 @@ test("UTF-8 literal retirement stops pending preprocessing and releases capacity const worker = provider.createWorker(defaults); let replies = 0; worker.on("message", value => { if (value && typeof value === "object" && "id" in value) replies++; }); - worker.postMessage(request(literal("rg", ["é".repeat(3000)]), ["é".repeat(4000)])); - await new Promise(resolve => setTimeout(resolve, 0)); + // Exceed the synchronous work quantum so retirement interrupts admitted work. + worker.postMessage(request(literal("rg", ["é".repeat(30000)]), ["é".repeat(40000)])); const retirement = worker.terminate(); assert.equal(worker.terminate(), retirement); assert.throws(() => provider.createWorker(defaults), /worker.*limit/); diff --git a/packages/safe-bash/tests/commands/text-programs/nfa-work.test.ts b/packages/safe-bash/tests/commands/text-programs/nfa-work.test.ts index bd0ff0630f..4ecaa74ec7 100644 --- a/packages/safe-bash/tests/commands/text-programs/nfa-work.test.ts +++ b/packages/safe-bash/tests/commands/text-programs/nfa-work.test.ts @@ -105,13 +105,13 @@ test("NFA yields inside one find before its small work limit and preserves queue context.mock.method(performance, "now", () => now); const controller = new AbortController(); const reason = Object.freeze({ cancelled: "inside find" }); - const budget = makeBudget(512, 32768, controller.signal); + const budget = makeBudget(8192, 32768, controller.signal); const step = budget.step.bind(budget); context.mock.method(budget, "step", (count = 1) => { now += count; step(count); }); const abort = setImmediate(() => controller.abort(reason)); try { // Include the required literal so the search must enter the NFA. - await assert.rejects(async () => await new Pattern("(a*)(a*)b").find("aaaaaaaab", budget), error => error === reason); + await assert.rejects(async () => await new Pattern("(a*)(a*)b").find("a".repeat(32) + "b", budget), error => error === reason); } finally { clearImmediate(abort); } }); @@ -141,13 +141,13 @@ test("mandatory literal scans retain explicit work limits and queued cancellatio let now = 0; context.mock.method(performance, "now", () => now); const controller = new AbortController(); - const budget = makeBudget(512, 8192, controller.signal); + const budget = makeBudget(32768, 8192, controller.signal); const step = budget.step.bind(budget); context.mock.method(budget, "step", (count = 1) => { now += count; step(count); }); const reason = Object.freeze({ cancelled: "literal scan" }); const abort = setImmediate(() => controller.abort(reason)); try { - await assert.rejects(pattern.find("x".repeat(128), budget), error => error === reason); + await assert.rejects(pattern.find("x".repeat(4096), budget), error => error === reason); } finally { clearImmediate(abort); } }); diff --git a/packages/safe-playwright-cloudflare/tests/browser-process-lifetime-guardian.test.ts b/packages/safe-playwright-cloudflare/tests/browser-process-lifetime-guardian.test.ts index 787aef7741..8220fb35a7 100644 --- a/packages/safe-playwright-cloudflare/tests/browser-process-lifetime-guardian.test.ts +++ b/packages/safe-playwright-cloudflare/tests/browser-process-lifetime-guardian.test.ts @@ -7,13 +7,14 @@ vi.mock('node:timers/promises', () => ({ setTimeout: mocks.delay })); afterEach(() => { vi.restoreAllMocks(); vi.resetModules(); mocks.inspect.mockReset(); mocks.remove.mockReset(); mocks.delay.mockClear(); }); -for (const failingCommand of ['ps', 'lsof']) for (const failures of [1, 50]) test(`guardian handles ${failures} ${failingCommand} inspection timeouts`, async () => { +for (const failingCommand of ['ps', 'lsof']) for (const { failures, recover } of [{ failures: 1, recover: false }, { failures: 50, recover: false }, { failures: 50, recover: true }]) test(`guardian handles ${failures} ${failingCommand} inspection timeouts, eventual recovery=${recover}`, async () => { const handlers = new Map unknown>(); vi.spyOn(process, 'on').mockImplementation((event, listener) => { handlers.set(event, listener); return process; }); vi.spyOn(process, 'kill').mockReturnValue(true); const exit = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never); - vi.spyOn(console, 'error').mockImplementation((_message, error) => { throw error; }); + vi.spyOn(console, 'error').mockImplementation((_message, error) => { if (!recover) throw error; }); let remaining = failures; + mocks.remove.mockImplementation(() => { expect(remaining).toBeLessThanOrEqual(0); }); const failure = Object.assign(new Error('process inspection timed out'), { code: 'ETIMEDOUT' }); mocks.inspect.mockImplementation((command: string) => { if (command === failingCommand && remaining-- > 0) throw failure; @@ -22,10 +23,11 @@ for (const failingCommand of ['ps', 'lsof']) for (const failures of [1, 50]) tes await import('./browser-process-lifetime.guardian.mjs'); handlers.get('message')!({ operation: 'own', pid: 12344, directory: '/synthetic-owned-browser' }); const completion = Promise.resolve(handlers.get('disconnect')!()).then(() => undefined, error => error); - expect(await completion).toBe(failures === 1 ? undefined : failure); - expect(mocks.inspect.mock.calls.filter(([command]) => command === failingCommand)).toHaveLength(failures === 1 ? 2 : 50); - expect(mocks.delay).toHaveBeenCalledTimes(failures === 1 ? 1 : 49); - if (failures === 1) { + const succeeds = failures === 1 || recover; + expect(await completion).toBe(succeeds ? undefined : failure); + expect(mocks.inspect.mock.calls.filter(([command]) => command === failingCommand)).toHaveLength(succeeds ? failures + 1 : 50); + expect(mocks.delay).toHaveBeenCalledTimes(succeeds ? failures : 49); + if (succeeds) { expect(mocks.remove).toHaveBeenCalledWith('/synthetic-owned-browser', { recursive: true, force: true }); expect(exit).toHaveBeenCalledWith(0); } else { From d62ecccef5266734207f512d18609c61ac6866c2 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Fri, 25 Sep 2026 00:55:20 -0500 Subject: [PATCH 07/13] fix(ci): report stalled safe-bash test files .github/workflows: Apply a ten-minute per-file Node test deadline to the complete serial Safe Bash suite. This exceeds the existing 400-second test allowance and reports hanging children instead of leaving the suite pending indefinitely. Verification: npm run lint:workflows passed. Read-only colleague review confirmed Node22 file-level timeout and ordinary runner argument forwarding. --- .github/workflows/pr-checks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index b63e0acd01..02129afc62 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -60,7 +60,7 @@ jobs: run: npm run build - uses: ./.github/actions/setup-bash-oracle - name: Run the complete @poe-platform/safe-bash unit suite serially - run: npm run test:unit --workspace @poe-platform/safe-bash -- --test-concurrency=1 + run: npm run test:unit --workspace @poe-platform/safe-bash -- --test-concurrency=1 --test-timeout=600000 bun-public-imports: name: Packed public APIs (Bun 1.3.11 and Node22) runs-on: ubuntu-latest From abc98ff0d780c2385fff8f6401fd795397bcd4cc Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Fri, 25 Sep 2026 01:33:41 -0500 Subject: [PATCH 08/13] test(safe-bash): reconcile upstream count coverage packages/safe-bash: Adopt the upstream bare-multiplier case and assert exact leading or trailing bytes for numeric multipliers. This resolves the overlapping test additions while preserving stronger output checks. Validation: all43 count tests pass; complete guarded lint passed17,946 inputs with zero errors; three-way file merge succeeds. --- .../safe-bash/tests/commands/coreutils-copy-counts.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/safe-bash/tests/commands/coreutils-copy-counts.test.ts b/packages/safe-bash/tests/commands/coreutils-copy-counts.test.ts index 198f59fd95..0be52a817c 100644 --- a/packages/safe-bash/tests/commands/coreutils-copy-counts.test.ts +++ b/packages/safe-bash/tests/commands/coreutils-copy-counts.test.ts @@ -52,10 +52,10 @@ for (const [command, args, expected] of [ for (const command of ["head", "tail"]) for (const [suffix, count] of [["b", 512], ["kB", 1000], ["K", 1024], ["M", 1048576], ["G", 1073741824]] as const) { test(`${command} accepts byte multiplier ${suffix}`, async () => { - const stdin = "x".repeat(1100); + const stdin = "a".repeat(1024) + "b".repeat(1024); const result = await run(command, ["-c", `1${suffix}`], { stdin }); assert.equal(result.exitCode, 0, result.stderr); - assert.equal(result.stdout.length, Math.min(count, stdin.length)); + assert.equal(result.stdout, command === "head" ? stdin.slice(0, count) : stdin.slice(-count)); }); } From 7f62124bba47639c455641c98a583d3e6a9552e4 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Fri, 25 Sep 2026 02:15:40 -0500 Subject: [PATCH 09/13] fix(ci): serialize workspace test stages .github/workflows: avoid overlapping independent two-worker suites and native tasks on the same runner. Preserve all tests, hooks, assertions and deadlines. All 623 tests across six SafeJS CI failure files pass with one local worker and with the CI two-worker setting in isolation. Colleague review and workflow lint pass. Full GitHub CI remains required. Tracks hey-boss #1137. --- .github/workflows/pr-checks.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 02129afc62..c59796030d 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -41,6 +41,7 @@ jobs: sudo apt-get update sudo apt-get install --yes zsh test -x /bin/zsh + # Each stage owns its worker pool; avoid overlapping CPU-heavy replay suites. - run: npm test -- --concurrency=1 --exclude-workspace=@poe-platform/safe-bash - run: npm run smoke safe-bash-node22: From 39b391dd07f4a02062ac72a5f78d1ec8b1c72e88 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Fri, 25 Sep 2026 02:32:25 -0500 Subject: [PATCH 10/13] fix(safe-bash): flush grep batches before resuming input packages/safe-bash: Restore output backpressure after the upstream batch optimization for both synchronous and worker regex providers, preserving max-count exits and per-line synchronous processing. The existing worker regression and new synchronous exact-output regression both failed before the fix. All252 focused grep/count/move/copy/browser tests,440 filesystem tests, the134-workspace root build,36-package focused rebuild, and complete guarded lint passed. Tracks hey-boss #1139. --- .../commands/regex-execution/commands.test.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/packages/safe-bash/tests/commands/regex-execution/commands.test.ts b/packages/safe-bash/tests/commands/regex-execution/commands.test.ts index 6fd332ff13..2524465063 100644 --- a/packages/safe-bash/tests/commands/regex-execution/commands.test.ts +++ b/packages/safe-bash/tests/commands/regex-execution/commands.test.ts @@ -51,6 +51,27 @@ for (const fixture of cases) test(fixture.name, { timeout: 5000 }, async () => { assert.equal(result.stderr.length, 0); }); +test("synchronous grep flushes each batch before reading feedback-dependent input", { timeout: 5000 }, async () => { + const definition = createStandardCommands().find(entry => entry.name === "grep")!; + const chunks: Uint8Array[] = []; + let closed = false; + const source = (async function* () { + try { + yield Buffer.from("a\na\na\n"); + assert.equal(Buffer.concat(chunks).toString(), "a\na\na\n"); + yield Buffer.from("a\n"); + assert.equal(Buffer.concat(chunks).toString(), "a\na\na\na\n"); + } finally { closed = true; } + })(); + const result = await run(definition, ["a", "-"], source, { + stdout: { async write(bytes) { await delay(1); chunks.push(bytes.slice()); } }, + }); + assert.equal(result.code, 0, result.stderr.toString()); + assert.equal(result.stderr.length, 0); + assert.equal(Buffer.concat(chunks).toString(), "a\na\na\na\n"); + assert.equal(closed, true); +}); + for (const tool of ["grep", "rg"] as const) { test(`${tool} validation and fragment matching never construct host RegExp`, { timeout: 5000 }, async () => { const definition = command(tool); From cbe3b4545384dce0dc83e0515e397009775f6dca Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Fri, 25 Sep 2026 02:49:17 -0500 Subject: [PATCH 11/13] fix(ci): cap workspace test suites at one Vitest worker .github/workflows: Use the existing worker override after independent Linux validation found replay failures even with workspace stages serialized. Preserve every command, assertion and deadline. Validation: resolved Vitest configuration uses one worker and5000ms; focused replay/budget/presentation tests and workflow lint pass. Full exact-head CI remains required. Tracks hey-boss #1137. --- .github/workflows/pr-checks.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index c59796030d..d20425aef5 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -41,8 +41,12 @@ jobs: sudo apt-get update sudo apt-get install --yes zsh test -x /bin/zsh - # Each stage owns its worker pool; avoid overlapping CPU-heavy replay suites. - - run: npm test -- --concurrency=1 --exclude-workspace=@poe-platform/safe-bash + - name: Run workspace unit stages serially + # Each stage has its own workers; overlapping stages oversubscribe runner CPUs. + run: npm test -- --concurrency=1 --exclude-workspace=@poe-platform/safe-bash + env: + # Native replay tests also need the full CPU budget within each stage. + VITEST_MAX_WORKERS: "1" - run: npm run smoke safe-bash-node22: name: "@poe-platform/safe-bash (Node22)" From 4707122e2d6b2add1869fc90649667e4e9497eac Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Fri, 25 Sep 2026 03:18:19 -0500 Subject: [PATCH 12/13] fix(safe-bash): retain undefined copy rejection through cleanup packages/safe-bash: track failed copying independently from its rejection value and drain retained-reader cleanup before rethrowing the original reason. Six direct regression cases cover Error and undefined rejection values, secondary cleanup failures, successful-copy cleanup failure, and single-close behavior. Two cases failed before the fix; all 88 copy/predicate tests pass. Addresses hey-boss #1240. --- .../commands/copy-source-binding.test.ts | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/packages/safe-bash/tests/commands/copy-source-binding.test.ts b/packages/safe-bash/tests/commands/copy-source-binding.test.ts index bc10ef2d98..0ffcd3ef03 100644 --- a/packages/safe-bash/tests/commands/copy-source-binding.test.ts +++ b/packages/safe-bash/tests/commands/copy-source-binding.test.ts @@ -569,3 +569,37 @@ test("copyCheckedSource preserves primary read failure when close also rejects", assert.match(result.stderr, /EIO.*primary read failure/u); assert.doesNotMatch(result.stderr, /secondary close failure/u); }); + +for (const readFailure of [false, true]) for (const undefinedRead of [false, true]) for (const undefinedClose of [false, true]) { + if (!readFailure && undefinedRead) continue; + test(`copy preserves rejection identity through cleanup: read=${readFailure}, undefinedRead=${undefinedRead}, undefinedClose=${undefinedClose}`, async () => { + const fs = await fixture({ source: "payload" }); + const { context } = await run("true", [], { fs }); + const expected = await fs.stat("/work/source"); + const primary = undefinedRead ? undefined : new Error("read failed"); + const secondary = undefinedClose ? undefined : new Error("close failed"); + let closes = 0; + let cleanup!: () => void | Promise; + const view = new Proxy(fs, { get(target, property) { + if (property === "openReadFile") return async (...args: Parameters) => { + const reader = await fs.openReadFile(...args); + return { ...reader, + async read(...args: Parameters) { + if (readFailure) throw primary; + return reader.read(...args); + }, + async close() { closes++; await reader.close(); throw secondary; }, + }; + }; + const member = Reflect.get(target, property); + return typeof member === "function" ? member.bind(target) : member; + } }); + await copyCheckedSource({ ...context, fs: view, registerCleanup(close) { cleanup = close; } }, + "/work/source", "/work/new", expected, true).then( + () => assert.fail("copy must reject"), + reason => assert.equal(reason, readFailure ? primary : secondary), + ); + if (readFailure) await cleanup(); + assert.equal(closes, 1); + }); +} From c102b8868a35759480ab5943e3dcca8766e7dfe0 Mon Sep 17 00:00:00 2001 From: Kamil Jopek Date: Fri, 25 Sep 2026 09:00:22 -0500 Subject: [PATCH 13/13] test(safe-bash): remove superseded fixture import packages/safe-bash/tests: remove an unused import left after reconciling upstream retained-copy fixtures. Validation: all 498 remaining Safe Bash regression tests and six guardian cases pass; 36 dependency builds complete and workflow lint passes. --- .../tests/commands/recursive-filesystem-admission.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/safe-bash/tests/commands/recursive-filesystem-admission.test.ts b/packages/safe-bash/tests/commands/recursive-filesystem-admission.test.ts index dfa373443b..865e0daf3b 100644 --- a/packages/safe-bash/tests/commands/recursive-filesystem-admission.test.ts +++ b/packages/safe-bash/tests/commands/recursive-filesystem-admission.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { CommandRegistry, FsError, collectBytes, toByteSource, type ByteSink, type CommandContext, type FileStat, type FileSystem } from "../../src/contracts/index.js"; +import { CommandRegistry, FsError, toByteSource, type ByteSink, type CommandContext, type FileStat, type FileSystem } from "../../src/contracts/index.js"; import { filesystemCommands } from "../../src/commands/filesystem.js"; import { createMemoryFileSystem } from "../../src/fs/memory/index.js"; import { Shell } from "../../src/shell/index.js";