Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
23.9 KB
Raw Blame
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';

const source = readFileSync(join(import.meta.dir, '../../scripts/ci-local.sh'), 'utf8');
const templateStart = source.indexOf("INNER_CMD=$(cat <<'EOF'");
const templateEnd = source.indexOf('\n# Conductor / git-worktree support:', templateStart);

test('the CI admin build keeps container dependencies and Vite cache off the host', () => {
  const compose = Bun.YAML.parse(readFileSync(join(import.meta.dir, '../../docker-compose.ci.yml'), 'utf8')) as {
    services: { runner: { volumes: string[] } };
    volumes: Record<string, unknown>;
  };
  expect(compose.services.runner.volumes).toContain('gbrain-ci-admin-node-modules:/app/admin/node_modules');
  expect(Object.hasOwn(compose.volumes, 'gbrain-ci-admin-node-modules')).toBe(true);
  expect(compose.services.runner.volumes).toContain('gbrain-ci-admin-dist:/app/admin/dist');
  expect(Object.hasOwn(compose.volumes, 'gbrain-ci-admin-dist')).toBe(true);
  // Compiled-CLI tests must run a Linux binary built in the container, never a
  // host (e.g. macOS) build leaking through the /app bind mount.
  expect(compose.services.runner.volumes).toContain('gbrain-ci-bin:/app/bin');
  expect(Object.hasOwn(compose.volumes, 'gbrain-ci-bin')).toBe(true);
});

test('the runner compiles its own CLI and avoids GNU-only xargs flags', () => {
  const template = source.slice(templateStart, templateEnd);
  // `xargs -a FILE` is GNU-only; BSD xargs (macOS hosts) rejects it.
  expect(source).not.toMatch(/xargs\s+-a\b/);
  const install = template.indexOf('bun install --frozen-lockfile');
  const build = template.indexOf('bun run build', install);
  expect(install).toBeGreaterThanOrEqual(0);
  expect(build).toBeGreaterThan(install);
  expect(build).toBeLessThan(template.indexOf('__RUN_PHASES__'));
});

describe('ci-local command rendering', () => {
  // Every tool the runner's prerequisite gate checks; curl backs check:vendor-postgres (#7765).
  const prerequisites = ['git', 'python3', 'ps', 'psql', 'cc', 'jq', 'curl'];
  const cases = [
    { phaseExit: 0, missingTool: '' },
    { phaseExit: 7, missingTool: '' },
    ...prerequisites.map(missingTool => ({ phaseExit: 0, missingTool })),
  ];
  for (const { phaseExit, missingTool } of cases) {
    test(`preserves stderr and exit ${phaseExit}; missing prerequisite ${missingTool || 'none'}`, () => {
      expect(templateStart).toBeGreaterThanOrEqual(0);
      expect(templateEnd).toBeGreaterThan(templateStart);
      const home = mkdtempSync(join(tmpdir(), 'gbrain-ci-render-'));
      try {
        const bin = join(home, 'bin');
        mkdirSync(bin);
        // Execute the actual runner template, with installation/configuration
        // commands stubbed so this regression needs neither Docker nor root.
        for (const name of ['bun', ...prerequisites]) {
          writeFileSync(join(bin, name), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
        }
        writeFileSync(join(bin, 'apt-get'), '#!/bin/sh\nprintf "%s\\n" "$*" >> "$INSTALL_LOG"\n', { mode: 0o755 });
        mkdirSync(join(home, 'scripts'));
        writeFileSync(join(home, 'scripts', 'ci-hydrate-admin-dist.sh'), 'exit 0\n');
        const phaseLog = join(home, 'phase.log');
        const installLog = join(home, 'install.log');
        const phases = [
          'printf "%s\\n" "literal & marker"',
          'sh -c \'printf "%s\\n" "phase stdout"; printf "%s\\n" "phase stderr" >&2; exit "$1"\' _ "$PHASE_EXIT" >> "$PHASE_LOG" 2>&1',
          'printf "%s\\n" "phase completed"',
        ].join('\n');
        const script = [
          // Exercise Bash 5.2's replacement semantics when available; older
          // macOS Bash still runs the same rendering and redirection checks.
          'shopt -s patsub_replacement 2>/dev/null || true',
          // Hide exactly one prerequisite, even on a fully provisioned host.
          'command() { if [ "$1" = "-v" ] && [ "${2:-}" = "$FIXTURE_MISSING_TOOL" ]; then return 1; fi; builtin command "$@"; }',
          'export -f command',
          source.slice(templateStart, templateEnd),
          'bash -c "$INNER_CMD"',
        ].join('\n');
        const result = spawnSync('bash', ['-c', script], {
          cwd: home, encoding: 'utf8', timeout: 5_000,
          env: {
            ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}`,
            RUN_PHASES_CMD: phases, PHASE_LOG: phaseLog, PHASE_EXIT: String(phaseExit),
            FIXTURE_MISSING_TOOL: missingTool, INSTALL_LOG: installLog,
          },
        });
        expect(result.status, result.stderr).toBe(phaseExit);
        expect(readFileSync(phaseLog, 'utf8')).toBe('phase stdout\nphase stderr\n');
        expect(result.stdout).toContain('literal & marker');
        expect(result.stdout.includes('phase completed')).toBe(phaseExit === 0);
        expect(existsSync(join(home, '__RUN_PHASES__1'))).toBe(false);
        if (missingTool) {
          expect(readFileSync(installLog, 'utf8')).toBe('update -qq\ninstall -y -qq git ca-certificates python3 procps postgresql-client jq curl build-essential\n');
        } else {
          expect(existsSync(installLog)).toBe(false);
        }
      } finally {
        rmSync(home, { recursive: true, force: true });
      }
    });
  }
});

function runPhases(noShard: boolean, diff: boolean, failStage = '') {
  const home = mkdtempSync(join(tmpdir(), 'gbrain-ci-phases-'));
  try {
    const bin = join(home, 'bin');
    mkdirSync(bin);
    mkdirSync(join(home, 'scripts'));
    const trace = join(home, 'trace');
    const put = (path: string, body: string) => writeFileSync(join(home, path), `#!/bin/bash\n${body}\n`, { mode: 0o755 });
    for (const name of ['git', 'python3', 'ps', 'psql', 'apt-get']) put(`bin/${name}`, 'exit 0');
    put('scripts/ci-hydrate-admin-dist.sh', 'exit 0');
    put('bin/bun', `
case "$*" in
  "scripts/lib/ensure-e2e-database.ts "*)
    printf 'admin_db:%s:%s\\n' "$2" "$3" >> "$TRACE"
    [ "$FAIL_STAGE" != admin_db ] || exit 7
    exit 0 ;;
  "run verify") stage=verify ;;
  "run test:serial") stage=serial ;;
  "run test:slow") stage=slow ;;
  *) exit 0 ;;
esac
printf '%s:%s\\n' "$stage" "\${DATABASE_URL-unset}" >> "$TRACE"
[ "$FAIL_STAGE" != "$stage" ] || exit 7
`);
    put('scripts/check-bun-test-timeout.sh', `
printf 'timeout_guard:%s\\n' "\${DATABASE_URL-unset}" >> "$TRACE"
[ "$FAIL_STAGE" != timeout_guard ] || exit 7
`);
    put('scripts/run-unit-shard.sh', `
printf 'unit:%s:%s\\n' "\${SHARD-all}" "\${DATABASE_URL-unset}" >> "$TRACE"
printf '%s\\n' 'early diagnostic retained beyond summary tail' >&2
for line in {1..35}; do printf 'fixture progress %s\\n' "$line"; done
[ -z "\${DATABASE_URL:-}" ] || exit 41
[ "$FAIL_STAGE" != unit ] || exit 7
`);
    put('scripts/run-e2e.sh', `
set -eu
case "$DATABASE_URL" in postgresql://postgres:postgres@postgres-*:5432/gbrain_test?sslmode=disable) ;; *) exit 42 ;; esac
[ "$GBRAIN_PGBOUNCER_URL" = 'postgresql://postgres:postgres@pgbouncer:5432/gbrain_pgbouncer_test?sslmode=disable' ] || exit 43
[ "$GBRAIN_PGBOUNCER_DIRECT_URL" = 'postgresql://postgres:postgres@postgres-1:5432/gbrain_ci_admin_test?sslmode=disable' ] || exit 44
[ "$GBRAIN_CI_REQUIRE_PGBOUNCER" = 1 ] || exit 45
[ "$GBRAIN_TEST_DB" = 1 ] || exit 46
printf 'target:%s\\n' "db=$DATABASE_URL" "pgbouncer=$GBRAIN_PGBOUNCER_URL" "direct=$GBRAIN_PGBOUNCER_DIRECT_URL" >> "$TRACE"
printf 'e2e:%s:%s\\n' "\${SHARD-all}" "$*" >> "$TRACE"
[ "$FAIL_STAGE" != e2e ] || exit 7
`);
    const start = source.indexOf('# Step 4: build the runner-side command.');
    expect(start).toBeGreaterThanOrEqual(0);
    const script = source.slice(start, templateEnd)
      .replaceAll('/tmp/shard-logs', join(home, 'shard-logs'))
      .replaceAll('/tmp/e2e-selected.txt', join(home, 'selected.txt'));
    const result = spawnSync('bash', ['-c', `${script}\nbash -c "$INNER_CMD"`], {
      cwd: home, encoding: 'utf8', timeout: 5_000,
      env: {
        ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}`, TRACE: trace,
        NO_SHARD: noShard ? '1' : '0', DIFF: diff ? '1' : '0', FAIL_STAGE: failStage,
        DATABASE_URL: 'ambient-fixture', GBRAIN_DATABASE_URL: 'ambient-fixture',
        GBRAIN_TEST_DB: 'ambient-must-be-overridden',
      },
    });
    const archivedLogs = [1, 2, 3, 4].map(shard => {
      const path = join(home, '.context/ci-local-shards', `shard-${shard}.log`);
      return existsSync(path) ? readFileSync(path, 'utf8') : '';
    });
    return { ...result, archivedLogs, trace: existsSync(trace) ? readFileSync(trace, 'utf8').trim().split('\n') : [] };
  } finally {
    rmSync(home, { recursive: true, force: true });
  }
}

describe('ci-local execution coverage', () => {
  for (const noShard of [false, true]) {
    for (const diff of [false, true]) {
      test(`serial and slow precede unit/E2E with live target forwarding (no-shard=${noShard}, diff=${diff})`, () => {
        const result = runPhases(noShard, diff);
        expect(result.status, result.stdout + result.stderr).toBe(0);
        expect(result.trace.slice(0, 4)).toEqual(['timeout_guard:ambient-fixture', 'verify:ambient-fixture', 'serial:unset', 'slow:unset']);
        const units = result.trace.filter(line => line.startsWith('unit:'));
        const e2e = result.trace.filter(line => line.startsWith('e2e:'));
        expect(units).toHaveLength(noShard ? 1 : 4);
        expect(units.every(line => line.endsWith(':unset'))).toBe(true);
        expect(e2e).toHaveLength(noShard ? 1 : 4);
        const targets = result.trace.filter(line => line.startsWith('target:'));
        expect(targets).toHaveLength(noShard ? 3 : 12);
        for (const target of targets) expect(() => assertSafeE2eDatabaseUrl(target.slice(target.indexOf('=') + 1), {})).not.toThrow();
        // --diff no longer narrows: every shard runs run-e2e.sh's full discovery.
        expect(e2e.every(line => line.endsWith(':'))).toBe(true);
        if (!noShard) {
          expect(result.stdout).toContain('Complete shard logs saved to .context/ci-local-shards/');
          for (const log of result.archivedLogs) {
            expect(log).toContain('early diagnostic retained beyond summary tail');
            expect(log).toContain('DONE');
          }
        }
      });
    }
  }

  for (const noShard of [false, true]) {
    test(`the PgBouncer admin database is created first and is no shard's database (#6674, no-shard=${noShard})`, () => {
      const result = runPhases(noShard, false);
      expect(result.status, result.stdout + result.stderr).toBe(0);
      // Shards run concurrently, so their target lines interleave: each line names its role.
      const role = (name: string) => result.trace.filter(line => line.startsWith(`target:${name}=`)).map(line => new URL(line.slice(line.indexOf('=') + 1)));
      const shards = role('db');
      expect(shards).toHaveLength(noShard ? 1 : 4);
      const admins = new Set(role('direct').map(url => `${url.host}${url.pathname}`));
      expect([...admins]).toEqual(['postgres-1:5432/gbrain_ci_admin_test']);
      for (const shard of shards) expect(shard.pathname).not.toBe('/gbrain_ci_admin_test');
      const created = result.trace.indexOf('admin_db:postgresql://postgres:postgres@postgres-1:5432/gbrain_test?sslmode=disable:gbrain_ci_admin_test');
      expect(created).toBeGreaterThanOrEqual(0);
      expect(created).toBeLessThan(result.trace.findIndex(line => line.startsWith('e2e:')));
    });
  }

  test('a failed admin database bootstrap starts no shard', () => {
    const result = runPhases(false, false, 'admin_db');
    expect(result.status).toBe(1);
    expect(result.stderr).toContain('could not create gbrain_ci_admin_test; shards not started');
    expect(result.trace.some(line => line.startsWith('unit:') || line.startsWith('e2e:'))).toBe(false);
  });

  for (const failStage of ['timeout_guard', 'verify', 'serial', 'slow', 'unit', 'e2e']) {
    test(`a failed ${failStage} stage cannot produce a green local CI result`, () => {
      const result = runPhases(false, false, failStage);
      expect(result.status).not.toBe(0);
      expect(result.stdout).not.toContain('All 4 shards passed');
      if (failStage !== 'e2e') expect(result.trace.some(line => line.startsWith('e2e:'))).toBe(false);
      if (['timeout_guard', 'verify', 'serial', 'slow'].includes(failStage)) {
        expect(result.status).toBe(7);
        expect(result.trace.some(line => line.startsWith('unit:'))).toBe(false);
        if (failStage === 'timeout_guard') expect(result.trace.some(line => line.startsWith('verify:'))).toBe(false);
      } else {
        for (const log of result.archivedLogs) {
          expect(log).toContain('early diagnostic retained beyond summary tail');
          expect(log).toContain(`${failStage.toUpperCase()} FAILED`);
        }
      }
    });
  }

  for (const gitleaks of ['missing', 'success', 'failure']) {
    test(`doc-only diff requires a successful gitleaks scan (${gitleaks})`, () => {
      const home = mkdtempSync(join(tmpdir(), 'gbrain-ci-docs-'));
      try {
        const bin = join(home, 'bin');
        mkdirSync(bin);
        mkdirSync(join(home, 'scripts'));
        writeFileSync(join(bin, 'bun'), '#!/bin/sh\necho DOC_ONLY\n', { mode: 0o755 });
        writeFileSync(join(bin, 'docker'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
        writeFileSync(join(bin, 'gitleaks'), '#!/bin/sh\nprintf "%s\\n" "$1" >> "$SCAN_LOG"\n[ "$SCAN_MODE" != failure ]\n', { mode: 0o755 });
        const end = source.indexOf('# Pre-flight: postgres host ports');
        const script = `command() { if [ "$1" = -v ] && [ "\${2:-}" = gitleaks ] && [ "$SCAN_MODE" = missing ]; then return 1; fi; builtin command "$@"; }\n${source.slice(0, end)}`;
        const log = join(home, 'scans');
        // Keep this branch-routing fixture focused on the scanner result;
        // the real detector/configuration canary runs separately in CI.
        writeFileSync(join(home, 'scripts/test-gitleaks-config.sh'), 'exit 0\n');
        writeFileSync(join(home, 'scripts/scan-worktree-secrets.sh'), 'gitleaks dir . --redact --no-banner\n');
        writeFileSync(join(home, 'scripts/ci-doc-checks.sh'), 'printf "%s\\n" docs >> "$SCAN_LOG"\n');
        const result = spawnSync('bash', ['-c', script, join(home, 'scripts/ci-local.sh'), '--diff'], {
          encoding: 'utf8', timeout: 5_000,
          env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, SCAN_MODE: gitleaks, SCAN_LOG: log },
        });
        expect(result.status, result.stderr).toBe(gitleaks === 'success' ? 0 : 1);
        const scans = existsSync(log) ? readFileSync(log, 'utf8') : '';
        expect(scans).toBe(gitleaks === 'success' ? 'dir\ngit\ndocs\n' : gitleaks === 'failure' ? 'dir\n' : '');
      } finally {
        rmSync(home, { recursive: true, force: true });
      }
    });
  }

  function diffPreflight(classification: string, docChecks = 'exit 0') {
    const home = mkdtempSync(join(tmpdir(), 'gbrain-ci-diff-'));
    try {
      const bin = join(home, 'bin');
      mkdirSync(bin);
      mkdirSync(join(home, 'scripts'));
      writeFileSync(join(bin, 'bun'), `#!/bin/sh\necho ${classification}\n`, { mode: 0o755 });
      writeFileSync(join(bin, 'docker'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
      writeFileSync(join(bin, 'gitleaks'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
      writeFileSync(join(home, 'scripts/test-gitleaks-config.sh'), 'exit 0\n');
      writeFileSync(join(home, 'scripts/scan-worktree-secrets.sh'), 'exit 0\n');
      writeFileSync(join(home, 'scripts/ci-doc-checks.sh'), `${docChecks}\n`);
      const end = source.indexOf('# Pre-flight: postgres host ports');
      return spawnSync('bash', ['-c', `${source.slice(0, end)}\necho FULL_GATE_CONTINUES`, join(home, 'scripts/ci-local.sh'), '--diff'], {
        encoding: 'utf8', timeout: 5_000, env: { ...process.env, PATH: `${bin}:${process.env.PATH}` },
      });
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  }

  test('doc-only diff fails when a doc check fails (e.g. llms.txt not rebuilt)', () => {
    const result = diffPreflight('DOC_ONLY', 'echo "Fix: bun run build:llms" >&2; exit 1');
    expect(result.status).toBe(1);
    expect(result.stderr).toContain('Fix: bun run build:llms');
    expect(result.stdout).not.toContain('FULL_GATE_CONTINUES');
  });

  for (const classification of ['SRC', 'EMPTY', 'ERR']) {
    test(`a ${classification} diff says narrowing is retired and runs the full gate`, () => {
      const result = diffPreflight(classification);
      expect(result.status, result.stderr).toBe(0);
      expect(result.stdout).toContain('E2E narrowing is retired; running the full E2E corpus (see docs/TESTING.md#e2e-selection)');
      expect(result.stdout).toContain('FULL_GATE_CONTINUES');
    });
  }
});

describe('required PgBouncer execution through run-e2e', () => {
  for (const [required, passes, testExit, expectedExit, parentCoverageExists, outputBytes = 0] of [
    [true, 2, 0, 0, false],
    [true, 0, 0, 1, false],
    [true, 0, 3, 1, false],
    [false, 0, 0, 0, false],
    [true, 2, 0, 0, true],
    [true, 2, 0, 0, false, 262144],
    [true, 0, 0, 1, false, 262144],
  ] as const) {
    test(`required=${required}, executed=${passes}, Bun exit=${testExit}, parent coverage exists=${parentCoverageExists}${outputBytes ? `, diagnostic bytes=${outputBytes}` : ''}`, () => {
      const home = mkdtempSync(join(tmpdir(), 'gbrain-ci-pooler-'));
      try {
        const bin = join(home, 'bin');
        mkdirSync(bin);
        mkdirSync(join(home, 'scripts/lib'), { recursive: true });
        const script = readFileSync(join(import.meta.dir, '../../scripts/run-e2e.sh'), 'utf8');
        writeFileSync(join(home, 'scripts/run-e2e.sh'), script);
        writeFileSync(join(home, 'scripts/lib/test-env.sh'), readFileSync(join(import.meta.dir, '../../scripts/lib/test-env.sh'), 'utf8') + '\nensure_pglite_snapshot() { :; }\n');
        writeFileSync(join(bin, 'psql'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
        writeFileSync(join(bin, 'bun'), `#!/bin/sh
printf '%s\\n' "$GBRAIN_PGBOUNCER_URL" "$GBRAIN_PGBOUNCER_DIRECT_URL" "$GBRAIN_CI_REQUIRE_PGBOUNCER" "$GBRAIN_TEST_DB" "\${GBRAIN_SOURCE-unset}" "\${COVERAGE_DIR:-disabled}" > "$ENV_REPORT"
for arg do case "$arg" in --reporter-outfile=*) report="\${arg#*=}" ;; esac; done
skips=0
if [ "$FAKE_PASSES" -eq 0 ]; then skips=4; fi
tests=$((FAKE_PASSES + skips))
{
  printf '<testsuites tests="%s" failures="0" skipped="%s">\\n  <testsuite file="test/e2e/pgbouncer-teardown.test.ts" tests="%s" failures="0" skipped="%s">\\n' "$tests" "$skips" "$tests" "$skips"
  i=0
  while [ "$i" -lt "$tests" ]; do
    printf '<testcase name="pooler-%s">' "$i"
    if [ "$FAKE_PASSES" -eq 0 ]; then printf '<skipped />'; fi
    printf '</testcase>\\n'
    i=$((i + 1))
  done
  printf '</testsuite>\\n</testsuites>\\n'
} > "$report"
printf 'bun test v1.3.13\\n\\ntest/e2e/pgbouncer-teardown.test.ts:\\n %s pass\\n %s skip\\n 0 fail\\nRan %s tests across 1 file. [1.00ms]\\n' "$FAKE_PASSES" "$skips" "$tests"
if [ "$FAKE_OUTPUT_BYTES" -gt 0 ]; then printf '%*s\\n' "$FAKE_OUTPUT_BYTES" ''; fi
exit "$FAKE_EXIT"
`, { mode: 0o755 });
        const report = join(home, 'environment');
        const pooled = 'postgresql://localhost:6543/gbrain_pgbouncer_test';
        const direct = 'postgresql://localhost:5434/gbrain_test';
        const parentCoverage = join(home, 'parent-coverage');
        const parentManifest = join(parentCoverage, 'lane-manifest.json');
        const manifestBefore = '{"lane":"shard-1","complete":true}\n';
        if (parentCoverageExists) {
          mkdirSync(parentCoverage);
          writeFileSync(parentManifest, manifestBefore);
        }
        // Model hosted CI even when this test runs locally: nested fake Bun
        // must neither collect into nor overwrite the outer unit lane.
        const inheritedEnv = { ...process.env, COVERAGE_DIR: parentCoverage };
        const result = spawnSync('bash', [join(home, 'scripts/run-e2e.sh'), 'test/e2e/pgbouncer-teardown.test.ts'], {
          cwd: home, encoding: 'utf8', timeout: 5_000,
          env: {
            ...inheritedEnv, HOME: home, PATH: `${bin}:${process.env.PATH}`,
            // This child intentionally exercises one selected file. The outer
            // unit shard must not repartition it into an empty E2E selection.
            SHARD: '',
            COVERAGE_DIR: '',
            DATABASE_URL: direct, GBRAIN_PGBOUNCER_URL: pooled, GBRAIN_PGBOUNCER_DIRECT_URL: direct,
            GBRAIN_CI_REQUIRE_PGBOUNCER: required ? '1' : '0', GBRAIN_SOURCE: 'ambient-must-be-removed',
            GBRAIN_TEST_DB: '1',
            ENV_REPORT: report, FAKE_PASSES: String(passes), FAKE_EXIT: String(testExit), FAKE_OUTPUT_BYTES: String(outputBytes),
          },
        });
        expect(result.status, result.stdout + result.stderr).toBe(expectedExit);
        expect(readFileSync(report, 'utf8')).toBe(`${pooled}\n${direct}\n${required ? '1' : '0'}\n1\nunset\ndisabled\n`);
        if (parentCoverageExists) expect(readFileSync(parentManifest, 'utf8')).toBe(manifestBefore);
        else expect(existsSync(parentCoverage)).toBe(false);
        if (required && passes === 0 && testExit === 0) expect(result.stdout).toContain('required PgBouncer tests did not execute');
      } finally {
        rmSync(home, { recursive: true, force: true });
      }
    });
  }
});

describe('local test configuration through run-e2e', () => {
  for (const disabled of ['1', '0', undefined]) {
    test(`preserves configuration isolation flag ${disabled ?? '(absent)'} through the actual Bun child`, () => {
      const fixture = mkdtempSync(join(tmpdir(), 'gbrain-e2e-env-file-'));
      const repo = resolve(import.meta.dir, '../..');
      try {
        mkdirSync(join(fixture, 'scripts/lib'), { recursive: true });
        mkdirSync(join(fixture, 'test/e2e'), { recursive: true });
        // Copy the real loader into a separate fixture: its import.meta.dir
        // must resolve ONLY our synthetic .env.testing, never the checkout's.
        writeFileSync(join(fixture, 'scripts/run-e2e.sh'), readFileSync(join(repo, 'scripts/run-e2e.sh')));
        writeFileSync(join(fixture, 'scripts/lib/test-env.sh'), readFileSync(join(import.meta.dir, '../../scripts/lib/test-env.sh'), 'utf8') + '\nensure_pglite_snapshot() { :; }\n');
        writeFileSync(join(fixture, 'test/e2e/helpers.ts'), readFileSync(join(repo, 'test/e2e/helpers.ts')));
        symlinkSync(join(repo, 'src'), join(fixture, 'src'), 'dir');
        symlinkSync(join(repo, 'test/helpers'), join(fixture, 'test/helpers'), 'dir');
        writeFileSync(join(fixture, '.env.testing'), 'E2E_CONFIG_FILE_CANARY=synthetic-fixture-loaded\n');
        const expected = {
          disabled: disabled ?? null,
          loaded: disabled === '1' ? null : 'synthetic-fixture-loaded',
          operatorOverride: null,
        };
        writeFileSync(join(fixture, 'test/e2e/config-file-probe.test.ts'), `
import { expect, test } from 'bun:test';
import './helpers.ts';
test('configuration file respects the parent isolation policy', () => {
  expect({
    disabled: process.env.GBRAIN_CI_DISABLE_TEST_ENV_FILE ?? null,
    loaded: process.env.E2E_CONFIG_FILE_CANARY ?? null,
    operatorOverride: process.env.GBRAIN_SOURCE ?? null,
  }).toEqual(${JSON.stringify(expected)});
});
`);
        const env: Record<string, string | undefined> = {
          ...process.env, HOME: fixture, PATH: `${dirname(process.execPath)}:${process.env.PATH}`,
          SHARD: '', COVERAGE_DIR: '', DATABASE_URL: '', GBRAIN_DATABASE_URL: '',
          GBRAIN_CI_REQUIRE_PGBOUNCER: '0', GBRAIN_SOURCE: 'ambient-must-be-removed',
          GBRAIN_CI_DISABLE_TEST_ENV_FILE: disabled,
        };
        delete env.E2E_CONFIG_FILE_CANARY;
        const result = spawnSync('bash', [join(fixture, 'scripts/run-e2e.sh'), 'test/e2e/config-file-probe.test.ts'], {
          cwd: fixture, encoding: 'utf8', timeout: 20_000, env,
        });
        expect(result.status, result.stdout + result.stderr).toBe(0);
        expect(result.stdout).toContain('1 pass');
      } finally {
        rmSync(fixture, { recursive: true, force: true });
      }
    }, 25_000);
  }
});