From 945b60317cbf40f7709175ed5cd66b119945df2a Mon Sep 17 00:00:00 2001 From: A <258483684+la14-1@users.noreply.github.com> Date: Sun, 22 Feb 2026 09:29:22 -0800 Subject: [PATCH] fix: clean up stray subprocess-test-*.txt files in preload (#1703) Automated refactor/discovery agents occasionally run tests from outside the cli/ directory, where bunfig.toml is not loaded and this preload never activates. When that happens, HOME stays as the real home dir (/root on CI), so any subprocess-test-*.txt written by tests leaks there instead of the sandbox. Added cleanupStrayTestFiles() which runs both on preload init and on process exit. This retroactively removes any leftover files from past runs and prevents accumulation in future ones. Co-authored-by: B <6723574+louisgv@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 --- cli/src/__tests__/preload.ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/cli/src/__tests__/preload.ts b/cli/src/__tests__/preload.ts index 1c100933..b8241f99 100644 --- a/cli/src/__tests__/preload.ts +++ b/cli/src/__tests__/preload.ts @@ -23,10 +23,36 @@ * - Subprocesses (execSync, spawnSync) inherit the sandboxed environment */ -import { mkdirSync, rmSync, mkdtempSync } from "fs"; +import { mkdirSync, readdirSync, rmSync, mkdtempSync } from "fs"; import { join } from "path"; import { tmpdir } from "os"; +// ── Stray test file cleanup ────────────────────────────────────────────────── +// +// Automated refactor/discovery agents occasionally run tests from outside the +// cli/ directory, where bunfig.toml is not loaded and this preload never runs. +// In those cases HOME remains the real home directory (/root on CI), so any +// test that writes "$HOME/subprocess-test-*.txt" leaves files there. +// +// We clean up before and after every test run to keep the working tree tidy. + +const REAL_HOME = process.env.HOME ?? ""; + +function cleanupStrayTestFiles(): void { + if (!REAL_HOME) return; + try { + for (const f of readdirSync(REAL_HOME)) { + if (f.startsWith("subprocess-test-") && f.endsWith(".txt")) { + rmSync(join(REAL_HOME, f), { force: true }); + } + } + } catch { + // Best-effort + } +} + +cleanupStrayTestFiles(); + // ── Create isolated HOME ──────────────────────────────────────────────────── const TEST_HOME = mkdtempSync(join(tmpdir(), "spawn-test-home-")); @@ -52,4 +78,5 @@ process.on("exit", () => { } catch { // Best-effort cleanup } + cleanupStrayTestFiles(); });