Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(test): isolate audit writes to a per-run scratch dir in the shared bootstrap (#2823) (#2966)

Vishnu J42c4ea929fe2
diff --git a/bunfig.toml b/bunfig.toml
index e7a953223d..3dd8ebb9a6 100644
--- a/bunfig.toml
+++ b/bunfig.toml
@@ -13,4 +13,9 @@ timeout = 60_000
# fixtures still match the schema. v0.37's production default is ZE/1280;
# tests that want the new default call configureGateway() explicitly in
# their own beforeAll.
-preload = ["./test/helpers/legacy-embedding-preload.ts"]
+#
+# #2823: redirect GBRAIN_AUDIT_DIR to a per-run scratch dir BEFORE any test
+# runs, so audit-emitting code paths (content-sanity, shell-audit, etc.)
+# can't leak fixture events into the operator's real ~/.gbrain/audit/. See
+# test/helpers/audit-dir-preload.ts for the full rationale.
+preload = ["./test/helpers/legacy-embedding-preload.ts", "./test/helpers/audit-dir-preload.ts"]
diff --git a/test/audit/audit-dir-preload.test.ts b/test/audit/audit-dir-preload.test.ts
new file mode 100644
index 0000000000..3987eeddd9
--- /dev/null
+++ b/test/audit/audit-dir-preload.test.ts
@@ -0,0 +1,79 @@
+/**
+ * Regression gate for #2823: the shared test bootstrap
+ * (`test/helpers/audit-dir-preload.ts`, wired via `bunfig.toml`'s
+ * `preload`) must redirect `GBRAIN_AUDIT_DIR` to a per-run scratch
+ * directory BEFORE any test file runs, so audit-emitting code paths never
+ * fall through to the operator's real `~/.gbrain/audit/`.
+ *
+ * Before the fix, `test/import-file.test.ts`'s oversize-content boundary
+ * fixture (`'borderline-slug'`) fired a real `soft_block` content-sanity
+ * event straight into the developer's live audit trail on every test run.
+ * This file reproduces that exact event shape directly against the audit
+ * module (no PGLite/import-file machinery needed) and asserts it lands
+ * only in the scratch dir.
+ */
+import { describe, test, expect } from 'bun:test';
+import { homedir, tmpdir } from 'os';
+import { join } from 'path';
+import { readFileSync, existsSync } from 'fs';
+import { resolveAuditDir } from '../../src/core/audit/audit-writer.ts';
+import {
+ logContentSanityAssessment,
+ readRecentContentSanityEvents,
+ computeContentSanityAuditFilename,
+} from '../../src/core/audit/content-sanity-audit.ts';
+import { assessContentSanity } from '../../src/core/content-sanity.ts';
+
+describe('shared test-bootstrap audit isolation (#2823)', () => {
+ test('GBRAIN_AUDIT_DIR is set by the preload to a scratch dir, not the real ~/.gbrain/audit', () => {
+ const dir = process.env.GBRAIN_AUDIT_DIR;
+ expect(dir).toBeTruthy();
+ expect(dir).not.toBe(join(homedir(), '.gbrain', 'audit'));
+ // mkdtempSync(tmpdir(), ...) always lives directly under os.tmpdir().
+ expect(dir!.startsWith(tmpdir())).toBe(true);
+ });
+
+ test('resolveAuditDir() resolves to the preload-set scratch dir', () => {
+ const expected = process.env.GBRAIN_AUDIT_DIR;
+ expect(expected).toBeTruthy();
+ expect(resolveAuditDir()).toBe(expected!);
+ });
+
+ test('an oversize content-sanity event (the import-file.test.ts "borderline-slug" shape) never reaches the real ~/.gbrain/audit', () => {
+ // Unique per test-run so a stale match from a prior manual run can
+ // never produce a false pass.
+ const sentinelSlug = `borderline-slug-audit-dir-preload-${Date.now()}-${Math.random().toString(36).slice(2)}`;
+
+ const realAuditDir = join(homedir(), '.gbrain', 'audit');
+ const realAuditFile = join(realAuditDir, computeContentSanityAuditFilename());
+
+ // Reproduce the exact disposition the leaking fixture hits: body bytes
+ // over DEFAULT_BYTES_BLOCK (500_000) with no junk pattern match →
+ // shouldSkipEmbed=true, no shouldQuarantine → classified 'soft_block'.
+ const result = assessContentSanity({
+ compiled_truth: 'x'.repeat(600_000),
+ timeline: '',
+ title: 'Borderline',
+ });
+ expect(result.shouldSkipEmbed).toBe(true);
+ expect(result.shouldQuarantine).toBe(false);
+
+ logContentSanityAssessment(sentinelSlug, 'default', result);
+
+ // 1. The event IS readable back through the audit module — proves the
+ // write succeeded and landed in the dir resolveAuditDir() reports.
+ const recent = readRecentContentSanityEvents(1);
+ const found = recent.find((e) => e.slug === sentinelSlug);
+ expect(found).toBeDefined();
+ expect(found?.event_type).toBe('soft_block');
+
+ // 2. The real ~/.gbrain/audit content-sanity file for the current ISO
+ // week — if it exists at all on this machine — does NOT contain the
+ // sentinel slug. This is the actual regression: before the fix, this
+ // assertion would fail on any machine with a real ~/.gbrain.
+ if (existsSync(realAuditFile)) {
+ const contents = readFileSync(realAuditFile, 'utf8');
+ expect(contents).not.toContain(sentinelSlug);
+ }
+ });
+});
diff --git a/test/gbrain-home-isolation.test.ts b/test/gbrain-home-isolation.test.ts
index 25e1f95066..d4ce3c29fc 100644
--- a/test/gbrain-home-isolation.test.ts
+++ b/test/gbrain-home-isolation.test.ts
@@ -19,8 +19,14 @@ import { mkdtempSync, existsSync, readdirSync, statSync, rmSync } from 'fs';
import { homedir, tmpdir } from 'os';
import { join } from 'path';
-// Save original env so we don't leak between tests.
+// Save original env so we don't leak between tests. #2823: GBRAIN_AUDIT_DIR
+// must be captured too — the shared test bootstrap (test/helpers/audit-dir-preload.ts)
+// sets a process-global scratch dir before any test file runs, so "restore"
+// here means "put back the preload's value," not "delete the var and let
+// it fall through to the real ~/.gbrain/audit for every test file that
+// runs after this one in the same shard process."
const ORIG_GBRAIN_HOME = process.env.GBRAIN_HOME;
+const ORIG_GBRAIN_AUDIT_DIR = process.env.GBRAIN_AUDIT_DIR;
function fresh(): string {
return mkdtempSync(join(tmpdir(), 'gbrain-home-isolation-'));
@@ -134,7 +140,11 @@ describe('GBRAIN_HOME write-side isolation', () => {
expect(resolveAuditDir()).toBe(auditTmp);
} finally {
process.env.GBRAIN_HOME = ORIG_GBRAIN_HOME;
- delete process.env.GBRAIN_AUDIT_DIR;
+ if (ORIG_GBRAIN_AUDIT_DIR === undefined) {
+ delete process.env.GBRAIN_AUDIT_DIR;
+ } else {
+ process.env.GBRAIN_AUDIT_DIR = ORIG_GBRAIN_AUDIT_DIR;
+ }
rmSync(tmp, { recursive: true, force: true });
rmSync(auditTmp, { recursive: true, force: true });
}
diff --git a/test/helpers/audit-dir-preload.ts b/test/helpers/audit-dir-preload.ts
new file mode 100644
index 0000000000..6f723238c0
--- /dev/null
+++ b/test/helpers/audit-dir-preload.ts
@@ -0,0 +1,51 @@
+/**
+ * Pre-test setup: redirect audit-writer output (content-sanity,
+ * shell-audit, supervisor-audit, slug-fallback, etc. — every module built
+ * on `src/core/audit/audit-writer.ts`) to a per-run scratch directory
+ * instead of the operator's real `~/.gbrain/audit/`.
+ *
+ * Why this exists (#2823): `audit-writer.ts::resolveAuditDir()` honors a
+ * `GBRAIN_AUDIT_DIR` env override, but nothing in the shared test bootstrap
+ * ever set it. Any test that exercises an audit-emitting code path without
+ * wrapping the call in its own `withEnv({ GBRAIN_AUDIT_DIR: ... })` (most
+ * don't — only the content-sanity-focused suites did) fell through to the
+ * real default and appended fixture rows into the operator's live audit
+ * trail. `test/import-file.test.ts`'s oversize-content boundary fixture
+ * (`'borderline-slug'`, content just under `MAX_FILE_SIZE` but over
+ * `DEFAULT_BYTES_BLOCK`) is the concrete offender named in the issue: it
+ * fires a real `soft_block` content-sanity event on every run, landing in
+ * `~/.gbrain/audit/content-sanity-YYYY-Www.jsonl` right alongside real
+ * production signal that doctor's `content_sanity_audit_recent` check
+ * reads.
+ *
+ * Fix: set `GBRAIN_AUDIT_DIR` once, globally, before any test file loads,
+ * to a fresh `mkdtemp` directory unique to THIS process. Each
+ * `scripts/run-unit-shard.sh` shard is its own `bun test` process, so each
+ * shard gets its own scratch dir automatically — no cross-shard collision,
+ * no manual cleanup needed (short-lived test process; OS reaps tmp, same
+ * tradeoff `test/helpers/with-env.ts`'s `emptyHome()` documents).
+ *
+ * Individual test files that already manage their own isolated
+ * `GBRAIN_AUDIT_DIR` per-test via `withEnv` (e.g.
+ * `test/import-file-content-sanity.test.ts`, `test/audit/content-sanity-audit.test.ts`)
+ * are unaffected — `withEnv` saves/restores around whatever this preload
+ * set as the process-global default, same as any other env var.
+ *
+ * Only sets the var if it isn't already set, so a developer who exports
+ * `GBRAIN_AUDIT_DIR` themselves (e.g. to inspect audit output after a
+ * local run) keeps their override.
+ *
+ * Imported by `bunfig.toml` via
+ * `preload = [..., "./test/helpers/audit-dir-preload.ts"]`.
+ */
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+if (!process.env.GBRAIN_AUDIT_DIR) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-test-audit-'));
+ process.env.GBRAIN_AUDIT_DIR = dir;
+ if (process.env.GBRAIN_DEBUG_PRELOAD === '1') {
+ console.error(`[audit-dir-preload] GBRAIN_AUDIT_DIR=${dir}`);
+ }
+}