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 <noreply@anthropic.com>
This commit is contained in:
A 2026-02-22 09:29:22 -08:00 committed by GitHub
parent c1b42d3f97
commit 945b60317c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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();
});