Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(ci): identity-level executed-test ledger and report-only CI step (X2)
garrytan109927d40ec4
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex a78c308938..19d132fdbd 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -98,13 +98,23 @@ jobs:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test# #3485 preload guard: this job intentionally tests against a DB.GBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts# --timeout also raises bun's 5s default hook budget (beforeAll/afterAll# do NOT inherit a test's third-arg timeout; verified on bun 1.3.x).# Every runner script in scripts/ passes it; bare invocations must too.# phantom-redirect rides this job: its Postgres arm is the other# engine-parity backstop and no other CI lane carries DATABASE_URL to it# (the unit wrappers strip the URL per #3485).- run: bun test --timeout=60000 test/e2e/op-checkpoint-jsonb-parity.test.ts test/e2e/jsonb-roundtrip.test.ts test/phantom-redirect-engine-parity.test.ts+ run: bash scripts/run-with-receipt.sh jsonb-parity guard -- bun test --timeout=60000 test/e2e/op-checkpoint-jsonb-parity.test.ts test/e2e/jsonb-roundtrip.test.ts test/phantom-redirect-engine-parity.test.ts+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-jsonb-parity+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true# Freeze selection before setup; each worker owns a separate Postgres service.prepare-e2e:@@ -191,7 +201,28 @@ jobs:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_testGBRAIN_TEST_ALLOW_DATABASE_URL: '1'E2E_MATRIX_ROW: ${{ toJSON(matrix) }}+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receiptsrun: bun scripts/capture-test-log.ts --job 'Selected E2E (diff-relevant) ${{ matrix.shard }}' --out "$RUNNER_TEMP/e2e.log" -- bun scripts/e2e-matrix.ts run+ # An empty (doc-only) selection launches nothing; record that the lane+ # was declared empty so the identity ledger does not read it as missing.+ - name: Record declared-empty selection+ if: ${{ matrix.empty }}+ shell: bash+ run: |+ mkdir -p "$RUNNER_TEMP/receipts"+ printf '%s\n' version=1 lane=e2e kind=primary tag=declared-empty shard= of= arm= "sha=$GITHUB_SHA" \+ "run_id=$GITHUB_RUN_ID" "run_attempt=$GITHUB_RUN_ATTEMPT" "job=$GITHUB_JOB" "started=$(date +%s)" declared_empty=1 exit=0 \+ > "$RUNNER_TEMP/receipts/e2e--declared-empty--primary.receipt"+ : > "$RUNNER_TEMP/receipts/e2e--declared-empty--primary.files"+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-e2e-${{ matrix.shard }}+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true- name: Upload E2E timing logif: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4@@ -282,20 +313,22 @@ jobs:# (test/e2e/helpers.ts) as the other DB-backed files on this line.# Also added to the E2E_EXCLUSIONS in scripts/e2e-matrix.ts so a PR# touching sync.ts doesn't run it a second time there.- run: bun test --timeout=60000 test/e2e/mechanical.test.ts test/e2e/job-isolation.test.ts test/e2e/sync-reconcile-postgres.test.ts+ run: bash scripts/run-with-receipt.sh tier1 mechanical -- bun test --timeout=60000 test/e2e/mechanical.test.ts test/e2e/job-isolation.test.ts test/e2e/sync-reconcile-postgres.test.tsenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test# #3485 preload guard: this job intentionally tests against a DB.GBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts- name: Run engine parity suite# The behavioral parity pin for the two engines (containment-sprint# engine peels lean on it). Own invocation line: this suite has only# ever run one-process-per-file via run-e2e.sh — do not fold it into# the shared-process tier1 line above.- run: bun test --timeout=60000 test/e2e/engine-parity.test.ts+ run: bash scripts/run-with-receipt.sh tier1 engine-parity -- bun test --timeout=60000 test/e2e/engine-parity.test.tsenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_testGBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts- name: Run backend matrix (direct Postgres, then PgBouncer)# scripts/e2e-backend-matrix.txt: the E5 executor binding matrix and the# engine parity files, each run on direct Postgres and again through the@@ -314,16 +347,19 @@ jobs:GBRAIN_CI_REQUIRE_PGBOUNCER: '1'GBRAIN_TEST_DB: '1'GBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ GBRAIN_TEST_RECEIPT_LANE: backend-matrix- name: Run multi-agent serve suite# cathedral-6 (T7): multi-agent continuity + isolation over a real# `gbrain serve --http`. Own invocation line (engine-parity# precedent): the file spawns two serves on fixed ports# (19133/19134) and SIGKILLs one mid-hammer — never fold it into the# shared-process tier1 line above. Named files only, no glob.- run: bun test --timeout=60000 test/e2e/serve-http-multi-agent.test.ts+ run: bash scripts/run-with-receipt.sh tier1 serve-http-multi-agent -- bun test --timeout=60000 test/e2e/serve-http-multi-agent.test.tsenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_testGBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts- name: Create isolated database for the bootstrap suite# The bootstrap suite rewinds the schema ledger and replays every# migration; replayed constraint-adds (e.g. facts_source_id_fkey)@@ -339,11 +375,12 @@ jobs:# coverage-full-e2e glob, so a broken PostgresEngine bootstrap block# could reach master with every PR lane green. Own invocation line# and its OWN database (see the step above). Named files only, no glob.- run: bun test --timeout=60000 test/e2e/postgres-bootstrap.test.ts+ run: bash scripts/run-with-receipt.sh tier1 postgres-bootstrap -- bun test --timeout=60000 test/e2e/postgres-bootstrap.test.tsenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_bootstrap_test# #3485 preload guard: this job intentionally tests against a DB.GBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts- name: Run serve-delegated sync suite# Serve-delegated sync (PGLite): a real `gbrain serve` owns the# single-writer lock while real `gbrain sync` subprocesses delegate@@ -352,13 +389,26 @@ jobs:# PGLite-only (env DATABASE_URL is a live gbrain config source and# would flip the sandboxed brain to Postgres; the file also# self-strips). Named files only, no glob.- run: bun test --timeout=240000 test/e2e/sync-delegation-under-serve.serial.test.ts+ run: bash scripts/run-with-receipt.sh tier1 sync-delegation -- bun test --timeout=240000 test/e2e/sync-delegation-under-serve.serial.test.ts+ env:+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts- name: Run PGLite inline subagent drain suite# dream-synthesize-pglite pins the inline drain's per-child lease# keepalive (v0.46.26 private-queue lifecycle) — previously nightly-# glob-only, where the keepalive pin broke silently. Deliberately NO# DATABASE_URL: the suite is PGLite-only. Named files only, no glob.- run: bun test --timeout=120000 test/e2e/dream-synthesize-pglite.test.ts+ run: bash scripts/run-with-receipt.sh tier1 dream-synthesize -- bun test --timeout=120000 test/e2e/dream-synthesize-pglite.test.ts+ env:+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-tier1+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: truetier2:name: Tier 2 (LLM Skills)@@ -452,13 +502,23 @@ jobs:}EOF- name: Run Tier 2 skill tests- run: bun test --timeout=60000 test/e2e/skills.test.ts+ run: bash scripts/run-with-receipt.sh tier2 skills -- bun test --timeout=60000 test/e2e/skills.test.tsenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test# #3485 preload guard: this job intentionally tests against a DB.GBRAIN_TEST_ALLOW_DATABASE_URL: '1'OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-tier2+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true# ──────────────────────────────────────────────────────────────────────# Full coverage pipeline (scheduled or explicitly dispatched). The honest@@ -487,6 +547,17 @@ jobs:run: scripts/test-shard.sh ${{ matrix.shard }} 10env:COVERAGE_DIR: ${{ runner.temp }}/coverage+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ GBRAIN_TEST_RECEIPT_LANE: full-unit+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-full-unit-${{ matrix.shard }}+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true- name: Upload coverageif: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4@@ -510,6 +581,17 @@ jobs:- run: bun run test:serialenv:COVERAGE_DIR: ${{ runner.temp }}/coverage+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ GBRAIN_TEST_RECEIPT_LANE: full-serial+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-full-serial+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true- name: Upload coverageif: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4@@ -620,6 +702,17 @@ jobs:E2E_FILE_TIMEOUT_SECS: '300'OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ GBRAIN_TEST_RECEIPT_LANE: full-e2e+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-full-e2e-${{ matrix.shard }}+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true- name: Upload coverageif: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4@@ -691,6 +784,49 @@ jobs:if-no-files-found: ignoreoverwrite: true+ # Report-only executed-test ledger (X2) plus the A9 missing-key line: every+ # lane's receipts in one identity table (step summary + JSON artifact). Not+ # in e2e-status; baseline comparisons run locally with+ # bun scripts/ci-executed-counts.ts --base-run <id> --head-run <id>+ executed-receipts:+ needs: [jsonb-parity, tier1, tier2, selected-e2e, coverage-full-unit, coverage-full-serial, coverage-full-e2e]+ if: always()+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.2+ - name: Download receipts+ continue-on-error: true+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ with:+ pattern: receipts-*+ path: ${{ runner.temp }}/receipts+ - name: Executed-test identities and missing-key skips → step summary (report-only)+ # Selected E2E never receives provider keys; Tier 2 and the nightly+ # full E2E receive the repo secrets, which may be unset (A9).+ env:+ OPENAI_SET: ${{ secrets.OPENAI_API_KEY != '' }}+ ANTHROPIC_SET: ${{ secrets.ANTHROPIC_API_KEY != '' }}+ run: |+ mkdir -p "$RUNNER_TEMP/receipts"+ state() { [ "$1" = true ] && echo set || echo unset; }+ echo "Provider secrets: OPENAI_API_KEY $(state "$OPENAI_SET"), ANTHROPIC_API_KEY $(state "$ANTHROPIC_SET"). Selected E2E runs without provider keys by design." >> "$GITHUB_STEP_SUMMARY"+ bun scripts/ci-executed-counts.ts --head-dir "$RUNNER_TEMP/receipts" --report-only \+ --expect-attempt "$GITHUB_RUN_ID:$GITHUB_RUN_ATTEMPT" --missing-keys OPENAI_API_KEY,ANTHROPIC_API_KEY \+ --summary "$GITHUB_STEP_SUMMARY" --json "$RUNNER_TEMP/executed-identities.json" > /dev/null+ - name: Upload identity ledger+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: executed-identities+ path: ${{ runner.temp }}/executed-identities.json+ retention-days: 14+ if-no-files-found: ignore+ overwrite: true+# The stable aggregate includes full-profile execution lanes when requested.# Coverage reporting itself remains advisory; failed tests never do.e2e-status:diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex f9e8848f79..a3c00f6bec 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -210,7 +210,21 @@ jobs:# check:schema-migration-order compares new schema migrations with# origin/master's latest version; a depth-1 fetch of the ref is enough.- run: git fetch --no-tags --depth=1 origin +refs/heads/master:refs/remotes/origin/master+ # Receipts (X2): verify records every check's real outcome (pass, fail,+ # timeout, self-skip) as one JUnit testcase; logs stay on failure.- run: bun run verify+ env:+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ GBRAIN_VERIFY_LOG_DIR: ${{ runner.temp }}/verify-logs+ - name: Upload verify logs+ if: failure()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: verify-logs+ path: ${{ runner.temp }}/verify-logs+ retention-days: 14+ if-no-files-found: ignore+ overwrite: true# Guard: no bare `bun test` in workflows/scripts — bun ignores# bunfig.toml's timeout, and hooks (beforeAll/afterAll) get the 5s# default regardless of per-test third-arg timeouts. Runs directly@@ -223,9 +237,19 @@ jobs:- name: Shell scripts parse under bash 3.2env:GBRAIN_BASH32_REQUIRE: '1'+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receiptsrun: |bun run check:bash32- bun test --timeout 60000 test/scripts/check-bash32.test.ts+ bash scripts/run-with-receipt.sh verify-tests bash32 -- bun test --timeout 60000 test/scripts/check-bash32.test.ts+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-verify+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: trueserial-tests:if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}@@ -276,6 +300,16 @@ jobs:env:SHARD: ${{ matrix.shard }}/4COVERAGE_DIR: ${{ runner.temp }}/coverage+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-serial-${{ matrix.shard }}+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true- name: Upload coverage (serial lane)if: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4@@ -336,12 +370,23 @@ jobs:- run: bun install --frozen-lockfile- name: Ensure PGLite snapshot (build-or-validate, non-fatal)run: bash -c '. scripts/lib/test-env.sh && ensure_pglite_snapshot slow-eval && echo "GBRAIN_PGLITE_SNAPSHOT=${GBRAIN_PGLITE_SNAPSHOT:-}" >> "$GITHUB_ENV"'- - run: bun test test/eval-longmemeval-e2e.slow.test.ts --timeout=60000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/sloweval+ - run: bash scripts/run-with-receipt.sh slow longmemeval-e2e -- bun test test/eval-longmemeval-e2e.slow.test.ts --timeout=60000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/sloweval+ env:+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts- name: Write coverage lane manifestrun: |printf '{"lane":"sloweval","sha":"%s","lcovCount":%s,"complete":true}\n' \"$GITHUB_SHA" "$(find "$RUNNER_TEMP/coverage" -name lcov.info | wc -l | tr -d ' ')" \> "$RUNNER_TEMP/coverage/lane-manifest.json"+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-slow-eval+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true- name: Upload coverage (slow-eval lane)if: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4@@ -401,12 +446,23 @@ jobs:*) echo "GBRAIN_PGLITE_SNAPSHOT=$PWD/$GBRAIN_PGLITE_SNAPSHOT" >> "$GITHUB_ENV" ;;esacfi- - run: bun test test/eval-brainbench-e2e.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/slowbrainbench+ - run: bash scripts/run-with-receipt.sh slow brainbench-e2e -- bun test test/eval-brainbench-e2e.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/slowbrainbench+ env:+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts- name: Write coverage lane manifestrun: |printf '{"lane":"slowbrainbench","sha":"%s","lcovCount":%s,"complete":true}\n' \"$GITHUB_SHA" "$(find "$RUNNER_TEMP/coverage" -name lcov.info | wc -l | tr -d ' ')" \> "$RUNNER_TEMP/coverage/lane-manifest.json"+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-slow-brainbench+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true- name: Upload coverage (slow-brainbench lane)if: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4@@ -490,22 +546,36 @@ jobs:run: bash -c '. scripts/lib/test-env.sh && ensure_pglite_snapshot slow-perf && echo "GBRAIN_PGLITE_SNAPSHOT=${GBRAIN_PGLITE_SNAPSHOT:-}" >> "$GITHUB_ENV"'# Two bun processes: each needs its own coverage dir (a reused dir is# silently overwritten by the second process).- - run: bun test test/entity-resolve-perf.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/perf-a+ - run: bash scripts/run-with-receipt.sh slow entity-resolve-perf -- bun test test/entity-resolve-perf.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/perf-a+ env:+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts# MEMORY_VERBS v1 (Cathedral 1): the entity() p99 < 100ms contract gate# (20K-page corpus + ratio guard) shares this runner — same perf-job# shape, runs in parallel with the matrix.- - run: bun test test/entity-card-perf.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/perf-b+ - run: bash scripts/run-with-receipt.sh slow entity-card-perf -- bun test test/entity-card-perf.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/perf-b+ env:+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts# Export at scale: pull requests prove bounded keyset enumeration, sidecars# and fence normalization on 10,001 pages (~30s); pushes, schedules and# manual runs keep the 100,001-page scale (~4-10 minutes, one core).- - run: bun test test/export-scale.slow.test.ts --timeout=900000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/perf-c+ - run: bash scripts/run-with-receipt.sh slow export-scale -- bun test test/export-scale.slow.test.ts --timeout=900000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/perf-cenv:GBRAIN_TEST_EXPORT_SCALE_PAGES: ${{ github.event_name == 'pull_request' && '10001' || '100001' }}+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts- name: Write coverage lane manifestrun: |printf '{"lane":"slowperf","sha":"%s","lcovCount":%s,"complete":true}\n' \"$GITHUB_SHA" "$(find "$RUNNER_TEMP/coverage" -name lcov.info | wc -l | tr -d ' ')" \> "$RUNNER_TEMP/coverage/lane-manifest.json"+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-slow-perf+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true- name: Upload coverage (slow-perf lane)if: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4@@ -573,6 +643,16 @@ jobs:run: bun scripts/capture-test-log.ts --job 'test (${{ matrix.shard }})' --out "$RUNNER_TEMP/unit.log" -- bash scripts/test-shard.sh ${{ matrix.shard }} 8env:COVERAGE_DIR: ${{ runner.temp }}/coverage+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-unit-${{ matrix.shard }}+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true- name: Upload coverage (shard lane)if: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4@@ -708,7 +788,60 @@ jobs:- name: Build the pinned pre-feature executablerun: bash scripts/build-shared-skills-baseline.sh "$RUNNER_TEMP/gbrain-before-shared-skills"- name: Reject old consumers before they change shared skill state- run: GBRAIN_TEST_OLD_BINARY="$RUNNER_TEMP/gbrain-before-shared-skills" bun test --timeout 180000 test/persistence-skill-old-binary.slow.test.ts+ env:+ GBRAIN_TEST_OLD_BINARY: ${{ runner.temp }}/gbrain-before-shared-skills+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ run: bash scripts/run-with-receipt.sh shared-skills old-binary -- bun test --timeout 180000 test/persistence-skill-old-binary.slow.test.ts+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-shared-skills+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true++ # Report-only executed-test ledger (X2): every lane's receipts in one+ # identity table (step summary + JSON artifact). Not in test-status: a+ # comparison against a baseline run is the parent's local call:+ # bun scripts/ci-executed-counts.ts --base-run <id> --head-run <id>+ executed-receipts:+ needs: [verify, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, test, shared-skills-compatibility]+ if: ${{ always() && (github.event_name != 'workflow_dispatch' || inputs.native_only != true) }}+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ sparse-checkout: |+ scripts/ci-executed-counts.ts+ docs/test-audit/2026-10-04/expected-deltas.tsv+ sparse-checkout-cone-mode: false+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.2+ - name: Download receipts+ continue-on-error: true+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ with:+ pattern: receipts-*+ path: ${{ runner.temp }}/receipts+ - name: Executed-test identities → step summary (report-only)+ run: |+ mkdir -p "$RUNNER_TEMP/receipts"+ bun scripts/ci-executed-counts.ts --head-dir "$RUNNER_TEMP/receipts" --report-only \+ --expect-attempt "$GITHUB_RUN_ID:$GITHUB_RUN_ATTEMPT" \+ --summary "$GITHUB_STEP_SUMMARY" --json "$RUNNER_TEMP/executed-identities.json" > /dev/null+ - name: Upload identity ledger+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: executed-identities+ path: ${{ runner.temp }}/executed-identities.json+ retention-days: 14+ if-no-files-found: ignore+ overwrite: true# The stable aggregate succeeds only when every required lane ran successfully.# Coverage percentages remain advisory until their separate graduation.diff --git a/docs/test-audit/2026-10-04/expected-deltas.tsv b/docs/test-audit/2026-10-04/expected-deltas.tsvnew file mode 100644index 0000000000..ac3eb23040--- /dev/null+++ b/docs/test-audit/2026-10-04/expected-deltas.tsv@@ -0,0 +1,25 @@+# Expected executed-test deltas for the GBRA-47 test/eval/CI wave (X2).+#+# scripts/ci-executed-counts.ts compares the executed test identities of a+# baseline run with a head run. Identity = (lane, file, test, arm). Every base+# identity that no longer executes in head must match a row below, or the+# comparison fails and prints the row to add. New tests need no row.+#+# Columns (tab-separated; \t, \n and \\ escape a tab, newline or backslash):+# kind retire | move | skip | job+# lane identity lane: unit, serial, slow, verify, e2e, backend-matrix,+# tier1, tier2, jsonb-parity, shared-skills (job rows: the CI+# artifact name that no longer exists, * allowed, e.g. receipts-slow-eval)+# file test file (exact; verify checks use "verify")+# test full test name ("describe > test"), or * for every test in the file+# arm backend arm (postgres-direct, pgbouncer) or empty; * matches any+# new_lane move only: lane the test runs in now (empty = unchanged)+# new_file move only: file the test lives in now (empty = unchanged)+# new_test move only: new test name (empty = unchanged; with test=* names stay)+# reason why the identity stops executing here (required, never TODO)+# evidence retire only: the Retiring-a-test row, e.g.+# docs/test-audit/2026-10-04/implementation/<lane>.md#<anchor>+#+# A move passes only when the target identity executes in head; a skip row+# (planned pass-to-skip) passes only when head reports the test skipped.+kind lane file test arm new_lane new_file new_test reason evidencediff --git a/scripts/ci-executed-counts.ts b/scripts/ci-executed-counts.tsnew file mode 100644index 0000000000..9abe70175a--- /dev/null+++ b/scripts/ci-executed-counts.ts@@ -0,0 +1,701 @@+#!/usr/bin/env bun+/**+ * Executed-test identity ledger (X2).+ *+ * Reads the receipts every CI lane writes (scripts/lib/test-env.sh+ * `receipts_init`: one `<id>.receipt` + `<id>.files` + Bun JUnit report per bun+ * invocation; verify writes one testcase per check) and accounts for every+ * executed test by identity: (lane, file, test name, backend arm).+ *+ * One side (head only) prints the per-lane executed/skipped/failed table and+ * every completeness problem. Two sides (base and head) also list each base+ * identity that no longer executes in head. A drop passes only when+ * docs/test-audit/2026-10-04/expected-deltas.tsv declares it (retirement,+ * move, pass-to-skip); otherwise the tool prints the exact row to declare it.+ * New tests need no declaration.+ *+ * Completeness (any problem means `incomplete`, which fails):+ * - an assigned file with no valid JUnit from any attempt (a killed shard+ * that no rescue re-ran, a truncated report); a later attempt (rerun or+ * rescue) supersedes an earlier one for the files it re-ran;+ * - a receipt from an earlier run attempt than the run's latest;+ * - a missing shard, a lane that executed zero tests (unless the lane was+ * declared empty), or a base artifact missing from head without a+ * `job` row.+ *+ * Usage:+ * bun scripts/ci-executed-counts.ts --head-run <id>[,<id>] [--base-run <id>[,<id>]]+ * bun scripts/ci-executed-counts.ts --head-dir <dir> [--base-dir <dir>]+ * Options: --deltas <tsv>, --summary <file> (appends Markdown, e.g. the step+ * summary), --json <file>, --report-only (always exit 0), --fail-on-additions+ * (stability check between baseline runs), --expect-attempt <run>:<n>,+ * --missing-keys K1,K2 (count skipped tests in files that read those keys),+ * --repo owner/name.+ * Exit: 0 pass, 1 drop/incomplete, 2 usage or download error.+ */+import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync, appendFileSync, writeFileSync } from 'node:fs';+import { basename, join } from 'node:path';+import { spawnSync } from 'node:child_process';+import { tmpdir } from 'node:os';++export const DEFAULT_DELTAS = 'docs/test-audit/2026-10-04/expected-deltas.tsv';+const DOCS = 'Docs: docs/TESTING.md#executed-test-receipts';++export type Status = 'pass' | 'fail' | 'skip' | 'todo';+export interface TestCase { file: string; test: string; status: Status }++export class JUnitError extends Error {}++const ENTITIES: Record<string, string> = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" };+function decode(text: string): string {+ return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-z]+);/g, (whole, ref: string) => {+ if (ref[0] === '#') {+ const code = ref[1] === 'x' ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;+ }+ return ENTITIES[ref] ?? whole;+ });+}++/** Unstable fragments (temp paths, UUIDs) must not split one test into two identities. Timestamps stay: test names use fixed dates on purpose. */+export function canonicalTestName(name: string): string {+ return name+ .replace(/\/(?:private\/)?(?:tmp|var\/folders)\/[^\s'"`),]+/g, '<tmp>')+ .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, '<uuid>');+}++/**+ * Strict parser for the JUnit subset Bun (and run-verify-parallel.sh) writes.+ * Anything malformed or cut short throws: a truncated report is never read as+ * a shorter test list.+ */+export function parseJUnit(xml: string): TestCase[] {+ const token = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>|<(\/?)([A-Za-z_][\w:.-]*)((?:\s+[\w:.-]+\s*=\s*"[^"]*")*)\s*(\/?)>|[^<]+/y;+ const attrRe = /([\w:.-]+)\s*=\s*"([^"]*)"/g;+ const stack: { tag: string; attrs: Record<string, string> }[] = [];+ const cases: TestCase[] = [];+ let current: { file: string; test: string; status: Status } | undefined;+ let rootTests: number | undefined;+ let closedRoot = false;+ const open = (tag: string, attrs: Record<string, string>) => {+ if (tag === 'testcase') {+ const suites = stack.filter(s => s.tag === 'testsuite');+ const file = suites[0]?.attrs.file ?? attrs.file ?? suites[0]?.attrs.name ?? '';+ const describe = suites.slice(1).map(s => s.attrs.name ?? '');+ if (!attrs.name) throw new JUnitError('testcase without a name');+ current = { file, test: [...describe, attrs.name].join(' > '), status: 'pass' };+ } else if (current && tag === 'skipped') {+ if (current.status !== 'fail') current.status = attrs.message === 'TODO' ? 'todo' : 'skip';+ } else if (current && (tag === 'failure' || tag === 'error')) {+ current.status = 'fail';+ }+ };+ const close = (tag: string) => {+ if (tag === 'testcase' && current) {+ cases.push({ ...current, test: canonicalTestName(current.test) });+ current = undefined;+ }+ if (tag === 'testsuites' && stack.length === 0) closedRoot = true;+ };+ let index = 0;+ while (index < xml.length) {+ token.lastIndex = index;+ const match = token.exec(xml);+ if (!match) throw new JUnitError(`malformed or truncated report near byte ${index}`);+ index = token.lastIndex;+ const [whole, slash, tag, rawAttrs, selfClose] = match;+ if (!tag) {+ if (whole.startsWith('<') || stack.length || closedRoot || !whole.trim()) continue;+ throw new JUnitError('text outside the report root');+ }+ if (closedRoot) throw new JUnitError('content after the closing </testsuites>');+ if (slash) {+ const top = stack.pop();+ if (!top || top.tag !== tag) throw new JUnitError(`unbalanced </${tag}>`);+ close(tag);+ continue;+ }+ const attrs: Record<string, string> = {};+ for (const a of (rawAttrs ?? '').matchAll(attrRe)) attrs[a[1]] = decode(a[2]);+ if (stack.length === 0) {+ if (tag !== 'testsuites') throw new JUnitError(`report root is <${tag}>, expected <testsuites>`);+ if (attrs.tests !== undefined) rootTests = Number(attrs.tests);+ }+ open(tag, attrs);+ if (selfClose) close(tag);+ else stack.push({ tag, attrs });+ }+ if (!closedRoot || stack.length) throw new JUnitError('report ends before </testsuites> (truncated)');+ if (rootTests !== undefined && rootTests !== cases.length) {+ throw new JUnitError(`report declares ${rootTests} tests but lists ${cases.length}`);+ }+ return cases;+}++const RANK: Record<string, number> = { primary: 0, rerun: 1, rescue: 2 };++export interface Receipt {+ id: string;+ artifact: string;+ lane: string;+ kind: string;+ shard?: number;+ of?: number;+ arm: string;+ runId: string;+ runAttempt?: number;+ sha: string;+ started: number;+ exit?: number;+ empty: boolean;+ declaredEmpty: boolean;+ files: string[];+ junit: 'ok' | 'missing' | 'truncated' | 'not-expected';+ junitError?: string;+ cases: TestCase[];+}++function normalizePath(path: string, root: string): string {+ let p = path.trim();+ if (root && p.startsWith(`${root}/`)) p = p.slice(root.length + 1);+ return p.replace(/^\.\//, '');+}++function readMeta(text: string): Record<string, string> {+ const meta: Record<string, string> = {};+ for (const line of text.split('\n')) {+ const eq = line.indexOf('=');+ if (eq > 0) meta[line.slice(0, eq)] = line.slice(eq + 1);+ }+ return meta;+}++const optionalInt = (value: string | undefined): number | undefined =>+ value !== undefined && /^\d+$/.test(value) ? Number(value) : undefined;++export function loadReceipt(dir: string, id: string, artifact: string): Receipt {+ const meta = readMeta(readFileSync(join(dir, `${id}.receipt`), 'utf8'));+ const root = meta.root ?? '';+ const filesPath = join(dir, `${id}.files`);+ const files = existsSync(filesPath)+ ? readFileSync(filesPath, 'utf8').split('\n').filter(Boolean).map(f => normalizePath(f, root))+ : [];+ const empty = meta.empty === '1' || meta.declared_empty === '1';+ const receipt: Receipt = {+ id, artifact, files, empty,+ lane: meta.lane || 'unknown',+ kind: meta.kind || 'primary',+ shard: optionalInt(meta.shard),+ of: optionalInt(meta.of),+ arm: meta.arm ?? '',+ runId: meta.run_id ?? '',+ runAttempt: optionalInt(meta.run_attempt),+ sha: meta.sha ?? '',+ started: optionalInt(meta.started) ?? 0,+ exit: optionalInt(meta.exit),+ declaredEmpty: meta.declared_empty === '1',+ junit: empty ? 'not-expected' : 'missing',+ cases: [],+ };+ const junitPath = join(dir, `${id}.junit.xml`);+ if (!empty && existsSync(junitPath)) {+ try {+ receipt.cases = parseJUnit(readFileSync(junitPath, 'utf8')).map(c => ({ ...c, file: normalizePath(c.file, root) }));+ receipt.junit = 'ok';+ } catch (error) {+ receipt.junit = 'truncated';+ receipt.junitError = error instanceof Error ? error.message : String(error);+ }+ }+ return receipt;+}++/** A directory of receipts is one artifact; a directory of such directories is several. */+export function loadReceiptDir(dir: string): Receipt[] {+ const ids = (d: string) => readdirSync(d).filter(n => n.endsWith('.receipt')).map(n => n.slice(0, -'.receipt'.length)).sort();+ const own = ids(dir);+ if (own.length) return own.map(id => loadReceipt(dir, id, basename(dir)));+ const receipts: Receipt[] = [];+ for (const name of readdirSync(dir).sort()) {+ const sub = join(dir, name);+ if (!statSync(sub).isDirectory()) continue;+ for (const id of ids(sub)) receipts.push(loadReceipt(sub, id, name));+ }+ return receipts;+}++export interface Identity { lane: string; file: string; test: string; arm: string; status: Status; artifact: string; kind: string }+export interface Issue { kind: string; lane?: string; artifact?: string; file?: string; detail: string }+export interface LaneStats { lane: string; files: number; executed: number; passed: number; failed: number; skipped: number; superseded: number; declaredEmpty: boolean }+export interface Side {+ label: string;+ artifacts: Set<string>;+ identities: Map<string, Identity>;+ issues: Issue[];+ duplicates: { key: string; count: number }[];+ overlaps: string[];+ lanes: Map<string, LaneStats>;+ shas: Set<string>;+}++export const identityKey = (lane: string, file: string, test: string, arm: string) => [lane, file, test, arm].join('\u001f');+const executed = (status: Status | undefined) => status === 'pass' || status === 'fail';++function describeAttempt(r: Receipt): string {+ const state = r.junit === 'truncated' ? `truncated JUnit (${r.junitError})` : r.junit === 'missing' ? 'no JUnit report' : r.junit;+ return `${r.artifact}/${r.id} [${r.kind}${r.exit === undefined ? ', interrupted' : `, exit ${r.exit}`}]: ${state}`;+}++export function buildSide(label: string, all: Receipt[], expectedAttempts = new Map<string, number>()): Side {+ const side: Side = { label, artifacts: new Set(all.map(r => r.artifact)), identities: new Map(), issues: [], duplicates: [], overlaps: [], lanes: new Map(), shas: new Set() };+ const latest = new Map(expectedAttempts);+ for (const r of all) {+ if (r.runId && r.runAttempt !== undefined && r.runAttempt > (latest.get(r.runId) ?? 0)) latest.set(r.runId, r.runAttempt);+ }+ const receipts = all.filter(r => {+ const want = r.runId ? latest.get(r.runId) : undefined;+ if (want !== undefined && r.runAttempt !== undefined && r.runAttempt < want) {+ side.issues.push({ kind: 'prior-attempt', lane: r.lane, artifact: r.artifact, detail: `${r.artifact}/${r.id} comes from attempt ${r.runAttempt} of run ${r.runId}; the run's latest attempt is ${want}. Re-run all jobs, not only failed ones, so every lane reports from one attempt.` });+ return false;+ }+ if (r.sha) side.shas.add(r.sha);+ return true;+ });+ const byLane = new Map<string, Receipt[]>();+ for (const r of receipts) byLane.set(r.lane, [...(byLane.get(r.lane) ?? []), r]);+ const duplicateCounts = new Map<string, number>();+ for (const [lane, laneReceipts] of [...byLane].sort(([a], [b]) => a.localeCompare(b))) {+ const stats: LaneStats = { lane, files: 0, executed: 0, passed: 0, failed: 0, skipped: 0, superseded: 0, declaredEmpty: laneReceipts.some(r => r.declaredEmpty) };+ side.lanes.set(lane, stats);+ const sharded = laneReceipts.filter(r => r.of !== undefined);+ const ofs = new Set(sharded.map(r => r.of));+ if (ofs.size > 1) side.issues.push({ kind: 'missing-shard', lane, detail: `lane ${lane} mixes shard totals (${[...ofs].join(', ')})` });+ for (const of of ofs) {+ const present = new Set(sharded.filter(r => r.of === of).map(r => r.shard));+ for (let shard = 1; shard <= (of ?? 0); shard++) {+ if (!present.has(shard)) side.issues.push({ kind: 'missing-shard', lane, detail: `lane ${lane}: shard ${shard} of ${of} left no receipt (its job did not run, or its "Upload receipts" step found nothing)` });+ }+ }+ const byFile = new Map<string, Receipt[]>();+ for (const r of laneReceipts) {+ if (r.empty) continue;+ const files = new Set([...r.files, ...r.cases.map(c => c.file)]);+ for (const file of files) {+ const key = `${file}\u001f${r.arm}`;+ byFile.set(key, [...(byFile.get(key) ?? []), r]);+ }+ }+ stats.files = new Set([...byFile.keys()].map(k => k.split('\u001f')[0])).size;+ for (const [fileArm, attempts] of [...byFile].sort(([a], [b]) => a.localeCompare(b))) {+ const [file, arm] = fileArm.split('\u001f');+ const where = arm ? `${file} [${arm}]` : file;+ const valid = attempts.filter(r => r.junit === 'ok');+ if (!valid.length) {+ side.issues.push({ kind: 'incomplete', lane, file, artifact: attempts[0].artifact, detail: `lane ${lane}: ${where} has no valid receipt from any attempt (${attempts.map(describeAttempt).join('; ')})` });+ continue;+ }+ const primaries = valid.filter(r => (RANK[r.kind] ?? 0) === 0);+ if (primaries.length > 1) side.overlaps.push(`lane ${lane}: ${where} ran in ${primaries.length} primary invocations (${primaries.map(r => `${r.artifact}/${r.id}`).join(', ')})`);+ const winner = valid.reduce((best, r) => {+ const order = (x: Receipt) => [RANK[x.kind] ?? 0, x.started];+ const [br, bs] = order(best);+ const [rr, rs] = order(r);+ return rr > br || (rr === br && (rs > bs || (rs === bs && r.id > best.id))) ? r : best;+ });+ if ((RANK[winner.kind] ?? 0) > 0) stats.superseded++;+ // Repeated names inside one file (Bun's JUnit keeps test.each titles as+ // the unformatted "%s" template) stay distinct by occurrence order.+ const seen = new Map<string, number>();+ for (const c of winner.cases) {+ if (c.file !== file) continue;+ const n = (seen.get(c.test) ?? 0) + 1;+ seen.set(c.test, n);+ const test = n === 1 ? c.test : `${c.test} [#${n}]`;+ if (n > 1) duplicateCounts.set(identityKey(lane, file, c.test, winner.arm), n);+ side.identities.set(identityKey(lane, file, test, winner.arm), { lane, file, test, arm: winner.arm, status: c.status, artifact: winner.artifact, kind: winner.kind });+ }+ }+ }+ for (const id of side.identities.values()) {+ const stats = side.lanes.get(id.lane)!;+ if (id.status === 'pass') stats.passed++;+ else if (id.status === 'fail') stats.failed++;+ else stats.skipped++;+ if (executed(id.status)) stats.executed++;+ }+ for (const stats of side.lanes.values()) {+ if (stats.executed === 0 && !stats.declaredEmpty && stats.files > 0) {+ side.issues.push({ kind: 'empty-lane', lane: stats.lane, detail: `lane ${stats.lane} executed 0 tests across ${stats.files} file(s)` });+ }+ }+ side.duplicates = [...duplicateCounts].map(([key, count]) => ({ key, count }));+ return side;+}++export type DeltaKind = 'retire' | 'move' | 'skip' | 'job';+export interface DeltaRow { line: number; kind: DeltaKind; lane: string; file: string; test: string; arm: string; newLane: string; newFile: string; newTest: string; reason: string; evidence: string }+export const DELTA_COLUMNS = ['kind', 'lane', 'file', 'test', 'arm', 'new_lane', 'new_file', 'new_test', 'reason', 'evidence'];++const unescapeField = (value: string) => value.replace(/\\(t|n|\\)/g, (_, c: string) => (c === 't' ? '\t' : c === 'n' ? '\n' : '\\'));+export const escapeField = (value: string) => value.replace(/\\/g, '\\\\').replace(/\t/g, '\\t').replace(/\n/g, '\\n');+const isTodo = (value: string) => !value.trim() || /^TODO\b/i.test(value.trim());++export function parseDeltas(text: string): { rows: DeltaRow[]; errors: string[] } {+ const rows: DeltaRow[] = [];+ const errors: string[] = [];+ let header = false;+ text.split('\n').forEach((raw, i) => {+ const line = i + 1;+ if (!raw.trim() || raw.startsWith('#')) return;+ const cells = raw.split('\t');+ if (!header) {+ if (cells.join('\t') !== DELTA_COLUMNS.join('\t')) errors.push(`line ${line}: header must be ${DELTA_COLUMNS.join(' ')}`);+ header = true;+ return;+ }+ if (cells.length !== DELTA_COLUMNS.length) {+ errors.push(`line ${line}: ${cells.length} columns, expected ${DELTA_COLUMNS.length} (tab-separated)`);+ return;+ }+ const [kind, lane, file, test, arm, newLane, newFile, newTest, reason, evidence] = cells.map(unescapeField);+ const row: DeltaRow = { line, kind: kind as DeltaKind, lane, file, test, arm, newLane, newFile, newTest, reason, evidence };+ if (!['retire', 'move', 'skip', 'job'].includes(kind)) errors.push(`line ${line}: kind "${kind}" is not retire, move, skip or job`);+ else if (isTodo(reason)) errors.push(`line ${line}: reason is empty or still TODO`);+ else if (kind === 'job' ? !lane : !lane || lane === '*' || !file || file === '*' || !test) errors.push(`line ${line}: ${kind === 'job' ? 'job rows name the artifact in the lane column' : 'lane and file must be exact; test is a name or *'}`);+ else if (kind === 'retire' && isTodo(evidence)) errors.push(`line ${line}: a retirement needs its Retiring-a-test evidence (docs/test-audit/.../implementation/<lane>.md#...)`);+ else if (kind === 'move' && !newLane && !newFile && !newTest) errors.push(`line ${line}: a move names new_lane, new_file or new_test`);+ else rows.push(row);+ });+ if (!header && text.trim()) errors.push('missing header row');+ return { rows, errors };+}++const globMatch = (pattern: string, value: string) =>+ new RegExp(`^${pattern.split('*').map(p => p.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`).test(value);++function rowMatches(row: DeltaRow, id: Identity): boolean {+ return row.kind !== 'job' && row.lane === id.lane && row.file === id.file+ && (row.test === '*' || row.test === id.test) && (row.arm === '*' || row.arm === id.arm);+}++export interface Drop { identity: Identity; head: Status | 'absent'; verdict: 'undeclared' | 'retired' | 'moved' | 'skipped' | 'lane-declared-empty' | 'move-target-missing' | 'skip-mismatch'; row?: DeltaRow; detail?: string }+export interface Comparison {+ ok: boolean;+ base?: Side;+ head: Side;+ drops: Drop[];+ additions: Identity[];+ issues: Issue[];+ deltaErrors: string[];+ unusedRows: DeltaRow[];+ suggestions: string[];+}++export function deltaRow(kind: DeltaKind, id: Pick<Identity, 'lane' | 'file' | 'test' | 'arm'>, target: { lane?: string; file?: string; test?: string } = {}): string {+ const evidence = kind === 'retire' ? 'TODO: docs/test-audit/2026-10-04/implementation/<lane>.md#<retiring-a-test row>' : '';+ return [kind, id.lane, id.file, id.test, id.arm, target.lane ?? '', target.file ?? '', target.test ?? '', 'TODO: why this test no longer runs here', evidence].map(escapeField).join('\t');+}++export function compare(head: Side, base: Side | undefined, deltas: { rows: DeltaRow[]; errors: string[] }, opts: { failOnAdditions?: boolean } = {}): Comparison {+ const result: Comparison = { ok: true, base, head, drops: [], additions: [], issues: [...(base?.issues.map(i => ({ ...i, detail: `base: ${i.detail}` })) ?? []), ...head.issues.map(i => ({ ...i, detail: base ? `head: ${i.detail}` : i.detail }))], deltaErrors: deltas.errors, unusedRows: [], suggestions: [] };+ const used = new Set<DeltaRow>();+ if (base) {+ for (const artifact of base.artifacts) {+ if (head.artifacts.has(artifact)) continue;+ const row = deltas.rows.find(r => r.kind === 'job' && globMatch(r.lane, artifact));+ if (row) used.add(row);+ else result.issues.push({ kind: 'missing-artifact', artifact, detail: `artifact ${artifact} is in base but not in head: its job did not run or uploaded nothing. Declare a removed or renamed job with a "job" row naming the artifact.` });+ }+ for (const id of base.identities.values()) {+ if (!executed(id.status)) continue;+ const now = head.identities.get(identityKey(id.lane, id.file, id.test, id.arm));+ if (executed(now?.status)) continue;+ const drop: Drop = { identity: id, head: now?.status ?? 'absent', verdict: 'undeclared' };+ const row = deltas.rows.find(r => rowMatches(r, id));+ if (row) {+ used.add(row);+ drop.row = row;+ if (row.kind === 'retire') drop.verdict = 'retired';+ else if (row.kind === 'skip') drop.verdict = now && !executed(now.status) ? 'skipped' : 'skip-mismatch';+ else {+ const target = identityKey(row.newLane || id.lane, row.newFile || id.file, row.test === '*' ? id.test : row.newTest || id.test, id.arm);+ drop.verdict = executed(head.identities.get(target)?.status) ? 'moved' : 'move-target-missing';+ if (drop.verdict === 'move-target-missing') drop.detail = `declared move target ${target.split('\u001f').join(' | ')} did not execute in head`;+ }+ } else if (head.lanes.get(id.lane)?.declaredEmpty) {+ drop.verdict = 'lane-declared-empty';+ }+ result.drops.push(drop);+ }+ const baseExecuted = new Set([...base.identities].filter(([, id]) => executed(id.status)).map(([key]) => key));+ result.additions = [...head.identities].filter(([key, id]) => executed(id.status) && !baseExecuted.has(key)).map(([, id]) => id);+ result.suggestions = suggestRows(result.drops.filter(d => d.verdict === 'undeclared'), base, head);+ }+ result.unusedRows = deltas.rows.filter(r => !used.has(r));+ const failing = result.drops.some(d => d.verdict === 'undeclared' || d.verdict === 'move-target-missing' || d.verdict === 'skip-mismatch');+ result.ok = !failing && !result.issues.length && !result.deltaErrors.length && !(opts.failOnAdditions && result.additions.length);+ return result;+}++/** The exact TSV rows that would declare each undeclared drop: a move when the test runs elsewhere in head, else a retirement. */+export function suggestRows(drops: Drop[], base: Side, head: Side): string[] {+ const rows: string[] = [];+ const headByTest = new Map<string, Identity[]>();+ for (const id of head.identities.values()) if (executed(id.status)) headByTest.set(id.test, [...(headByTest.get(id.test) ?? []), id]);+ const groups = new Map<string, Drop[]>();+ for (const d of drops) {+ const key = [d.identity.lane, d.identity.file, d.identity.arm].join('\u001f');+ groups.set(key, [...(groups.get(key) ?? []), d]);+ }+ for (const group of groups.values()) {+ const { lane, file, arm } = group[0].identity;+ const baseExecuted = [...base.identities.values()].filter(id => id.lane === lane && id.file === file && id.arm === arm && executed(id.status)).length;+ const headFileRuns = [...head.identities.values()].some(id => id.lane === lane && id.file === file && id.arm === arm && executed(id.status));+ const elsewhere = (d: Drop) => (headByTest.get(d.identity.test) ?? []).find(h => h.lane !== lane || h.file !== file);+ if (group.length === baseExecuted && !headFileRuns && group.length > 1) {+ const votes = new Map<string, number>();+ for (const d of group) {+ const h = elsewhere(d);+ if (h) votes.set(`${h.lane}\u001f${h.file}`, (votes.get(`${h.lane}\u001f${h.file}`) ?? 0) + 1);+ }+ const best = [...votes].sort((a, b) => b[1] - a[1])[0];+ if (best && best[1] * 2 >= group.length) {+ const [newLane, newFile] = best[0].split('\u001f');+ rows.push(deltaRow('move', { lane, file, test: '*', arm }, { lane: newLane === lane ? '' : newLane, file: newFile === file ? '' : newFile }));+ } else {+ rows.push(deltaRow('retire', { lane, file, test: '*', arm }));+ }+ continue;+ }+ for (const d of group) {+ const h = elsewhere(d);+ if (h) rows.push(deltaRow('move', d.identity, { lane: h.lane === lane ? '' : h.lane, file: h.file === file ? '' : h.file }));+ else if (d.head === 'skip' || d.head === 'todo') rows.push(deltaRow('skip', d.identity));+ else rows.push(deltaRow('retire', d.identity));+ }+ }+ return rows;+}++/** A9: skipped tests in files that read a provider key the run did not have. */+export function missingKeySkips(head: Side, keys: string[], root = '.'): { tests: number; files: string[] } {+ const files = new Map<string, number>();+ const reads = new Map<string, boolean>();+ for (const id of head.identities.values()) {+ if (executed(id.status) || id.file === 'verify') continue;+ if (!reads.has(id.file)) {+ let source = '';+ try { source = readFileSync(join(root, id.file), 'utf8'); } catch { /* deleted or out-of-tree file */ }+ reads.set(id.file, keys.some(k => source.includes(k)));+ }+ if (reads.get(id.file)) files.set(id.file, (files.get(id.file) ?? 0) + 1);+ }+ return { tests: [...files.values()].reduce((a, b) => a + b, 0), files: [...files.keys()].sort() };+}++const md = (value: string, max = 160) => {+ const text = value.length > max ? `${value.slice(0, max - 1)}…` : value;+ return text.replace(/[\r\n]+/g, ' ').replace(/([|`*_<>[\]\\])/g, '\\$1').replace(/@/g, '@\u200b');+};+const LIST_CAP = 200;++export function render(result: Comparison, extra: string[] = []): string {+ const out: string[] = [];+ const { base, head } = result;+ const verdict = result.ok ? 'PASS' : result.issues.length ? 'INCOMPLETE (fails)' : 'FAIL';+ out.push('## Executed-test identities (X2)', '');+ out.push(base ? `Base: ${md(base.label)} · Head: ${md(head.label)} · **${verdict}**` : `Head: ${md(head.label)} · **${verdict}**`, '');+ const lanes = [...new Set([...(base?.lanes.keys() ?? []), ...head.lanes.keys()])].sort();+ if (base) {+ out.push('| Lane | Base executed | Head executed | Head skipped | Head failed | Undeclared drops | Declared drops | Added |', '|---|---:|---:|---:|---:|---:|---:|---:|');+ for (const lane of lanes) {+ const b = base.lanes.get(lane);+ const h = head.lanes.get(lane);+ const drops = result.drops.filter(d => d.identity.lane === lane);+ const bad = drops.filter(d => d.verdict === 'undeclared' || d.verdict === 'move-target-missing' || d.verdict === 'skip-mismatch').length;+ out.push(`| ${md(lane)} | ${b?.executed ?? 0} | ${h?.executed ?? 0} | ${h?.skipped ?? 0} | ${h?.failed ?? 0} | ${bad} | ${drops.length - bad} | ${result.additions.filter(a => a.lane === lane).length} |`);+ }+ } else {+ out.push('| Lane | Files | Executed | Passed | Failed | Skipped | Superseded by rerun/rescue |', '|---|---:|---:|---:|---:|---:|---:|');+ for (const lane of lanes) {+ const h = head.lanes.get(lane)!;+ out.push(`| ${md(lane)}${h.declaredEmpty ? ' (declared empty)' : ''} | ${h.files} | ${h.executed} | ${h.passed} | ${h.failed} | ${h.skipped} | ${h.superseded} |`);+ }+ }+ out.push('');+ out.push(...extra);+ if (result.issues.length) {+ out.push(`### Incomplete (${result.issues.length})`, '', 'Why: a lane without a complete receipt cannot prove which tests ran, so the comparison fails closed.', 'Fix: rerun every job of the run (not only failed jobs) so each lane uploads a receipt from one attempt; a killed shard needs its rescue or a rerun.', DOCS, '');+ for (const issue of result.issues.slice(0, LIST_CAP)) out.push(`- ${md(issue.detail, 400)}`);+ if (result.issues.length > LIST_CAP) out.push(`- … ${result.issues.length - LIST_CAP} more (see --json)`);+ out.push('');+ }+ if (result.deltaErrors.length) {+ out.push(`### expected-deltas.tsv errors (${result.deltaErrors.length})`, '');+ for (const e of result.deltaErrors) out.push(`- ${md(e, 300)}`);+ out.push('');+ }+ const bad = result.drops.filter(d => d.verdict === 'undeclared' || d.verdict === 'move-target-missing' || d.verdict === 'skip-mismatch');+ if (bad.length) {+ out.push(`### Dropped identities (${bad.length})`, '', 'Why: these base tests no longer execute in head and expected-deltas.tsv does not account for them.', `Fix: restore the tests, or add the rows below to ${DEFAULT_DELTAS} with a real reason (retirements also need their Retiring-a-test evidence).`, DOCS, '');+ for (const d of bad.slice(0, LIST_CAP)) out.push(`- ${md(d.identity.lane)} · ${md(d.identity.file)} · ${md(d.identity.test)}${d.identity.arm ? ` · ${md(d.identity.arm)}` : ''} — head: ${d.head}${d.verdict === 'undeclared' ? '' : ` (${d.verdict}${d.detail ? `: ${md(d.detail, 200)}` : ''})`}`);+ if (bad.length > LIST_CAP) out.push(`- … ${bad.length - LIST_CAP} more (see --json)`);+ if (result.suggestions.length) out.push('', 'Rows to declare them:', '', '```tsv', ...result.suggestions.slice(0, LIST_CAP), '```');+ out.push('');+ }+ const declared = result.drops.length - bad.length;+ if (declared) out.push(`Declared drops: ${declared} (${['retired', 'moved', 'skipped', 'lane-declared-empty'].map(v => `${v} ${result.drops.filter(d => d.verdict === v).length}`).join(', ')}).`, '');+ if (base) out.push(`Added identities (new tests need no declaration): ${result.additions.length}.`, '');+ if (head.overlaps.length) {+ out.push(`Files that ran in more than one primary invocation in head (sharding overlap; the latest attempt counts): ${head.overlaps.length}.`, '');+ for (const o of head.overlaps.slice(0, 20)) out.push(`- ${md(o, 300)}`);+ out.push('');+ }+ if (head.duplicates.length) out.push(`Repeated test names in head (numbered by occurrence, e.g. test.each titles): ${head.duplicates.length}.`, '');+ if (result.unusedRows.length) out.push(`expected-deltas.tsv rows that matched nothing: ${result.unusedRows.map(r => `line ${r.line}`).join(', ')}.`, '');+ if (head.shas.size > 1) out.push(`Head receipts come from ${head.shas.size} commits: ${[...head.shas].map(s => s.slice(0, 12)).join(', ')}.`, '');+ return `${out.join('\n')}\n`;+}++export function toJSON(result: Comparison): unknown {+ const side = (s: Side) => ({ label: s.label, artifacts: [...s.artifacts].sort(), shas: [...s.shas], lanes: [...s.lanes.values()], identities: [...s.identities.values()], duplicates: s.duplicates.length, overlaps: s.overlaps });+ return {+ ok: result.ok,+ base: result.base ? side(result.base) : null,+ head: side(result.head),+ issues: result.issues,+ deltaErrors: result.deltaErrors,+ drops: result.drops.map(d => ({ ...d.identity, head: d.head, verdict: d.verdict, row: d.row?.line, detail: d.detail })),+ additions: result.additions,+ suggestions: result.suggestions,+ unusedRows: result.unusedRows.map(r => r.line),+ };+}++class UsageError extends Error {}++function gh(args: string[]): string {+ const r = spawnSync('gh', args, { encoding: 'utf8' });+ if (r.error || r.status !== 0) {+ throw new UsageError(`gh ${args.join(' ')} failed: ${(r.stderr || r.error?.message || '').trim()}\nWhy: run artifacts are read through the GitHub CLI.\nFix: gh auth status (a token with actions:read), and check the run id exists in the repo.`);+ }+ return r.stdout;+}++/** Download a run's receipts-* artifacts; returns the receipts and the run's latest attempt. */+export function downloadRun(repo: string, runId: string, into: string): { receipts: Receipt[]; attempt: number; label: string } {+ if (!/^\d+$/.test(runId)) throw new UsageError(`run id "${runId}" is not numeric`);+ const run = JSON.parse(gh(['api', `repos/${repo}/actions/runs/${runId}`, '--jq', '{attempt: .run_attempt, sha: .head_sha, status: .status, name: .name, event: .event}']));+ if (run.status !== 'completed') throw new UsageError(`run ${runId} is ${run.status}\nWhy: a running workflow has not uploaded every receipt yet.\nFix: wait for it to finish (gh run watch ${runId} --repo ${repo}).`);+ const dir = join(into, runId);+ gh(['run', 'download', runId, '--repo', repo, '--pattern', 'receipts-*', '--dir', dir]);+ const receipts = existsSync(dir) ? loadReceiptDir(dir) : [];+ if (!receipts.length) throw new UsageError(`run ${runId} has no receipts-* artifacts\nWhy: the run predates executed-test receipts, or its upload steps did not run.\nFix: re-run the workflow on a commit whose test.yml/e2e.yml upload receipts.`);+ return { receipts, attempt: Number(run.attempt), label: `${run.name} #${runId} (${run.event}, ${String(run.sha).slice(0, 12)}, attempt ${run.attempt})` };+}++interface Args { baseRuns: string[]; headRuns: string[]; baseDirs: string[]; headDirs: string[]; deltas?: string; summary?: string; json?: string; reportOnly: boolean; failOnAdditions: boolean; expect: Map<string, number>; missingKeys?: string[]; repo: string }++export function parseArgs(argv: string[]): Args {+ const args: Args = { baseRuns: [], headRuns: [], baseDirs: [], headDirs: [], reportOnly: false, failOnAdditions: false, expect: new Map(), repo: process.env.GITHUB_REPOSITORY || 'garrytan/gbrain' };+ for (let i = 0; i < argv.length; i++) {+ const flag = argv[i];+ const value = () => {+ const v = argv[++i];+ if (v === undefined || v.startsWith('--')) throw new UsageError(`${flag} needs a value`);+ return v;+ };+ const list = () => value().split(',').map(s => s.trim()).filter(Boolean);+ switch (flag) {+ case '--base-run': args.baseRuns.push(...list()); break;+ case '--head-run': args.headRuns.push(...list()); break;+ case '--base-dir': args.baseDirs.push(value()); break;+ case '--head-dir': args.headDirs.push(value()); break;+ case '--deltas': args.deltas = value(); break;+ case '--summary': args.summary = value(); break;+ case '--json': args.json = value(); break;+ case '--repo': args.repo = value(); break;+ case '--report-only': args.reportOnly = true; break;+ case '--fail-on-additions': args.failOnAdditions = true; break;+ case '--missing-keys': args.missingKeys = list(); break;+ case '--expect-attempt': {+ const m = /^(\d+):(\d+)$/.exec(value());+ if (!m) throw new UsageError('--expect-attempt takes <run-id>:<attempt>');+ args.expect.set(m[1], Number(m[2]));+ break;+ }+ case '--help': case '-h': throw new UsageError('help');+ default: throw new UsageError(`unknown option ${flag}`);+ }+ }+ if (!args.headRuns.length && !args.headDirs.length) throw new UsageError('pass --head-run <id> or --head-dir <dir>');+ return args;+}++function loadSide(runs: string[], dirs: string[], args: Args, into: string): Side | undefined {+ if (!runs.length && !dirs.length) return undefined;+ const receipts: Receipt[] = [];+ const expect = new Map(args.expect);+ const labels: string[] = [];+ for (const run of runs) {+ const got = downloadRun(args.repo, run, into);+ receipts.push(...got.receipts);+ expect.set(run, got.attempt);+ labels.push(got.label);+ }+ for (const dir of dirs) {+ if (!existsSync(dir)) throw new UsageError(`receipt directory ${dir} does not exist`);+ receipts.push(...loadReceiptDir(dir));+ labels.push(dir);+ }+ const seen = new Map<string, string>();+ for (const r of receipts) {+ const key = `${r.artifact}/${r.id}`;+ const source = r.runId || 'local';+ if (seen.has(key) && seen.get(key) !== source) throw new UsageError(`artifact ${r.artifact} appears in two runs of one side; pass one test.yml run and one e2e.yml run per side`);+ seen.set(key, source);+ }+ return buildSide(labels.join(' + '), receipts, expect);+}++export function main(argv: string[]): number {+ let args: Args;+ try {+ args = parseArgs(argv);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (message !== 'help') console.error(`ci-executed-counts: ${message}`);+ console.error('usage: bun scripts/ci-executed-counts.ts (--head-run <id>[,<id>] | --head-dir <dir>) [--base-run <id>[,<id>] | --base-dir <dir>] [--deltas <tsv>] [--summary <file>] [--json <file>] [--report-only] [--fail-on-additions] [--expect-attempt <run>:<n>] [--missing-keys K1,K2] [--repo owner/name]');+ return message === 'help' ? 0 : 2;+ }+ try {+ const scratch = mkdtempSync(join(tmpdir(), 'gbrain-receipts-'));+ const head = loadSide(args.headRuns, args.headDirs, args, scratch)!;+ const base = loadSide(args.baseRuns, args.baseDirs, args, scratch);+ const deltasPath = args.deltas ?? (existsSync(DEFAULT_DELTAS) ? DEFAULT_DELTAS : undefined);+ const deltas = deltasPath ? parseDeltas(readFileSync(deltasPath, 'utf8')) : { rows: [], errors: [] };+ const result = compare(head, base, deltas, { failOnAdditions: args.failOnAdditions });+ const extra: string[] = [];+ if (args.missingKeys) {+ const keys = args.missingKeys;+ if (keys.length) {+ const skipped = missingKeySkips(head, keys);+ const listed = skipped.files.slice(0, 20).map(f => md(f)).join(', ') + (skipped.files.length > 20 ? ', …' : '');+ extra.push(`**${skipped.tests} tests skipped for missing keys**: skipped tests in ${skipped.files.length} file(s) that read ${keys.join(' or ')}, which at least one lane ran without${skipped.files.length ? ` (${listed})` : ''}.`, '');+ } else {+ extra.push('**0 tests skipped for missing keys** (every provider key was set).', '');+ }+ }+ const text = render(result, extra);+ process.stdout.write(text);+ if (args.summary) appendFileSync(args.summary, text);+ if (args.json) writeFileSync(args.json, `${JSON.stringify(toJSON(result), null, 2)}\n`);+ return result.ok || args.reportOnly ? 0 : 1;+ } catch (error) {+ console.error(`ci-executed-counts: ${error instanceof Error ? error.message : String(error)}`);+ console.error(DOCS);+ return 2;+ }+}++if (import.meta.main) process.exitCode = main(process.argv.slice(2));diff --git a/test/scripts/ci-executed-counts.test.ts b/test/scripts/ci-executed-counts.test.tsnew file mode 100644index 0000000000..4ece08f135--- /dev/null+++ b/test/scripts/ci-executed-counts.test.ts@@ -0,0 +1,284 @@+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawnSync } from 'node:child_process';+import {+ buildSide, compare, loadReceiptDir, parseDeltas, parseJUnit, missingKeySkips, canonicalTestName,+ DELTA_COLUMNS, JUnitError,+} from '../../scripts/ci-executed-counts.ts';++const REPO = join(import.meta.dir, '../..');+const HEADER = DELTA_COLUMNS.join('\t');++type Case = { file: string; name: string; describe?: string[]; status?: 'pass' | 'fail' | 'skip' | 'todo' };++/** Bun-shaped JUnit: one file-level testsuite per file, nested describe suites. */+function junit(cases: Case[]): string {+ const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');+ const files = [...new Set(cases.map(c => c.file))];+ const body = files.map(file => {+ const inner = cases.filter(c => c.file === file).map(c => {+ const child = c.status === 'fail' ? '<failure type="AssertionError" message="boom" />'+ : c.status === 'skip' ? '<skipped />' : c.status === 'todo' ? '<skipped message="TODO" />' : '';+ let xml = `<testcase name="${esc(c.name)}" classname="" file="${file}">${child}</testcase>`;+ for (const d of [...(c.describe ?? [])].reverse()) xml = `<testsuite name="${esc(d)}" file="${file}">${xml}</testsuite>`;+ return xml;+ }).join('\n');+ return ` <testsuite name="${file}" file="${file}">\n${inner}\n </testsuite>`;+ }).join('\n');+ return `<?xml version="1.0" encoding="UTF-8"?>\n<testsuites name="bun test" tests="${cases.length}">\n${body}\n</testsuites>\n`;+}++let root: string;+beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'gbrain-x2-')); });+afterEach(() => { rmSync(root, { recursive: true, force: true }); });++interface ReceiptSpec {+ artifact: string; id: string; lane?: string; kind?: string; shard?: number; of?: number; arm?: string;+ files: string[]; cases?: Case[]; junit?: string | null; exit?: number | null; runId?: string; attempt?: number; started?: number;+ extra?: string[];+}+function writeReceipt(side: string, spec: ReceiptSpec): void {+ const dir = join(root, side, spec.artifact);+ mkdirSync(dir, { recursive: true });+ const meta = [+ 'version=1', `lane=${spec.lane ?? 'unit'}`, `kind=${spec.kind ?? 'primary'}`, `tag=${spec.id}`,+ `shard=${spec.shard ?? ''}`, `of=${spec.of ?? ''}`, `arm=${spec.arm ?? ''}`, 'sha=abc123', `root=/repo`,+ `run_id=${spec.runId ?? ''}`, `run_attempt=${spec.attempt ?? ''}`, 'job=test', `started=${spec.started ?? 100}`,+ ...(spec.extra ?? []),+ ];+ if (spec.exit !== null) meta.push(`exit=${spec.exit ?? 0}`);+ writeFileSync(join(dir, `${spec.id}.receipt`), `${meta.join('\n')}\n`);+ writeFileSync(join(dir, `${spec.id}.files`), spec.files.map(f => `${f}\n`).join(''));+ if (spec.junit !== null) writeFileSync(join(dir, `${spec.id}.junit.xml`), spec.junit ?? junit(spec.cases ?? []));+}+const side = (name: string, expect?: Map<string, number>) => buildSide(name, loadReceiptDir(join(root, name)), expect);+const noDeltas = { rows: [], errors: [] };++const A: Case = { file: 'test/a.test.ts', name: 'adds', describe: ['math'] };+const B: Case = { file: 'test/a.test.ts', name: 'subtracts', describe: ['math'] };+const C: Case = { file: 'test/a.test.ts', name: 'multiplies', describe: ['math'] };++describe('parseJUnit', () => {+ test('reads Bun nesting, skips, todos and failures as one identity per testcase', () => {+ const cases = parseJUnit(junit([+ { file: 'test/x.test.ts', name: 'ok', describe: ['outer', 'inner'] },+ { file: 'test/x.test.ts', name: 'later', status: 'skip' },+ { file: 'test/x.test.ts', name: 'planned', status: 'todo' },+ { file: 'test/y.test.ts', name: 'broken', status: 'fail' },+ ]));+ expect(cases).toEqual([+ { file: 'test/x.test.ts', test: 'outer > inner > ok', status: 'pass' },+ { file: 'test/x.test.ts', test: 'later', status: 'skip' },+ { file: 'test/x.test.ts', test: 'planned', status: 'todo' },+ { file: 'test/y.test.ts', test: 'broken', status: 'fail' },+ ]);+ });++ test('a truncated or miscounted report throws instead of reading as fewer tests', () => {+ const full = junit([A, B]);+ expect(() => parseJUnit(full.slice(0, full.indexOf('subtracts')))).toThrow(JUnitError);+ expect(() => parseJUnit(full.replace('</testsuites>', ''))).toThrow(/truncated/);+ expect(() => parseJUnit(full.replace('tests="2"', 'tests="3"'))).toThrow(/declares 3 tests/);+ });++ test('unstable fragments canonicalize so reruns keep one identity; fixed dates stay', () => {+ expect(canonicalTestName('writes /tmp/gbrain-x-AbC123/out as 3f2b1c4d-1111-2222-3333-444455556666 on 2026-10-04T10:00:00Z'))+ .toBe('writes <tmp> as <uuid> on 2026-10-04T10:00:00Z');+ });++ test('repeated names in one file (test.each templates) stay distinct identities by occurrence', () => {+ const each = (status?: 'skip'): Case => ({ file: 'test/a.test.ts', name: 'case %s', status });+ writeReceipt('base', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [each(), each(), each()] });+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [each(), each()] });+ expect([...side('base').identities.values()].map(i => i.test)).toEqual(['case %s', 'case %s [#2]', 'case %s [#3]']);+ expect(compare(side('head'), side('base'), noDeltas).drops.map(d => d.identity.test)).toEqual(['case %s [#3]']);+ });+});++describe('identity comparison', () => {+ test('identical identity sets pass', () => {+ for (const s of ['base', 'head']) writeReceipt(s, { artifact: 'receipts-unit-1', id: 'u1', shard: 1, of: 1, files: ['test/a.test.ts'], cases: [A, B] });+ const result = compare(side('head'), side('base'), noDeltas);+ expect(result.issues).toEqual([]);+ expect(result.ok).toBe(true);+ });++ test('an equal-count substitution fails and prints the row that would declare the dropped test', () => {+ writeReceipt('base', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [A, B] });+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [A, C] });+ const result = compare(side('head'), side('base'), noDeltas);+ expect(result.ok).toBe(false);+ expect(result.drops.map(d => [d.identity.test, d.verdict])).toEqual([['math > subtracts', 'undeclared']]);+ expect(result.additions.map(a => a.test)).toEqual(['math > multiplies']);+ expect(result.suggestions).toEqual([+ ['retire', 'unit', 'test/a.test.ts', 'math > subtracts', '', '', '', '', 'TODO: why this test no longer runs here', 'TODO: docs/test-audit/2026-10-04/implementation/<lane>.md#<retiring-a-test row>'].join('\t'),+ ]);+ });++ test('a declared file-level move passes only when the tests execute at the new location', () => {+ const moved = (file: string): Case[] => [A, B].map(c => ({ ...c, file }));+ writeReceipt('base', { artifact: 'receipts-serial-1', id: 's1', lane: 'serial', files: ['test/a.serial.test.ts'], cases: moved('test/a.serial.test.ts') });+ writeReceipt('head', { artifact: 'receipts-serial-1', id: 's1', lane: 'serial', files: [], cases: [] , extra: ['empty=1'], junit: null });+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: moved('test/a.test.ts') });+ const undeclared = compare(side('head'), side('base'), noDeltas);+ expect(undeclared.ok).toBe(false);+ expect(undeclared.suggestions).toEqual([['move', 'serial', 'test/a.serial.test.ts', '*', '', 'unit', 'test/a.test.ts', '', 'TODO: why this test no longer runs here', ''].join('\t')]);+ const row = ['move', 'serial', 'test/a.serial.test.ts', '*', '', 'unit', 'test/a.test.ts', '', 'D6: isolation check proved the file parallel-safe', ''].join('\t');+ const declared = compare(side('head'), side('base'), parseDeltas(`${HEADER}\n${row}\n`));+ expect(declared.drops.map(d => d.verdict)).toEqual(['moved', 'moved']);+ expect(declared.ok).toBe(true);+ const wrongTarget = row.replace('unit\ttest/a.test.ts', 'unit\ttest/elsewhere.test.ts');+ const missing = compare(side('head'), side('base'), parseDeltas(`${HEADER}\n${wrongTarget}\n`));+ expect(missing.ok).toBe(false);+ expect(missing.drops[0].verdict).toBe('move-target-missing');+ });++ test('a retirement passes with its evidence row and is refused without one', () => {+ writeReceipt('base', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [A, B] });+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [A] });+ const row = (evidence: string) => ['retire', 'unit', 'test/a.test.ts', 'math > subtracts', '', '', '', '', 'pinned an abandoned contract', evidence].join('\t');+ const retired = compare(side('head'), side('base'), parseDeltas(`${HEADER}\n${row('docs/test-audit/2026-10-04/implementation/s3.md#subtracts')}\n`));+ expect(retired.drops[0].verdict).toBe('retired');+ expect(retired.ok).toBe(true);+ const noEvidence = parseDeltas(`${HEADER}\n${row('TODO')}\n`);+ expect(noEvidence.errors[0]).toContain('Retiring-a-test evidence');+ expect(compare(side('head'), side('base'), noEvidence).ok).toBe(false);+ });++ test('a declared pass-to-skip passes only while head reports the test skipped', () => {+ writeReceipt('base', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [A, B] });+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [A, { ...B, status: 'skip' }] });+ const row = ['skip', 'unit', 'test/a.test.ts', 'math > subtracts', '', '', '', '', 'D14: covered by the e2e arm', ''].join('\t');+ expect(compare(side('head'), side('base'), parseDeltas(`${HEADER}\n${row}\n`)).ok).toBe(true);+ expect(compare(side('head'), side('base'), noDeltas).suggestions[0].startsWith('skip\t')).toBe(true);+ });++ test('backend arms of one file are separate identities', () => {+ for (const arm of ['postgres-direct', 'pgbouncer']) {+ writeReceipt('base', { artifact: 'receipts-tier1', id: `m-${arm}`, lane: 'backend-matrix', arm, files: ['test/e2e/m.test.ts'], cases: [{ file: 'test/e2e/m.test.ts', name: 'binds' }] });+ }+ writeReceipt('head', { artifact: 'receipts-tier1', id: 'm-postgres-direct', lane: 'backend-matrix', arm: 'postgres-direct', files: ['test/e2e/m.test.ts'], cases: [{ file: 'test/e2e/m.test.ts', name: 'binds' }] });+ const result = compare(side('head'), side('base'), noDeltas);+ expect(side('base').identities.size).toBe(2);+ expect(result.drops.map(d => d.identity.arm)).toEqual(['pgbouncer']);+ });++ test('a base artifact missing from head fails unless a job row declares it', () => {+ writeReceipt('base', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [A] });+ writeReceipt('base', { artifact: 'receipts-slow-eval', id: 'e1', lane: 'slow', files: ['test/e.slow.test.ts'], cases: [{ file: 'test/e.slow.test.ts', name: 'evals' }] });+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts', 'test/e.slow.test.ts'], cases: [A, { file: 'test/e.slow.test.ts', name: 'evals' }] });+ const moveRow = ['move', 'slow', 'test/e.slow.test.ts', '*', '', 'unit', '', '', 'B10: the 5s file rides the unit matrix', ''].join('\t');+ const missing = compare(side('head'), side('base'), parseDeltas(`${HEADER}\n${moveRow}\n`));+ expect(missing.issues.map(i => i.kind)).toEqual(['missing-artifact']);+ expect(missing.ok).toBe(false);+ const jobRow = ['job', 'receipts-slow-*', '', '', '', '', '', '', 'B10: slow-eval job removed', ''].join('\t');+ expect(compare(side('head'), side('base'), parseDeltas(`${HEADER}\n${moveRow}\n${jobRow}\n`)).ok).toBe(true);+ });+});++describe('completeness', () => {+ test('a killed shard re-run by its rescue is complete and reports the rescue result', () => {+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', shard: 1, of: 1, files: ['test/a.test.ts', 'test/b.test.ts'], junit: null, exit: null });+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'rescue', kind: 'rescue', started: 200, files: ['test/a.test.ts', 'test/b.test.ts'], cases: [A, { file: 'test/b.test.ts', name: 'b' }] });+ const head = side('head');+ expect(head.issues).toEqual([]);+ expect(head.lanes.get('unit')).toMatchObject({ executed: 2, superseded: 2 });+ expect(compare(head, undefined, noDeltas).ok).toBe(true);+ });++ test('a rescue supersedes the failing primary for the files it re-ran', () => {+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [{ ...A, status: 'fail' }] });+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'rescue', kind: 'rescue', files: ['test/a.test.ts'], cases: [A] });+ expect([...side('head').identities.values()].map(i => i.status)).toEqual(['pass']);+ });++ test('a killed shard without a rescue is incomplete and names the attempt', () => {+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', shard: 1, of: 1, files: ['test/a.test.ts'], junit: null, exit: null });+ const result = compare(side('head'), undefined, noDeltas);+ expect(result.ok).toBe(false);+ expect(result.issues[0].detail).toContain('test/a.test.ts has no valid receipt from any attempt');+ expect(result.issues[0].detail).toContain('interrupted');+ });++ test('a truncated JUnit report is incomplete', () => {+ const cut = junit([A, B]);+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], junit: cut.slice(0, cut.length - 30), exit: 1 });+ const result = compare(side('head'), undefined, noDeltas);+ expect(result.ok).toBe(false);+ expect(result.issues[0].detail).toContain('truncated JUnit');+ });++ test('a receipt from an earlier run attempt is incomplete, not silently mixed in', () => {+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', runId: '42', attempt: 1, files: ['test/a.test.ts'], cases: [A] });+ writeReceipt('head', { artifact: 'receipts-unit-2', id: 'u2', runId: '42', attempt: 2, files: ['test/b.test.ts'], cases: [{ file: 'test/b.test.ts', name: 'b' }] });+ const result = compare(side('head'), undefined, noDeltas);+ expect(result.issues.map(i => i.kind)).toEqual(['prior-attempt']);+ expect(result.issues[0].detail).toContain('attempt 1 of run 42');+ const expected = side('head', new Map([['42', 3]]));+ expect(expected.issues.filter(i => i.kind === 'prior-attempt')).toHaveLength(2);+ });++ test('a missing shard and a lane that executed nothing are incomplete; empty assignments are not', () => {+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', shard: 1, of: 3, files: ['test/a.test.ts'], cases: [A] });+ writeReceipt('head', { artifact: 'receipts-unit-3', id: 'u3', shard: 3, of: 3, files: [], junit: null, extra: ['empty=1'] });+ writeReceipt('head', { artifact: 'receipts-slow', id: 's', lane: 'slow', files: ['test/s.slow.test.ts'], cases: [{ file: 'test/s.slow.test.ts', name: 'gated', status: 'skip' }] });+ const kinds = side('head').issues.map(i => i.kind).sort();+ expect(kinds).toEqual(['empty-lane', 'missing-shard']);+ });++ test('drops in a lane declared empty (doc-only E2E selection) are reported, not failed', () => {+ writeReceipt('base', { artifact: 'receipts-e2e-1', id: 'e', lane: 'e2e', files: ['test/e2e/x.test.ts'], cases: [{ file: 'test/e2e/x.test.ts', name: 'x' }] });+ writeReceipt('head', { artifact: 'receipts-e2e-1', id: 'e', lane: 'e2e', files: [], junit: null, extra: ['declared_empty=1'] });+ const result = compare(side('head'), side('base'), noDeltas);+ expect(result.drops[0].verdict).toBe('lane-declared-empty');+ expect(result.ok).toBe(true);+ });+});++describe('missing-key skip count (A9)', () => {+ test('counts skipped tests only in files that read a missing key', () => {+ mkdirSync(join(root, 'src/test/e2e'), { recursive: true });+ writeFileSync(join(root, 'src/test/e2e/live.test.ts'), 'const k = process.env.OPENAI_API_KEY;');+ writeFileSync(join(root, 'src/test/e2e/plain.test.ts'), 'export {};');+ writeReceipt('head', { artifact: 'receipts-e2e-1', id: 'e', lane: 'e2e', files: ['test/e2e/live.test.ts', 'test/e2e/plain.test.ts'], cases: [+ { file: 'test/e2e/live.test.ts', name: 'embeds', status: 'skip' },+ { file: 'test/e2e/live.test.ts', name: 'chats', status: 'skip' },+ { file: 'test/e2e/live.test.ts', name: 'offline' },+ { file: 'test/e2e/plain.test.ts', name: 'optional', status: 'skip' },+ ] });+ expect(missingKeySkips(side('head'), ['OPENAI_API_KEY'], join(root, 'src'))).toEqual({ tests: 2, files: ['test/e2e/live.test.ts'] });+ });+});++describe('CLI', () => {+ const cli = (...args: string[]) => spawnSync('bun', ['scripts/ci-executed-counts.ts', ...args], { cwd: REPO, encoding: 'utf8' });++ test('local directories: exit 1 on an undeclared drop with the row to add, 0 when identical, 2 on usage errors', () => {+ writeReceipt('base', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [A, B] });+ writeReceipt('head', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [A, C] });+ const deltas = join(root, 'deltas.tsv');+ writeFileSync(deltas, `${HEADER}\n`);+ const summary = join(root, 'summary.md');+ const json = join(root, 'out.json');+ const fail = cli('--base-dir', join(root, 'base'), '--head-dir', join(root, 'head'), '--deltas', deltas, '--summary', summary, '--json', json);+ expect(fail.status, fail.stderr).toBe(1);+ expect(fail.stdout).toContain('retire\tunit\ttest/a.test.ts\tmath > subtracts');+ expect(readFileSync(summary, 'utf8')).toContain('| unit | 2 | 2 | 0 | 0 | 1 | 0 | 1 |');+ expect(JSON.parse(readFileSync(json, 'utf8')).drops).toHaveLength(1);+ expect(cli('--base-dir', join(root, 'base'), '--head-dir', join(root, 'head'), '--deltas', deltas, '--report-only').status).toBe(0);+ expect(cli('--base-dir', join(root, 'base'), '--head-dir', join(root, 'base'), '--deltas', deltas).status).toBe(0);+ writeReceipt('grown', { artifact: 'receipts-unit-1', id: 'u1', files: ['test/a.test.ts'], cases: [A, B, C] });+ expect(cli('--base-dir', join(root, 'base'), '--head-dir', join(root, 'grown'), '--deltas', deltas).status).toBe(0);+ expect(cli('--base-dir', join(root, 'base'), '--head-dir', join(root, 'grown'), '--deltas', deltas, '--fail-on-additions').status).toBe(1);+ const usage = cli('--base-run', '1');+ expect(usage.status).toBe(2);+ expect(usage.stderr).toContain('--head-run');+ });++ test('the committed expected-deltas.tsv parses', () => {+ const parsed = parseDeltas(readFileSync(join(REPO, 'docs/test-audit/2026-10-04/expected-deltas.tsv'), 'utf8'));+ expect(parsed.errors).toEqual([]);+ });+});diff --git a/test/scripts/run-unit-parallel.test.ts b/test/scripts/run-unit-parallel.test.tsindex 8a13081c3b..81df40a090 100644--- a/test/scripts/run-unit-parallel.test.ts+++ b/test/scripts/run-unit-parallel.test.ts@@ -24,6 +24,7 @@ import { execFileSync, spawn, spawnSync } from 'child_process';import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, copyFileSync, chmodSync, symlinkSync } from 'fs';import { tmpdir } from 'os';import { dirname, join, resolve } from 'path';+import { buildSide, loadReceiptDir } from '../../scripts/ci-executed-counts.ts';const REPO_ROOT = resolve(import.meta.dir, '..', '..');const PARALLEL_SH_SRC = resolve(REPO_ROOT, 'scripts/run-unit-parallel.sh');@@ -403,6 +404,18 @@ describe('oom-once', () => {expect(r.code).toBe(0);}, 120_000);+ it('writes a receipt per bun invocation; the rescue receipt supersedes the phantom failure (X2)', () => {+ const r = runOom();+ expect(r.code).toBe(0);+ const dir = join(OROOT, '.context', 'test-receipts');+ const receipts = loadReceiptDir(dir);+ expect(receipts.filter(x => x.kind === 'rescue').map(x => [x.lane, x.files])).toEqual([['unit', ['test/b-oom-once.test.ts']]]);+ expect(receipts.filter(x => x.kind === 'primary' && x.lane === 'unit').map(x => x.files[0]).sort()).toEqual(['test/a-pass.test.ts', 'test/b-oom-once.test.ts']);+ const side = buildSide('local', receipts);+ expect(side.issues).toEqual([]);+ expect(side.lanes.get('unit')).toMatchObject({ executed: 2, failed: 0, superseded: 1 });+ }, 120_000);+it('GBRAIN_TEST_NO_OOM_FALLBACK=1 disables the rescue lane (stays red)', () => {const r = runOom({ GBRAIN_TEST_NO_OOM_FALLBACK: '1' });expect(r.code).not.toBe(0);