Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test: GBRAIN_TEST_* opt-ins survive the operator-env scrub; old names fail fast (D7)

garrytan23a2919e81a3
diff --git a/.github/workflows/macos-validation.yml b/.github/workflows/macos-validation.yml
index 2b56287856..d949c60d38 100644
--- a/.github/workflows/macos-validation.yml
+++ b/.github/workflows/macos-validation.yml
@@ -89,7 +89,7 @@ jobs:
if: ${{ !cancelled() }}
env:
GBRAIN_BASH32: /bin/bash
- GBRAIN_BASH32_REQUIRE: '1'
+ GBRAIN_TEST_BASH32_REQUIRE: '1'
# tsc peaks near 3 GB of heap on this repo; Node's default limit on
# the 7 GB runner is lower, so typecheck aborted on heap exhaustion.
NODE_OPTIONS: --max-old-space-size=4096
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index f9e8848f79..ebc11eeeea 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -222,7 +222,7 @@ jobs:
# test's real-parser fixture cases mandatory.
- name: Shell scripts parse under bash 3.2
env:
- GBRAIN_BASH32_REQUIRE: '1'
+ GBRAIN_TEST_BASH32_REQUIRE: '1'
run: |
bun run check:bash32
bun test --timeout 60000 test/scripts/check-bash32.test.ts
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 845c3ce8a0..d7ade381df 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -399,7 +399,7 @@ Test command tiers, each with a clear scope:
| `bun run test:slow` | Just the `*.slow.test.ts` set (intentional cold-path correctness checks). | seconds-to-minutes | When touching slow-path code. |
| `bun run test:serial` | Just the `*.serial.test.ts` set (cross-file-contention quarantine; one bun process per file for true module-registry isolation), run through a POOL of concurrent per-file processes — the isolation is per-process, not per-machine. Dispatch is heaviest-first (LPT) from the advisory `scripts/serial-weights.json` (seconds; mined from the `.context/serial-durations.txt` table each run banks; absent/corrupt weights fall back to discovery order, absent keys to the corpus p75 — scheduling only, never correctness; LPT order + the corrupt-weights fail-soft are pinned by `test/scripts/run-serial-pool.test.ts`). Pool defaults to `min(detect_cpus, 4)` then memory-adapts (same doctrine as the parallel runner); a small growth-guarded set of files (machine-global state or contention-critical timing — see the justified `EXCLUSIVE_FILES` list in `scripts/run-serial-tests.sh`, capped at 3 by `test/scripts/serial-files.test.ts`) runs on a sequential EXCLUSIVE lane after the pool. Per-test timeout 120s (pooled contention headroom); each pooled file is wall-clock-killed at 300s (`timeout -k`, exit-hang containment). `SHARD=N/M` partitions pooled files by duration; the three exclusive files run only on shard 1. Unset runs the complete corpus. Routing variables are cleared before tests start, so nested runners remain independent. Externally-killed files (exit 143/137 or a missing exit sentinel — sibling-workspace cleanup, memory jetsam) get ONE sequential rescue re-run, mirroring the parallel runner's doctrine: phantoms stay green with a rescue note, real failures stay red. Prints per-file PASS lines plus a top-10 slowest-files list. Knobs: `GBRAIN_SERIAL_POOL=N` (explicit pool width — bypasses the memory clamp; `1` restores fully-sequential), `GBRAIN_SERIAL_FILE_TIMEOUT`. | a few minutes for all ~220 files at pool=4 | Debugging quarantined files; CI's serial-tests job. |
| `bun run test:e2e` | Real Postgres E2E. Requires Docker + `DATABASE_URL`. Sequential within a shard; `SHARD=N/M` fans out against separate databases (ci-local runs 4 containers). Activates the PGLite snapshot like every other runner (per-file cold-path opt-outs where the test asserts the path TO post-initSchema state), exporting it as an ABSOLUTE path so CLI children spawned with varying cwd still find it. | ~5-10min | Pre-ship; nightly. |
-| `bun run test:compile-smoke` | Self-update integrity verify under a REAL `bun build --compile` binary, offline (sets `GBRAIN_SELFUPDATE_COMPILE_SMOKE=1`). The unit suite mocks the network seams; this proves the dependency-free crypto/base64/JSON verify path survives compilation — the failure mode `sigstore-js` would have hit. | ~5s (one compile) | When touching `src/core/binary-self-update.ts`; pre-ship on self-update changes. |
+| `bun run test:compile-smoke` | Self-update integrity verify under a REAL `bun build --compile` binary, offline; also runs unconditionally in the serial lane. The unit suite mocks the network seams; this proves the dependency-free crypto/base64/JSON verify path survives compilation — the failure mode `sigstore-js` would have hit. | under 1s (one small compile) | When touching `src/core/binary-self-update.ts`; pre-ship on self-update changes. |
| `bun run test:admin` | Pinned Playwright Chromium tests for the production embedded admin UI, served with an isolated temporary home/cwd and in-memory PGLite. Exercises owner login, OAuth consent, registration, setup, and lifecycle actions. | seconds-to-minutes | When touching the admin browser flow; required `admin-browser` CI job. |
For the admin browser lane, install frozen dependencies in the repository and
@@ -1255,14 +1255,14 @@ tracked `*.sh` except the guard fixtures under `test/fixtures/guards/`. It
uses the first parser available: `GBRAIN_BASH32=<path>` (a bash 3.x binary),
`/bin/bash` when it is bash 3.x (stock macOS), or the digest-pinned `bash:3.2`
Docker image (`GBRAIN_BASH32=docker` forces the image). With none it prints
-one skip line and exits 0; `GBRAIN_BASH32_REQUIRE=1` makes that exit 2. Each
+one skip line and exits 0; `GBRAIN_TEST_BASH32_REQUIRE=1` makes that exit 2. Each
failure prints `FAIL: <file:line>`, `Why:` (macOS `/bin/bash` is 3.2), `Fix:`
(read heredoc text with `IFS= read -r -d '' VAR <<'EOF' || true`) and `See:`.
To reproduce one file by hand:
`docker run --rm -v "$PWD":/w -w /w bash:3.2 bash -n <file>`.
The guard checks parsing only. It is not in `bun run verify`, which must not
-need Docker. The `test.yml` verify job runs it with `GBRAIN_BASH32_REQUIRE=1`
+need Docker. The `test.yml` verify job runs it with `GBRAIN_TEST_BASH32_REQUIRE=1`
together with `test/scripts/check-bash32.test.ts`, whose real-parser cases
feed it the `test/fixtures/guards/check-bash32.sh/{bad,good}` trees. The
macOS 26 job runs it under `/bin/bash` and then runs `bun run verify` there,
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index dc2a68ff38..90f140bb80 100644
--- a/docs/architecture/key-files/core-services-3.md
+++ b/docs/architecture/key-files/core-services-3.md
@@ -11,6 +11,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.
-- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, canonical entity types (`person`, `company`, `organization`, `entity`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints.
+- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, canonical entity types (`person`, `company`, `organization`, `entity`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_TEST_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints.
- `src/core/verbs/usage-log.ts` — observability sidecar: one JSONL line per verb call at `~/.gbrain/integrations/memory-verbs/usage.jsonl` (gbrainPath — GBRAIN_HOME honored; `brainId()` = the resolved gbrain home). LOCAL ONLY, never uploaded, stats-only (lock-free 10MB rotation may drop lines; O_APPEND line-atomic, best-effort on Windows). `logVerbUsage` is fire-and-forget (never awaited, never throws); written from the DISPATCH layer so param-validation failures count. `readVerbUsage`/`earliestVerbUsageTs` feed `gbrain protocol stats` (incl. measured TTHW vs the init-stamped `protocol_installed_at`) and the doctor `memory_verbs_usage` check.
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.md
index a43bce80ae..db8b83ab34 100644
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@ -36,7 +36,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/check-progress-to-stdout.sh` — CI guard against regressing to `\r`-on-stdout progress. Wired into `bun run test` via `scripts/check-progress-to-stdout.sh && bun test` in package.json.
- `scripts/check-retired-phrases.sh` — the retired-phrase guard (`bun run check:retired-phrases`, in `bun run verify`): greps `CLAUDE.md`, `AGENTS.md`, `CONTRIBUTING.md`, `docs/` and `skills/` for contributor-workflow phrases refactor wave 1 retired (the `RETIRED` table: pattern + the current instruction) and prints `FAIL: <file:line>` / `Why:` / `Fix:` / `See: docs/TESTING.md#retired-phrase-guard` per hit. Historical records (`docs/designs/`, `docs/test-audit/`, `docs/incidents/`, `docs/plans/`, `docs/proposals/`, `docs/research/`, `docs/issues/`, `docs/superpowers/`, `docs/migrations/`, `skills/migrations/`, the `docs/architecture/wave-1-*` porting kit) are exempt; `CHANGELOG.md` is not scanned. `GBRAIN_GUARD_ROOT` seam; fixtures `test/fixtures/guards/check-retired-phrases.sh/` (one `bad-<location>` tree per scanned location); pinned by `test/scripts/check-retired-phrases.test.ts`.
-- `scripts/check-bash32.sh` — the bash 3.2 parse guard (`bun run check:bash32`): runs the real GNU bash 3.2 parser (`bash -n`) over every tracked `*.sh` except `test/fixtures/guards/`, because macOS `/bin/bash` is 3.2 and rejects shapes bash 5 accepts (a heredoc inside `$(...)` with an odd quote). Parser order: `GBRAIN_BASH32` (a bash 3.x binary; `docker` forces the image), `/bin/bash` when it is 3.x, then the digest-pinned `bash:3.2` image. No parser prints one skip line and exits 0; `GBRAIN_BASH32_REQUIRE=1` makes it exit 2. Prints `FAIL: <file:line>` / `Why:` / `Fix:` / `See: docs/TESTING.md#bash-32-parse-guard`. Parse only, not in `bun run verify`; run by the `test.yml` verify job (image) and `macos-validation.yml` (`/bin/bash`, followed by `bun run verify`). `GBRAIN_GUARD_ROOT` seam; fixtures `test/fixtures/guards/check-bash32.sh/{bad,good}`; pinned by `test/scripts/check-bash32.test.ts`.
+- `scripts/check-bash32.sh` — the bash 3.2 parse guard (`bun run check:bash32`): runs the real GNU bash 3.2 parser (`bash -n`) over every tracked `*.sh` except `test/fixtures/guards/`, because macOS `/bin/bash` is 3.2 and rejects shapes bash 5 accepts (a heredoc inside `$(...)` with an odd quote). Parser order: `GBRAIN_BASH32` (a bash 3.x binary; `docker` forces the image), `/bin/bash` when it is 3.x, then the digest-pinned `bash:3.2` image. No parser prints one skip line and exits 0; `GBRAIN_TEST_BASH32_REQUIRE=1` makes it exit 2. Prints `FAIL: <file:line>` / `Why:` / `Fix:` / `See: docs/TESTING.md#bash-32-parse-guard`. Parse only, not in `bun run verify`; run by the `test.yml` verify job (image) and `macos-validation.yml` (`/bin/bash`, followed by `bun run verify`). `GBRAIN_GUARD_ROOT` seam; fixtures `test/fixtures/guards/check-bash32.sh/{bad,good}`; pinned by `test/scripts/check-bash32.test.ts`.
- `scripts/check-source-id-projection.sh` — CI grep guard for the multi-source bug class. Greps `src/core/postgres-engine.ts` + `src/core/pglite-engine.ts` for `SELECT.*FROM pages` projections matching the `rowToPage` feeder shape (id + slug + type + title) and fails if `source_id` is missing. `Page.source_id` is required at the type level; a projection dropping the column produces `Page` rows with `source_id: undefined` while TypeScript's `: string` lies about it. Wired into `bun run verify`.
diff --git a/package.json b/package.json
index a91018fb95..c6bd615407 100644
--- a/package.json
+++ b/package.json
@@ -81,7 +81,7 @@
"check:wasm": "bash scripts/check-wasm-embedded.sh",
"check:pglite-embedded": "bash scripts/check-pglite-embedded.sh",
"check:newlines": "bash scripts/check-trailing-newline.sh",
- "test:compile-smoke": "GBRAIN_SELFUPDATE_COMPILE_SMOKE=1 bun test test/binary-self-update-compiled.serial.test.ts",
+ "test:compile-smoke": "bun test test/binary-self-update-compiled.serial.test.ts",
"test:e2e": "bash scripts/run-e2e.sh",
"test:slow": "bash scripts/run-slow-tests.sh",
"test:scale": "bun scripts/scale/run.ts",
@@ -114,6 +114,7 @@
"check:admin-build": "bash scripts/check-admin-build.sh",
"check:admin-embedded": "bash scripts/check-admin-embedded.sh",
"check:test-isolation": "bash scripts/check-test-isolation.sh",
+ "check:test-env-opt-ins": "bun scripts/check-test-env-opt-ins.ts",
"check:fuzz-purity": "bash scripts/check-fuzz-purity.sh",
"check:operations-filter-bypass": "bash scripts/check-operations-filter-bypass.sh",
"check:fixture-privacy": "bash scripts/check-fixture-privacy.sh",
diff --git a/scripts/check-bash32.sh b/scripts/check-bash32.sh
index 57876f4ffd..c832675ffc 100755
--- a/scripts/check-bash32.sh
+++ b/scripts/check-bash32.sh
@@ -14,7 +14,7 @@
# /bin/bash when it is bash 3.x (stock macOS)
# Docker image bash:3.2 (GNU bash 3.2.57, digest-pinned)
# GBRAIN_BASH32=docker forces the image. Without a parser the guard prints
-# one skip line and exits 0, unless GBRAIN_BASH32_REQUIRE=1 (CI), which
+# one skip line and exits 0, unless GBRAIN_TEST_BASH32_REQUIRE=1 (CI), which
# turns that into exit 2.
#
# Run: bun run check:bash32
@@ -31,7 +31,14 @@ ROOT="$(pwd -P)"
IMAGE='bash:3.2@sha256:0fd7cb8499c63a3c9345e7088a9cd83bb69f6e895e83833859aff838a0312091'
DOCKER="${GBRAIN_BASH32_DOCKER:-docker}"
-REQUIRE="${GBRAIN_BASH32_REQUIRE:-0}"
+if [ -n "${GBRAIN_BASH32_REQUIRE:-}" ]; then
+ echo "✗ bash 3.2 parse: GBRAIN_BASH32_REQUIRE was renamed to GBRAIN_TEST_BASH32_REQUIRE." >&2
+ echo "Why: test opt-ins live under GBRAIN_TEST_ so the test preload's operator-env scrub keeps them; the old name is no longer read." >&2
+ echo "Fix: unset GBRAIN_BASH32_REQUIRE && export GBRAIN_TEST_BASH32_REQUIRE=${GBRAIN_BASH32_REQUIRE}" >&2
+ echo "Docs: docs/TESTING.md#test-isolation-lint-and-helpers" >&2
+ exit 2
+fi
+REQUIRE="${GBRAIN_TEST_BASH32_REQUIRE:-0}"
FILES=()
if [ -n "${GBRAIN_GUARD_ROOT:-}" ]; then
@@ -55,7 +62,7 @@ is_bash3() {
unavailable() {
if [ "$REQUIRE" = "1" ]; then
- echo "✗ bash 3.2 parse: $1, and GBRAIN_BASH32_REQUIRE=1 forbids skipping" >&2
+ echo "✗ bash 3.2 parse: $1, and GBRAIN_TEST_BASH32_REQUIRE=1 forbids skipping" >&2
exit 2
fi
echo "- bash 3.2 parse: skipped ($1; install Docker or set GBRAIN_BASH32 to a bash 3.2 binary)"
diff --git a/scripts/check-test-env-opt-ins.ts b/scripts/check-test-env-opt-ins.ts
new file mode 100644
index 0000000000..4adaabaf35
--- /dev/null
+++ b/scripts/check-test-env-opt-ins.ts
@@ -0,0 +1,213 @@
+#!/usr/bin/env bun
+/**
+ * Test env opt-in guard (docs/TESTING.md#test-isolation-lint-and-helpers).
+ *
+ * test/helpers/operator-env-preload.ts deletes every GBRAIN_* variable outside
+ * its keep-lists before any test file loads. A test that gates execution on a
+ * stripped name (`describe.skipIf(!process.env.GBRAIN_X)`, `if (env) return`,
+ * a top-level constant used that way) can never see it set, so the gate is a
+ * silent no-op: six opt-ins, including `bun run test:compile-smoke`, were dead
+ * this way. This guard parses every test file under test/ and evals/ with the
+ * TypeScript AST and fails on an execution-gating read of a GBRAIN_* name the
+ * scrub strips, unless the same file assigns that name itself. Names that
+ * src/ reads are product configuration, not test opt-ins: the scrub removing
+ * them is the hermeticity it exists for, so a test asserting their absence is
+ * not flagged.
+ *
+ * The policy (keep-lists, RENAMED map, naming rule) is imported from
+ * test/helpers/operator-env-policy.ts, the module the preload applies.
+ *
+ * Seam: GBRAIN_GUARD_ROOT (fixture tree root).
+ */
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import ts from 'typescript';
+import { isStripped } from '../test/helpers/operator-env-policy';
+
+const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');
+const ANCHOR = 'docs/TESTING.md#test-isolation-lint-and-helpers';
+const SCAN_DIRS = ['test', 'evals'];
+const SKIP_DIRS = new Set(['node_modules', 'guards']);
+const GATE_CALLS = new Set(['skipIf', 'if', 'todoIf', 'runIf']);
+const TEST_CALL = /^(describe|test|it)(\.(skip|todo|only|if|skipIf))?$/;
+
+function tsFiles(dir: string): string[] {
+ if (!existsSync(dir)) return [];
+ const out: string[] = [];
+ for (const entry of readdirSync(dir).sort()) {
+ const full = join(dir, entry);
+ if (statSync(full).isDirectory()) {
+ if (!SKIP_DIRS.has(entry)) out.push(...tsFiles(full));
+ } else if (/\.(ts|tsx|mts)$/.test(entry) && !entry.endsWith('.d.ts')) {
+ out.push(full);
+ }
+ }
+ return out;
+}
+
+/** `process.env.NAME` / `process.env['NAME']` → NAME, else null. */
+function envName(node: ts.Node): string | null {
+ let target: ts.Expression;
+ let name: string;
+ if (ts.isPropertyAccessExpression(node)) {
+ target = node.expression;
+ name = node.name.text;
+ } else if (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression)) {
+ target = node.expression;
+ name = node.argumentExpression.text;
+ } else {
+ return null;
+ }
+ if (!ts.isPropertyAccessExpression(target) || target.name.text !== 'env') return null;
+ if (!ts.isIdentifier(target.expression) || target.expression.text !== 'process') return null;
+ return name;
+}
+
+const isAssignmentTarget = (node: ts.Node): boolean => {
+ const parent = node.parent;
+ if (ts.isDeleteExpression(parent)) return true;
+ return ts.isBinaryExpression(parent)
+ && parent.left === node
+ && parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment
+ && parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment;
+};
+
+const contains = (outer: ts.Node | undefined, inner: ts.Node): boolean =>
+ !!outer && inner.pos >= outer.pos && inner.end <= outer.end;
+
+function calleeText(call: ts.CallExpression, sf: ts.SourceFile): string {
+ let callee: ts.Expression = call.expression;
+ while (ts.isCallExpression(callee)) callee = callee.expression;
+ return callee.getText(sf);
+}
+
+/** Whether an if-branch stops or selects test execution (return, throw, a test registration, process.exit). */
+function branchGates(stmt: ts.Statement | undefined, sf: ts.SourceFile): boolean {
+ if (!stmt) return false;
+ let found = false;
+ const visit = (node: ts.Node): void => {
+ if (found || ts.isFunctionLike(node)) return;
+ if (ts.isReturnStatement(node) || ts.isThrowStatement(node)) found = true;
+ else if (ts.isCallExpression(node)) {
+ const text = calleeText(node, sf);
+ if (TEST_CALL.test(text) || text === 'process.exit') found = true;
+ }
+ if (!found) ts.forEachChild(node, visit);
+ };
+ visit(stmt);
+ return found;
+}
+
+const selectsTest = (expr: ts.Expression, sf: ts.SourceFile): boolean =>
+ TEST_CALL.test(expr.getText(sf));
+
+/**
+ * Whether `node` (an env read, or a reference to a value derived from one)
+ * gates execution. Walks up to the enclosing statement; a `const X = <read>`
+ * or `return <read>` makes every use of X / the returning function a gate
+ * candidate in turn.
+ */
+function gates(node: ts.Node, sf: ts.SourceFile, seen: Set<string>): boolean {
+ for (let child = node, cur = node.parent; cur; child = cur, cur = cur.parent) {
+ if (ts.isCallExpression(cur) && cur.arguments.some(a => contains(a, child))) {
+ const callee = cur.expression;
+ if (ts.isPropertyAccessExpression(callee) && GATE_CALLS.has(callee.name.text)) return true;
+ continue;
+ }
+ if (ts.isIfStatement(cur) && contains(cur.expression, node)) {
+ return branchGates(cur.thenStatement, sf) || branchGates(cur.elseStatement, sf);
+ }
+ if (ts.isConditionalExpression(cur) && contains(cur.condition, node)) {
+ return selectsTest(cur.whenTrue, sf) || selectsTest(cur.whenFalse, sf);
+ }
+ if (ts.isVariableDeclaration(cur) && ts.isIdentifier(cur.name) && contains(cur.initializer, node)) {
+ return usesGate(cur.name.text, sf, seen);
+ }
+ if (ts.isReturnStatement(cur)) {
+ const fn = enclosingFunctionName(cur);
+ return fn ? usesGate(fn, sf, seen) : false;
+ }
+ if (ts.isFunctionLike(cur) || ts.isSourceFile(cur)) return false;
+ }
+ return false;
+}
+
+function enclosingFunctionName(node: ts.Node): string | null {
+ for (let cur = node.parent; cur; cur = cur.parent) {
+ if (ts.isFunctionDeclaration(cur)) return cur.name?.text ?? null;
+ if (ts.isArrowFunction(cur) || ts.isFunctionExpression(cur)) {
+ const decl = cur.parent;
+ return ts.isVariableDeclaration(decl) && ts.isIdentifier(decl.name) ? decl.name.text : null;
+ }
+ if (ts.isFunctionLike(cur)) return null;
+ }
+ return null;
+}
+
+function usesGate(name: string, sf: ts.SourceFile, seen: Set<string>): boolean {
+ if (seen.has(name)) return false;
+ seen.add(name);
+ let found = false;
+ const visit = (node: ts.Node): void => {
+ if (found) return;
+ if (ts.isIdentifier(node) && node.text === name && !isDeclarationName(node) && gates(node, sf, seen)) found = true;
+ else ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ return found;
+}
+
+const isDeclarationName = (node: ts.Identifier): boolean => {
+ const parent = node.parent;
+ return (ts.isVariableDeclaration(parent) || ts.isFunctionDeclaration(parent) || ts.isParameter(parent))
+ && parent.name === node;
+};
+
+interface Finding { file: string; line: number; name: string }
+
+function scanFile(path: string): Finding[] {
+ const text = readFileSync(path, 'utf8');
+ if (!text.includes('GBRAIN_')) return [];
+ const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
+ const assigned = new Set<string>();
+ const reads: Array<{ node: ts.Node; name: string }> = [];
+ const visit = (node: ts.Node): void => {
+ const name = envName(node);
+ if (name && name.startsWith('GBRAIN_')) {
+ if (isAssignmentTarget(node)) assigned.add(name);
+ else reads.push({ node, name });
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ const findings: Finding[] = [];
+ for (const { node, name } of reads) {
+ if (!isStripped(name) || assigned.has(name) || PRODUCT.has(name)) continue;
+ if (!gates(node, sf, new Set())) continue;
+ const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
+ findings.push({ file: relative(ROOT, path), line, name });
+ }
+ return findings;
+}
+
+function productNames(): Set<string> {
+ const names = new Set<string>();
+ for (const file of tsFiles(join(ROOT, 'src'))) {
+ for (const m of readFileSync(file, 'utf8').matchAll(/\bGBRAIN_[A-Z0-9_]+/g)) names.add(m[0]);
+ }
+ return names;
+}
+
+const PRODUCT = productNames();
+const findings = SCAN_DIRS.flatMap(dir => tsFiles(join(ROOT, dir))).flatMap(scanFile);
+if (findings.length === 0) {
+ console.log('✓ test env opt-ins: no test gates execution on a GBRAIN_* name the operator-env scrub strips');
+ process.exit(0);
+}
+for (const f of findings) {
+ console.error(`FAIL [test_env_opt_in_stripped]: ${f.file}:${f.line} gates execution on ${f.name}, which the operator-env scrub deletes before tests run, so this gate can never fire.`);
+}
+console.error('Why: test/helpers/operator-env-preload.ts strips every GBRAIN_* name outside its keep-lists (test/helpers/operator-env-policy.ts); an opt-in under such a name is a silent skip.');
+console.error('Fix: rename the opt-in to GBRAIN_TEST_<AREA>_<WHAT> (paid: GBRAIN_TEST_LIVE_<WHAT>) and add the old name to RENAMED in test/helpers/operator-env-policy.ts, or add a KEEP_EXACT row there with its reason. GBRAIN_TEST_KEEP_AMBIENT_ENV=1 disables the scrub for local debugging only.');
+console.error(`Docs: ${ANCHOR}`);
+process.exit(1);
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index bb21180917..76058ce82d 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -74,7 +74,7 @@ check-durable-flush.ts scanner yes #5595/#5475 Windows durability (TS AST, scope
check-schema-migrations-fresh.sh buildfresh exempt regenerates src/core/schema-migrations/registry.generated.ts + diffs; generator enforces filename/version/name cross-check and duplicate versions (unit: test/scripts/build-schema-migrations.test.ts)
check-schema-fresh.sh buildfresh exempt W2: regenerates the schema chain (fragments -> schema.sql regions -> schema-embedded -> PGLite template) into a temp dir and diffs every output; names the source to edit (unit: test/scripts/build-schema.test.ts)
check-retired-phrases.sh scanner yes W7 (refactor wave 1): retired contributor-workflow phrases (migrations array, two-engine SQL rule, CLI switch case, region policy, hand-synced PGLite schema) fail in CLAUDE.md, AGENTS.md, CONTRIBUTING.md, docs/, skills/; historical records and the porting kit exempt; GBRAIN_GUARD_ROOT seam; bad-<location> fixtures
-check-bash32.sh scanner todo #5810: every tracked *.sh parses under bash 3.2 (real parser: GBRAIN_BASH32, stock macOS /bin/bash, or the digest-pinned bash:3.2 image); not in verify CHECKS or this self-test, which must not need Docker; its bad/good fixtures run in test/scripts/check-bash32.test.ts, mandatory in the test.yml verify-job step (GBRAIN_BASH32_REQUIRE=1)
+check-bash32.sh scanner todo #5810: every tracked *.sh parses under bash 3.2 (real parser: GBRAIN_BASH32, stock macOS /bin/bash, or the digest-pinned bash:3.2 image); not in verify CHECKS or this self-test, which must not need Docker; its bad/good fixtures run in test/scripts/check-bash32.test.ts, mandatory in the test.yml verify-job step (GBRAIN_TEST_BASH32_REQUIRE=1)
check-schema-migration-order.ts repostate exempt EO10: a migration origin/master lacks must be numbered above its latest version; reads the base ref from git (unit: test/scripts/build-schema-migrations.test.ts)
check-structural-manifest.sh buildfresh exempt regenerate+diff of structural-suites.tsv (classify-tests.ts); the diff IS the self-test
check-opencode-pin.sh repostate exempt pin-stamp drift check (OPENCODE-CLI-PIN.md stamps vs heavy-tests opencode-door env); own bun guard tests in test/check-bootstrap-guards.test.ts
@@ -84,3 +84,4 @@ check-orphan-modules.mjs scanner yes runtime-reachability walk (static+dynamic r
check-test-placeholders.mjs scanner yes TypeScript AST (CallExpression) scan of test/**/*.test.ts for no-op expect(true)/expect(1) placeholders; path+test+count allowlist (disabled in fixture mode); fixture root via argv/GBRAIN_GUARD_ROOT; in verify CHECKS
check-test-discriminates.sh buildfresh exempt manual per-PR discrimination helper (#3665): reverts named source files to their pre-fix state and runs the named test file to prove it fails without the fix — the test run IS the check; not in verify CHECKS or CI
check-agent-contract.ts scanner yes agent operator contract v1 (B9): syntax-only TS AST; per-rule shrink-only baselines in scripts/agent-contract-baselines/; registry completeness + code naming never baselined; GBRAIN_GUARD_ROOT seam (baselines from <root>/baselines)
+check-test-env-opt-ins.ts scanner yes D7 (GBRA-47): execution-gating process.env.GBRAIN_* reads in test/ and evals/ of names the operator-env preload strips (TS AST); policy shared with test/helpers/operator-env-policy.ts
diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh
index 0742151e14..4b5299ba0b 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -151,6 +151,7 @@ for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GROK_|OPEN
GBRAIN_TEST_DB) ;; # explicit schema-reset opt-in for service hosts; schema-drift still requires a test-shaped DB name
GBRAIN_PGBOUNCER_URL|GBRAIN_PGBOUNCER_DIRECT_URL|GBRAIN_CI_REQUIRE_PGBOUNCER) ;; # explicit pooler test target and execution requirement
GBRAIN_PGBOUNCER_E2E_URL|GBRAIN_PGBOUNCER_E2E_DB) ;; # backend-matrix pooled target (scripts/e2e-backend-matrix.txt)
+ GBRAIN_TEST_REQUIRE_COMPILE) ;; # bootstrap-compiled-binary opt-in: a failed compile fails instead of skipping
GBRAIN_E2E_FILE_TIMEOUT) ;; # per-file cap override — read AFTER this scrub, so it must survive it
GBRAIN_E2E_ALLOW_DB) ;; # #3485 name-floor opt-in — the guard's own error
# message tells operators to set it; stripping it
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index ef451d1f6d..4088edb681 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -87,6 +87,9 @@ CHECKS=(
"check:privacy"
"check:test-names"
"check:test-isolation"
+ # D7: a test that gates execution on a GBRAIN_* opt-in the operator-env
+ # preload strips is a silent skip; TS AST scan, ~2s.
+ "check:test-env-opt-ins"
# ── light tail (sub-second greps; historical order) ──
"check:proposal-pii"
"check:jsonb"
diff --git a/test/agent-scheduler-contract.serial.test.ts b/test/agent-scheduler-contract.serial.test.ts
index df0316ef23..d2db195abe 100644
--- a/test/agent-scheduler-contract.serial.test.ts
+++ b/test/agent-scheduler-contract.serial.test.ts
@@ -31,7 +31,7 @@ import { spawnSync, execFileSync } from 'child_process';
const REPO = resolve(import.meta.dir, '..');
const CLI = join(REPO, 'src', 'cli.ts');
-const SKIP = process.env.GBRAIN_SKIP_SUBPROCESS_TESTS === '1';
+const SKIP = process.env.GBRAIN_TEST_SKIP_SUBPROCESS === '1';
interface ShellResult { exitCode: number; stdout: string; stderr: string }
diff --git a/test/apply-migrations-list-db-state.serial.test.ts b/test/apply-migrations-list-db-state.serial.test.ts
index 1762eaa3e7..9126d0e57c 100644
--- a/test/apply-migrations-list-db-state.serial.test.ts
+++ b/test/apply-migrations-list-db-state.serial.test.ts
@@ -6,7 +6,7 @@
* indistinguishable to operators and CI gates.
*
* Serial because it spawns a subprocess and writes a tmpdir. Skippable via
- * `GBRAIN_SKIP_SUBPROCESS_TESTS=1` for fast-loop budget control.
+ * `GBRAIN_TEST_SKIP_SUBPROCESS=1` for fast-loop budget control.
*/
import { describe, test, expect } from 'bun:test';
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
@@ -14,7 +14,7 @@ import { join } from 'path';
import { tmpdir } from 'os';
const REPO = new URL('..', import.meta.url).pathname.replace(/\/$/, '');
-const SKIP = process.env.GBRAIN_SKIP_SUBPROCESS_TESTS === '1';
+const SKIP = process.env.GBRAIN_TEST_SKIP_SUBPROCESS === '1';
async function runCli(
args: string[],
diff --git a/test/autopilot-launchd-lifecycle.serial.test.ts b/test/autopilot-launchd-lifecycle.serial.test.ts
index f5ae7d92f6..4d57729d7e 100644
--- a/test/autopilot-launchd-lifecycle.serial.test.ts
+++ b/test/autopilot-launchd-lifecycle.serial.test.ts
@@ -30,7 +30,7 @@
* shell or stalls can eat the wrapper. The marker path and label are baked as
* absolute strings at install time so they cannot be misrouted; if the poll
* times out, the failure dump names this vector. Escape hatch:
- * GBRAIN_SKIP_LAUNCHD_E2E=1.
+ * GBRAIN_TEST_SKIP_LAUNCHD=1.
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync, chmodSync } from 'fs';
@@ -42,7 +42,7 @@ import { autopilotLaunchdLabel } from '../src/core/autopilot-paths.ts';
const REPO = resolve(import.meta.dir, '..');
const CLI = join(REPO, 'src', 'cli.ts');
-const SKIP_SUBPROCESS = process.env.GBRAIN_SKIP_SUBPROCESS_TESTS === '1';
+const SKIP_SUBPROCESS = process.env.GBRAIN_TEST_SKIP_SUBPROCESS === '1';
// ── label seam unit tests (serial file on purpose: env mutation would
// interleave with other autopilot tests in the parallel lane) ─────────────
@@ -278,15 +278,15 @@ describe.skipIf(SKIP_SUBPROCESS)('autopilot launchd lifecycle — shimmed (all p
function canUseLaunchd(): boolean {
if (process.platform !== 'darwin') return false;
- if (process.env.GBRAIN_SKIP_LAUNCHD_E2E === '1') return false;
+ if (process.env.GBRAIN_TEST_SKIP_LAUNCHD === '1') return false;
if (typeof process.getuid !== 'function') return false;
const probe = spawnSync('launchctl', ['print', `gui/${process.getuid()}`], { encoding: 'utf8', timeout: 10_000 });
return probe.status === 0;
}
const LAUNCHD_OK = canUseLaunchd();
-if (!LAUNCHD_OK && process.env.GBRAIN_REQUIRE_LAUNCHD === '1') {
- throw new Error('[autopilot-launchd-lifecycle] GBRAIN_REQUIRE_LAUNCHD=1 but the launchd GUI domain is unavailable');
+if (!LAUNCHD_OK && process.env.GBRAIN_TEST_REQUIRE_LAUNCHD === '1') {
+ throw new Error('[autopilot-launchd-lifecycle] GBRAIN_TEST_REQUIRE_LAUNCHD=1 but the launchd GUI domain is unavailable');
}
describe.skipIf(SKIP_SUBPROCESS || !LAUNCHD_OK)('autopilot launchd lifecycle — REAL launchd (darwin)', () => {
@@ -357,7 +357,7 @@ describe.skipIf(SKIP_SUBPROCESS || !LAUNCHD_OK)('autopilot launchd lifecycle —
throw new Error(
`wrapper never ran under launchd within 30s.\n`
+ `Likely: a dotfile in the REAL user zshenv/zshrc exec'd another shell or stalled `
- + `(launchd runs the wrapper with your real HOME). Escape hatch: GBRAIN_SKIP_LAUNCHD_E2E=1.\n`
+ + `(launchd runs the wrapper with your real HOME). Escape hatch: GBRAIN_TEST_SKIP_LAUNCHD=1.\n`
+ `launchctl print (exit ${p.status}):\n${(p.stdout || p.stderr).slice(0, 1500)}`,
);
}
diff --git a/test/binary-self-update-compiled.serial.test.ts b/test/binary-self-update-compiled.serial.test.ts
index dc63165a43..6755dfcffe 100644
--- a/test/binary-self-update-compiled.serial.test.ts
+++ b/test/binary-self-update-compiled.serial.test.ts
@@ -4,9 +4,8 @@
* node:crypto + base64 + JSON (the dependency-free verify primitives) survive
* compilation — the exact thing that would break had we used `sigstore-js`.
*
- * Opt-in: compiling is slow (~seconds) and writes a large temp binary, so this
- * is skipped unless GBRAIN_SELFUPDATE_COMPILE_SMOKE=1 (run it locally / in a
- * heavy-test lane, not the hot unit path). Mirrors the repo's e2e gating.
+ * Runs unconditionally in the serial lane: the harness bundles a handful of
+ * modules, so the compile takes well under a second.
*/
import { describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
@@ -14,10 +13,9 @@ import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-const RUN = process.env.GBRAIN_SELFUPDATE_COMPILE_SMOKE === '1';
const HARNESS = join(import.meta.dir, 'helpers', 'binary-self-update-smoke-harness.ts');
-describe.skipIf(!RUN)('binary-self-update integrity verify — compiled binary (offline)', () => {
+describe('binary-self-update integrity verify — compiled binary (offline)', () => {
test('real crypto + base64 + JSON verify path runs under bun build --compile', () => {
const dir = mkdtempSync(join(tmpdir(), 'gbrain-smoke-build-'));
const out = join(dir, 'smoke-harness');
diff --git a/test/doctor-cli-smoke.serial.test.ts b/test/doctor-cli-smoke.serial.test.ts
index ae5bd21296..fc453525bc 100644
--- a/test/doctor-cli-smoke.serial.test.ts
+++ b/test/doctor-cli-smoke.serial.test.ts
@@ -13,7 +13,7 @@
* the documented values, checks array is non-empty.
*
* Serial because it spawns subprocesses and writes a tmpdir. Skippable
- * via `GBRAIN_SKIP_SUBPROCESS_TESTS=1` for fast-loop budget control.
+ * via `GBRAIN_TEST_SKIP_SUBPROCESS=1` for fast-loop budget control.
*
* Per-spawn cold-start on CI is ~10-20s. Single test, single brain.
*/
@@ -23,7 +23,7 @@ import { join } from 'path';
import { tmpdir } from 'os';
const REPO = new URL('..', import.meta.url).pathname.replace(/\/$/, '');
-const SKIP = process.env.GBRAIN_SKIP_SUBPROCESS_TESTS === '1';
+const SKIP = process.env.GBRAIN_TEST_SKIP_SUBPROCESS === '1';
function makeGbrainShim(): { binDir: string; cleanup: () => void } {
const binDir = mkdtempSync(join(tmpdir(), 'gbrain-shim-doctor-'));
diff --git a/test/doctor-no-migrate.serial.test.ts b/test/doctor-no-migrate.serial.test.ts
index 408e030c34..9b9b92702d 100644
--- a/test/doctor-no-migrate.serial.test.ts
+++ b/test/doctor-no-migrate.serial.test.ts
@@ -11,7 +11,7 @@
* tryRunPendingMigrations built the full schema.
*
* Serial because it spawns a subprocess and writes a tmpdir. Skippable via
- * `GBRAIN_SKIP_SUBPROCESS_TESTS=1` for fast-loop budget control.
+ * `GBRAIN_TEST_SKIP_SUBPROCESS=1` for fast-loop budget control.
*/
import { describe, test, expect } from 'bun:test';
import { PGlite } from '@electric-sql/pglite';
@@ -22,7 +22,7 @@ import { join } from 'path';
import { tmpdir } from 'os';
const REPO = new URL('..', import.meta.url).pathname.replace(/\/$/, '');
-const SKIP = process.env.GBRAIN_SKIP_SUBPROCESS_TESTS === '1';
+const SKIP = process.env.GBRAIN_TEST_SKIP_SUBPROCESS === '1';
async function runCli(
args: string[],
diff --git a/test/dream-keyless-exit.test.ts b/test/dream-keyless-exit.test.ts
index 4ca1f33495..f565256e06 100644
--- a/test/dream-keyless-exit.test.ts
+++ b/test/dream-keyless-exit.test.ts
@@ -40,7 +40,7 @@ import { spawnSync, execFileSync } from 'child_process';
const REPO = resolve(import.meta.dir, '..');
const CLI = join(REPO, 'src', 'cli.ts');
-const SKIP = process.env.GBRAIN_SKIP_SUBPROCESS_TESTS === '1';
+const SKIP = process.env.GBRAIN_TEST_SKIP_SUBPROCESS === '1';
interface PhaseResultish {
phase: string;
diff --git a/test/e2e/bootstrap-compiled-binary.serial.test.ts b/test/e2e/bootstrap-compiled-binary.serial.test.ts
index 515a2e9924..40cab29c91 100644
--- a/test/e2e/bootstrap-compiled-binary.serial.test.ts
+++ b/test/e2e/bootstrap-compiled-binary.serial.test.ts
@@ -50,11 +50,11 @@ let buildFailReason = '';
built = true;
}
if (!built) {
- // On CI (or wherever GBRAIN_REQUIRE_COMPILE=1 is set) a failed compile
+ // On CI (or wherever GBRAIN_TEST_REQUIRE_COMPILE=1 is set) a failed compile
// must be a loud red — skipIf(!built) would otherwise become a PERMANENT
// silent skip the moment `bun build --compile` breaks. Dev boxes keep
// the graceful skip.
- if (process.env.GITHUB_ACTIONS || process.env.GBRAIN_REQUIRE_COMPILE === '1') {
+ if (process.env.GITHUB_ACTIONS || process.env.GBRAIN_TEST_REQUIRE_COMPILE === '1') {
throw new Error(`[bootstrap-compiled-binary] compile is required in this environment but failed: ${buildFailReason}`);
}
console.error(`[bootstrap-compiled-binary] SKIPPING: ${buildFailReason}`);
diff --git a/test/entity-card-perf.slow.test.ts b/test/entity-card-perf.slow.test.ts
index 9966dc2b21..3336a38aad 100644
--- a/test/entity-card-perf.slow.test.ts
+++ b/test/entity-card-perf.slow.test.ts
@@ -8,7 +8,7 @@
* three resolution arms (alias hit / exact title / slug-suffix) + misses.
*
* Two gates:
- * 1. HARD ABSOLUTE — p99 < 100ms × GBRAIN_PERF_BUDGET_MULTIPLIER (default 1;
+ * 1. HARD ABSOLUTE — p99 < 100ms × GBRAIN_TEST_PERF_BUDGET_MULTIPLIER (default 1;
* loosen in CI only with evidence of runner noise). The protocol DOC
* promises this number; the bound is op-layer latency (transport
* excluded, as documented).
@@ -58,10 +58,10 @@ const WARMUP = 20;
const MEASURED = 200;
const TARGET_ENTITIES = 50; // pages the measured calls rotate over
-const P99_BUDGET_MS = 100 * (Number(process.env.GBRAIN_PERF_BUDGET_MULTIPLIER) || 1);
+const P99_BUDGET_MS = 100 * (Number(process.env.GBRAIN_TEST_PERF_BUDGET_MULTIPLIER) || 1);
// v0.45.7 boundary verbs — MEMORY_VERBS_v1.md promises "zero-LLM, sub-second"
// for context_pack and delta; same multiplier convention as the entity gate.
-const BOUNDARY_P99_BUDGET_MS = 1000 * (Number(process.env.GBRAIN_PERF_BUDGET_MULTIPLIER) || 1);
+const BOUNDARY_P99_BUDGET_MS = 1000 * (Number(process.env.GBRAIN_TEST_PERF_BUDGET_MULTIPLIER) || 1);
const BOUNDARY_WARMUP = 10;
const BOUNDARY_MEASURED = 100; // p99 index 98 — second-largest, not the raw max
const DELTA_CHANGED_PAGES = 150; // realistic heartbeat slice (spec: ~50-200 changed)
diff --git a/test/fixtures/guards/check-test-env-opt-ins.ts/bad-derived/test/opt-in-const.ts b/test/fixtures/guards/check-test-env-opt-ins.ts/bad-derived/test/opt-in-const.ts
new file mode 100644
index 0000000000..9238831f44
--- /dev/null
+++ b/test/fixtures/guards/check-test-env-opt-ins.ts/bad-derived/test/opt-in-const.ts
@@ -0,0 +1,10 @@
+import { describe, test } from 'bun:test';
+
+// The same dead opt-in through a top-level constant and an early return.
+const SKIP = process.env.GBRAIN_FIXTURE_SKIP_SUBPROCESS === '1';
+
+describe('subprocess', () => {
+ test('spawns', () => {
+ if (SKIP) return;
+ });
+});
diff --git a/test/fixtures/guards/check-test-env-opt-ins.ts/bad/test/opt-in-gate.ts b/test/fixtures/guards/check-test-env-opt-ins.ts/bad/test/opt-in-gate.ts
new file mode 100644
index 0000000000..47d6490b4c
--- /dev/null
+++ b/test/fixtures/guards/check-test-env-opt-ins.ts/bad/test/opt-in-gate.ts
@@ -0,0 +1,7 @@
+import { describe, test } from 'bun:test';
+
+// A stripped GBRAIN_* opt-in read straight in describe.skipIf: the preload
+// deletes it, so the suite can never run.
+describe.skipIf(!process.env.GBRAIN_FIXTURE_COMPILE_SMOKE)('compiled smoke', () => {
+ test('runs', () => {});
+});
diff --git a/test/fixtures/guards/check-test-env-opt-ins.ts/good/src/setting.ts b/test/fixtures/guards/check-test-env-opt-ins.ts/good/src/setting.ts
new file mode 100644
index 0000000000..83a61da4b2
--- /dev/null
+++ b/test/fixtures/guards/check-test-env-opt-ins.ts/good/src/setting.ts
@@ -0,0 +1 @@
+export const escapeHatch = process.env.GBRAIN_FIXTURE_PRODUCT_SETTING === '1';
diff --git a/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/opt-in-ok.ts b/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/opt-in-ok.ts
new file mode 100644
index 0000000000..ee85ee452a
--- /dev/null
+++ b/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/opt-in-ok.ts
@@ -0,0 +1,17 @@
+import { describe, test } from 'bun:test';
+
+// GBRAIN_TEST_* survives the scrub.
+describe.skipIf(!process.env.GBRAIN_TEST_FIXTURE_COMPILE_SMOKE)('compiled smoke', () => {
+ test('runs', () => {});
+});
+
+// A file that sets the name itself may gate on it.
+process.env.GBRAIN_FIXTURE_SELF_SET = '1';
+if (process.env.GBRAIN_FIXTURE_SELF_SET !== '1') throw new Error('unreachable');
+
+// A product setting (read in src/) asserted absent is hermeticity, not an opt-in.
+if (process.env.GBRAIN_FIXTURE_PRODUCT_SETTING === '1') throw new Error('product escape hatch is on');
+
+// Non-gating reads are out of scope.
+const budget = 100 * (Number(process.env.GBRAIN_FIXTURE_MULTIPLIER) || 1);
+export { budget };
diff --git a/test/helpers/operator-env-policy.ts b/test/helpers/operator-env-policy.ts
new file mode 100644
index 0000000000..e493c02a00
--- /dev/null
+++ b/test/helpers/operator-env-policy.ts
@@ -0,0 +1,78 @@
+/**
+ * The operator-env scrub policy, shared by test/helpers/operator-env-preload.ts
+ * (which applies it before any test file loads) and
+ * scripts/check-test-env-opt-ins.ts (which fails on a test that gates
+ * execution on a GBRAIN_* name this policy strips). Side-effect free.
+ *
+ * Naming rule for test opt-ins: `GBRAIN_TEST_<AREA>_<WHAT>`; paid ones
+ * `GBRAIN_TEST_LIVE_<WHAT>`. The `GBRAIN_TEST_` prefix survives the scrub, so a
+ * test opt-in under it can never be silently stripped. Documented exceptions
+ * kept for compatibility: the `GBRAIN_REAL_*`, `GBRAIN_E2E_*`, `GBRAIN_CI_*`
+ * prefixes and the two `*_LIVE*` exact rows below.
+ */
+
+/** Operator/agent workspace prefixes with no test-machinery tenants. */
+export const STRIP_PREFIX = /^(CONDUCTOR_|MCP_|OPENCLAW_)/;
+
+export const KEEP_EXACT: ReadonlySet<string> = new Set([
+ 'GBRAIN_HOME', // per-run HOME isolation — gbrain-home-preload and run-e2e.sh both respect a pre-set value
+ 'GBRAIN_DATABASE_URL', // e2e DB target; database-url-guard-preload (registered first) already vetoed un-opted runs
+ 'GBRAIN_MODEL_DISCOVERY', // operator override provider-keys-preload deliberately respects
+ 'GBRAIN_PGLITE_SNAPSHOT', // schema-snapshot fast path exported by every unit runner (scripts/lib/test-env.sh)
+ 'GBRAIN_NO_SNAPSHOT', // cold-path opt-out must survive this preload and reach CLI children
+ 'GBRAIN_PGBOUNCER_URL', // explicit pooled test target supplied by ci-local
+ 'GBRAIN_PGBOUNCER_DIRECT_URL', // admin connection used to create the isolated pooler test DB
+ 'GBRAIN_COMPILED_BIN', // heavy-lane compile-once binary (agent-harness.ts ensureCompiledGbrain)
+ 'GBRAIN_AUDIT_DIR', // audit-dir-preload honors a wrapper pre-set (inspect audit output after a run)
+ 'GBRAIN_SYNC_FAILURES_DIR', // same wrapper pre-set contract in sync-failures-preload
+ 'GBRAIN_DEBUG_PRELOAD', // the preload stack's own logging hatch
+ // Documented exception to the GBRAIN_TEST_LIVE_* rule: paid live layer of
+ // cycle-synthesize-triage-calibration.
+ 'GBRAIN_TRIAGE_CALIBRATION_LIVE',
+ // Documented exception: opt-in keyed System One wire test
+ // (test/live/decide-typesafe.live.test.ts).
+ 'GBRAIN_LIVE_TYPESAFE',
+]);
+
+// GBRAIN_TEST_*: test-control opt-ins (ALLOW_DATABASE_URL, KEEP_PROVIDER_KEYS,
+// shard/memory knobs) must survive their own scrub or every escape hatch is a
+// dead end. GBRAIN_CI_*: ci-local.sh port plumbing. GBRAIN_E2E_*: db-guard's
+// name-floor opt-in (its error message tells operators to set it) + e2e
+// runner knobs. GBRAIN_REAL_*: heavy-lane real-agent door-suite opt-ins read
+// in-process by test/e2e/install-real-*.serial.test.ts.
+export const KEEP_PREFIX = /^GBRAIN_(TEST_|CI_|E2E_|REAL_)/;
+
+/**
+ * Test opt-ins renamed into the GBRAIN_TEST_ namespace. Under their old names
+ * the scrub deleted them before any test read them, so every opt-in below was
+ * a silent no-op. Setting an old name now stops the run with the rename line
+ * instead of skipping silently. Shell readers (scripts/check-bash32.sh) carry
+ * the same check for the names they read.
+ */
+export const RENAMED: Readonly<Record<string, string>> = {
+ GBRAIN_BASH32_REQUIRE: 'GBRAIN_TEST_BASH32_REQUIRE',
+ GBRAIN_PERF_BUDGET_MULTIPLIER: 'GBRAIN_TEST_PERF_BUDGET_MULTIPLIER',
+ GBRAIN_SKIP_SUBPROCESS_TESTS: 'GBRAIN_TEST_SKIP_SUBPROCESS',
+ GBRAIN_REQUIRE_LAUNCHD: 'GBRAIN_TEST_REQUIRE_LAUNCHD',
+ GBRAIN_SKIP_LAUNCHD_E2E: 'GBRAIN_TEST_SKIP_LAUNCHD',
+ GBRAIN_ENFORCE_E5_BUDGET: 'GBRAIN_TEST_ENFORCE_E5_BUDGET',
+ GBRAIN_REQUIRE_COMPILE: 'GBRAIN_TEST_REQUIRE_COMPILE',
+};
+
+/** Whether the scrub deletes `name` from a test process's environment. */
+export function isStripped(name: string): boolean {
+ if (STRIP_PREFIX.test(name)) return true;
+ return name.startsWith('GBRAIN_') && !KEEP_EXACT.has(name) && !KEEP_PREFIX.test(name);
+}
+
+/** The fail-fast message for an old opt-in name, or null when `name` was not renamed. */
+export function renamedOptInMessage(name: string, value: string): string | null {
+ const next = RENAMED[name];
+ if (!next) return null;
+ return [
+ `${name} was renamed to ${next}.`,
+ 'Why: test opt-ins must survive the operator-env scrub (test/helpers/operator-env-preload.ts), which deletes GBRAIN_* names outside GBRAIN_TEST_*; under the old name this opt-in was silently ignored.',
+ `Fix: unset ${name} && export ${next}=${value}`,
+ 'Docs: docs/TESTING.md#test-isolation-lint-and-helpers',
+ ].join('\n');
+}
diff --git a/test/helpers/operator-env-preload.ts b/test/helpers/operator-env-preload.ts
index 5561a65b69..c19cbc65c5 100644
--- a/test/helpers/operator-env-preload.ts
+++ b/test/helpers/operator-env-preload.ts
@@ -29,50 +29,33 @@
* A blanket GBRAIN_* delete would break that machinery — e.g. the e2e lane's
* GBRAIN_DATABASE_URL target or the snapshot fast path.
*
+ * The keep-lists, the renamed-opt-in map and the naming rule for test opt-ins
+ * live in ./operator-env-policy.ts, shared with
+ * scripts/check-test-env-opt-ins.ts.
+ *
* Escape hatch: GBRAIN_TEST_KEEP_AMBIENT_ENV=1 disables the scrub entirely
* (it lives under GBRAIN_TEST_, so it survives its own scrub). Debugging:
* GBRAIN_DEBUG_PRELOAD=1 logs the removed NAMES — never values, which may be
* secrets.
*/
-/** Operator/agent workspace prefixes with no test-machinery tenants. */
-const STRIP_PREFIX = /^(CONDUCTOR_|MCP_|OPENCLAW_)/;
-
-const KEEP_EXACT = new Set([
- 'GBRAIN_HOME', // per-run HOME isolation — gbrain-home-preload and run-e2e.sh both respect a pre-set value
- 'GBRAIN_DATABASE_URL', // e2e DB target; database-url-guard-preload (registered first) already vetoed un-opted runs
- 'GBRAIN_MODEL_DISCOVERY', // operator override provider-keys-preload deliberately respects
- 'GBRAIN_PGLITE_SNAPSHOT', // schema-snapshot fast path exported by every unit runner (scripts/lib/test-env.sh)
- 'GBRAIN_NO_SNAPSHOT', // cold-path opt-out must survive this preload and reach CLI children
- 'GBRAIN_PGBOUNCER_URL', // explicit pooled test target supplied by ci-local
- 'GBRAIN_PGBOUNCER_DIRECT_URL', // admin connection used to create the isolated pooler test DB
- 'GBRAIN_COMPILED_BIN', // heavy-lane compile-once binary (agent-harness.ts ensureCompiledGbrain)
- 'GBRAIN_AUDIT_DIR', // audit-dir-preload honors a wrapper pre-set (inspect audit output after a run)
- 'GBRAIN_SYNC_FAILURES_DIR', // same wrapper pre-set contract in sync-failures-preload
- 'GBRAIN_DEBUG_PRELOAD', // the preload stack's own logging hatch
- // Test-control opt-in documented in cycle-synthesize-triage-calibration's
- // header — the scrub was silently no-op'ing the paid live layer (any
- // GBRAIN_* opt-in read by a test file needs a row here or a KEEP_PREFIX).
- 'GBRAIN_TRIAGE_CALIBRATION_LIVE',
- // Opt-in keyed System One wire test (test/live/decide-typesafe.live.test.ts).
- 'GBRAIN_LIVE_TYPESAFE',
-]);
+import { isStripped, renamedOptInMessage } from './operator-env-policy';
-// GBRAIN_TEST_*: test-control opt-ins (ALLOW_DATABASE_URL, KEEP_PROVIDER_KEYS,
-// shard/memory knobs) must survive their own scrub or every escape hatch is a
-// dead end. GBRAIN_CI_*: ci-local.sh port plumbing. GBRAIN_E2E_*: db-guard's
-// name-floor opt-in (its error message tells operators to set it) + e2e
-// runner knobs. GBRAIN_REAL_*: heavy-lane real-agent door-suite opt-ins read
-// in-process by test/e2e/install-real-*.serial.test.ts.
-const KEEP_PREFIX = /^GBRAIN_(TEST_|CI_|E2E_|REAL_)/;
+// Old opt-in names fail fast BEFORE the scrub (and regardless of
+// GBRAIN_TEST_KEEP_AMBIENT_ENV): the scrub would otherwise delete them and the
+// gated tests would skip silently.
+for (const [name, value] of Object.entries(process.env)) {
+ if (value === undefined || value === '') continue;
+ const message = renamedOptInMessage(name, value);
+ if (!message) continue;
+ console.error(`[operator-env-preload] ${message}`);
+ process.exit(2);
+}
if (process.env.GBRAIN_TEST_KEEP_AMBIENT_ENV !== '1') {
const removed: string[] = [];
for (const name of Object.keys(process.env)) {
- const strip =
- STRIP_PREFIX.test(name) ||
- (name.startsWith('GBRAIN_') && !KEEP_EXACT.has(name) && !KEEP_PREFIX.test(name));
- if (!strip) continue;
+ if (!isStripped(name)) continue;
delete process.env[name];
removed.push(name);
}
diff --git a/test/operator-env-preload.test.ts b/test/operator-env-preload.test.ts
index f4bac391ab..4c681a1304 100644
--- a/test/operator-env-preload.test.ts
+++ b/test/operator-env-preload.test.ts
@@ -173,6 +173,31 @@ describe('operator-env-preload (#4023)', () => {
expect(r.report.GBRAIN_SOURCE).toBe('default');
}, 30_000);
+ test('a renamed test opt-in set under its old name stops the run with the rename line', () => {
+ // Under the old names the scrub deleted these before any test read them,
+ // so the gated tests skipped silently (D7). The preload now exits first.
+ for (const [old, next] of [
+ ['GBRAIN_SKIP_SUBPROCESS_TESTS', 'GBRAIN_TEST_SKIP_SUBPROCESS'],
+ ['GBRAIN_BASH32_REQUIRE', 'GBRAIN_TEST_BASH32_REQUIRE'],
+ ]) {
+ // Also with the scrub disabled: the old-name check runs before it.
+ const r = runProbe({ [old]: '1', GBRAIN_TEST_KEEP_AMBIENT_ENV: '1' }, [old]);
+ expect(r.exitCode).toBe(2);
+ expect(r.stderr).toContain(`${old} was renamed to ${next}.`);
+ expect(r.stderr).toContain(`Fix: unset ${old} && export ${next}=1`);
+ expect(r.stderr).toContain('Docs: docs/TESTING.md#test-isolation-lint-and-helpers');
+ expect(r.report).toEqual({});
+ }
+ }, 60_000);
+
+ test('the new opt-in names survive the scrub', () => {
+ const probed = ['GBRAIN_TEST_SKIP_SUBPROCESS', 'GBRAIN_TEST_BASH32_REQUIRE', 'GBRAIN_TEST_PERF_BUDGET_MULTIPLIER'];
+ const ambient = { GBRAIN_TEST_SKIP_SUBPROCESS: '1', GBRAIN_TEST_BASH32_REQUIRE: '1', GBRAIN_TEST_PERF_BUDGET_MULTIPLIER: '3' };
+ const r = runProbe(ambient, probed);
+ expect(r.exitCode).toBe(0);
+ expect(r.report).toEqual(ambient);
+ }, 30_000);
+
test('GBRAIN_DEBUG_PRELOAD=1 logs removed names, never values', () => {
const r = runProbe(
{ GBRAIN_SOURCE: 'hunter2-not-for-logs', GBRAIN_DEBUG_PRELOAD: '1' },
diff --git a/test/scripts/check-bash32.test.ts b/test/scripts/check-bash32.test.ts
index 169e5a8f66..0fac8acc7c 100644
--- a/test/scripts/check-bash32.test.ts
+++ b/test/scripts/check-bash32.test.ts
@@ -7,12 +7,12 @@
* Fails when: the real 3.2 parser stops flagging the #5810 shape, a guard
* fixture leaks into the scan, a failure loses its FAIL file:line / Why / Fix
* / See lines, or a missing parser stops being a one-line skip (exit 2 under
- * GBRAIN_BASH32_REQUIRE=1).
+ * GBRAIN_TEST_BASH32_REQUIRE=1).
* Seams: GBRAIN_GUARD_ROOT (fixture tree), GBRAIN_BASH32 (parser binary; a
* shim here), GBRAIN_BASH32_DOCKER (docker CLI). The real-parser cases run
* when bash 3.2 is reachable without a network pull (stock /bin/bash, or the
* pinned image already present) and are mandatory under
- * GBRAIN_BASH32_REQUIRE=1, which the CI step sets.
+ * GBRAIN_TEST_BASH32_REQUIRE=1, which the CI step sets.
*/
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { spawnSync } from 'node:child_process';
@@ -55,7 +55,7 @@ exit 0
function run(guardRoot: string, env: Record<string, string> = {}) {
return spawnSync('bash', [SCRIPT], {
encoding: 'utf8',
- env: { ...process.env, GBRAIN_BASH32: '', GBRAIN_BASH32_REQUIRE: '', GBRAIN_GUARD_ROOT: guardRoot, ...env },
+ env: { ...process.env, GBRAIN_BASH32: '', GBRAIN_BASH32_REQUIRE: '', GBRAIN_TEST_BASH32_REQUIRE: '', GBRAIN_GUARD_ROOT: guardRoot, ...env },
});
}
@@ -97,14 +97,22 @@ describe('check-bash32.sh reporting (parser shim)', () => {
expect(skipped.stdout.trim().split('\n')).toEqual([
'- bash 3.2 parse: skipped (no bash 3.x at /bin/bash and no docker CLI; install Docker or set GBRAIN_BASH32 to a bash 3.2 binary)',
]);
- const required = run(join(root, 'tree'), { ...noDocker, GBRAIN_BASH32_REQUIRE: '1' });
+ const required = run(join(root, 'tree'), { ...noDocker, GBRAIN_TEST_BASH32_REQUIRE: '1' });
expect(required.status).toBe(2);
- expect(required.stderr).toContain('GBRAIN_BASH32_REQUIRE=1 forbids skipping');
+ expect(required.stderr).toContain('GBRAIN_TEST_BASH32_REQUIRE=1 forbids skipping');
+ });
+
+ it('refuses the pre-rename GBRAIN_BASH32_REQUIRE with the rename line instead of ignoring it', () => {
+ write('tree/a.sh', 'echo a\n');
+ const r = run(join(root, 'tree'), { GBRAIN_BASH32: shim(), GBRAIN_BASH32_REQUIRE: '1' });
+ expect(r.status).toBe(2);
+ expect(r.stderr).toContain('GBRAIN_BASH32_REQUIRE was renamed to GBRAIN_TEST_BASH32_REQUIRE');
+ expect(r.stderr).toContain('Fix: unset GBRAIN_BASH32_REQUIRE && export GBRAIN_TEST_BASH32_REQUIRE=1');
});
});
function realParserReachable(): boolean {
- if (process.env.GBRAIN_BASH32_REQUIRE === '1') return true;
+ if (process.env.GBRAIN_TEST_BASH32_REQUIRE === '1') return true;
const native = spawnSync('/bin/bash', ['-c', 'echo "${BASH_VERSINFO[0]}"'], { encoding: 'utf8' });
if (native.stdout?.trim() === '3') return true;
return spawnSync('docker', ['image', 'inspect', IMAGE], { stdio: 'ignore' }).status === 0;
diff --git a/test/scripts/test-env-opt-ins-guard.test.ts b/test/scripts/test-env-opt-ins-guard.test.ts
new file mode 100644
index 0000000000..683191e81a
--- /dev/null
+++ b/test/scripts/test-env-opt-ins-guard.test.ts
@@ -0,0 +1,45 @@
+/**
+ * scripts/check-test-env-opt-ins.ts (D7): a test gating execution on a
+ * GBRAIN_* opt-in the operator-env preload strips is a silent skip. The
+ * guard-self-test harness proves the bad fixtures fail and the good one
+ * passes; this file pins the agent-facing output (Why / Fix / Docs, with an
+ * anchor that exists) and that the real tree is clean.
+ */
+import { describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+
+const REPO = resolve(import.meta.dir, '..', '..');
+const GUARD = join(REPO, 'scripts', 'check-test-env-opt-ins.ts');
+const FIXTURES = join(REPO, 'test', 'fixtures', 'guards', 'check-test-env-opt-ins.ts');
+
+function run(root?: string) {
+ return spawnSync('bun', [GUARD], {
+ encoding: 'utf8',
+ env: { ...process.env, ...(root ? { GBRAIN_GUARD_ROOT: root } : {}) },
+ });
+}
+
+describe('check-test-env-opt-ins', () => {
+ test('names each dead gate with file:line and prints Why / Fix / Docs', () => {
+ const r = run(join(FIXTURES, 'bad-derived'));
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('FAIL [test_env_opt_in_stripped]: test/opt-in-const.ts:4 gates execution on GBRAIN_FIXTURE_SKIP_SUBPROCESS');
+ expect(r.stderr).toMatch(/^Why: .*operator-env-preload\.ts strips every GBRAIN_\* name/m);
+ expect(r.stderr).toMatch(/^Fix: rename the opt-in to GBRAIN_TEST_<AREA>_<WHAT>.*RENAMED in test\/helpers\/operator-env-policy\.ts/m);
+ const anchor = r.stderr.match(/^Docs: docs\/TESTING\.md#([a-z0-9-]+)$/m)?.[1];
+ expect(anchor).toBeDefined();
+ const headings = readFileSync(join(REPO, 'docs', 'TESTING.md'), 'utf8')
+ .split('\n')
+ .filter(l => l.startsWith('#'))
+ .map(l => l.replace(/^#+\s*/, '').toLowerCase().replace(/[^a-z0-9 -]/g, '').replace(/ /g, '-'));
+ expect(headings).toContain(anchor!);
+ });
+
+ test('the real tree is clean', () => {
+ const r = run();
+ expect(r.stderr).toBe('');
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/test/truthful-catalog.e2e-lite.test.ts b/test/truthful-catalog.e2e-lite.test.ts
index 2a75b083aa..c79f2bc9e5 100644
--- a/test/truthful-catalog.e2e-lite.test.ts
+++ b/test/truthful-catalog.e2e-lite.test.ts
@@ -42,7 +42,7 @@
* (FOV-6c: exactly ONE warn-mode case below, probing a READ op only).
*
* Wall-clock budget: the whole file should finish in < 3 minutes (ENG-21).
- * The budget is ENFORCED only under GBRAIN_ENFORCE_E5_BUDGET=1 (a loaded CI
+ * The budget is ENFORCED only under GBRAIN_TEST_ENFORCE_E5_BUDGET=1 (a loaded CI
* shard or laptop makes wall-clock assertions flaky); otherwise an overrun
* warns loudly so drift is still visible.
*/
@@ -797,7 +797,7 @@ describe('E5 budget', () => {
`trim probe work or split cells before raising this budget.`;
// Machine load makes wall-clock assertions flaky — hard-fail only when
// the budget gate is explicitly armed (dedicated perf lane / local run).
- if (process.env.GBRAIN_ENFORCE_E5_BUDGET === '1') throw new Error(msg);
+ if (process.env.GBRAIN_TEST_ENFORCE_E5_BUDGET === '1') throw new Error(msg);
console.warn(msg);
}
});