Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.58.1.0 test: reduce duplicated fixtures and shard full E2E coverage (#5454)

Garry Tan46ad5153a362
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 4ba72c8633..72a9836a26 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.58.0.0",
+ "version": "0.58.1.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 621738d0bb..4d95728b37 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.58.0.0",
+ "version": "0.58.1.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 84fafb859d..0d5362836f 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -8,6 +8,11 @@ on:
schedule:
- cron: '0 6 * * *' # Nightly at 6am UTC
workflow_dispatch:
+ inputs:
+ full_corpus:
+ description: Run the complete scheduled coverage profile
+ type: boolean
+ default: false
permissions:
contents: read
@@ -16,7 +21,7 @@ permissions:
# PR number for pull_request events (fork-safe), github.ref fallback for
# push/scheduled runs.
concurrency:
- group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event_name == 'workflow_dispatch' && inputs.full_corpus && '-full-corpus' || '' }}
cancel-in-progress: true
jobs:
@@ -117,9 +122,11 @@ jobs:
- name: Select and freeze E2E files
id: select
shell: bash
+ env:
+ FULL_CORPUS: ${{ github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus) }}
run: |
- if [ "${{ github.event_name }}" = "schedule" ]; then
- # Nightly coverage carries the full E2E corpus separately.
+ if [ "$FULL_CORPUS" = "true" ]; then
+ # Full-profile coverage carries the complete E2E corpus separately.
: > "$RUNNER_TEMP/selected.txt"
else
git fetch origin master --quiet
@@ -417,16 +424,16 @@ jobs:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
# ──────────────────────────────────────────────────────────────────────
- # Nightly coverage-full pipeline (schedule-only). The honest
+ # Full coverage pipeline (scheduled or explicitly dispatched). The honest
# "unit + serial + E2E merged" number the containment sprint mandates:
# every lane runs WITH coverage inside THIS workflow (no cross-workflow
# artifact fetch — that channel is racy by construction), then one merge
# job compares against the fullCorpus baseline and uploads the trend
- # artifact. PR runs never pay this cost; the schedule gate on every job
+ # artifact. PR runs never pay this cost; the full-profile gate on every job
# below is load-bearing.
# ──────────────────────────────────────────────────────────────────────
coverage-full-unit:
- if: github.event_name == 'schedule'
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)
runs-on: ubicloud-standard-16-ubuntu-2404
timeout-minutes: 30
strategy:
@@ -454,7 +461,7 @@ jobs:
overwrite: true
coverage-full-serial:
- if: github.event_name == 'schedule'
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)
runs-on: ubicloud-standard-16-ubuntu-2404
timeout-minutes: 30
steps:
@@ -477,7 +484,7 @@ jobs:
overwrite: true
coverage-full-slow:
- if: github.event_name == 'schedule'
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)
runs-on: ubicloud-standard-16-ubuntu-2404
timeout-minutes: 25
steps:
@@ -507,9 +514,13 @@ jobs:
overwrite: true
coverage-full-e2e:
- if: github.event_name == 'schedule'
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)
runs-on: ubicloud-standard-16-ubuntu-2404
timeout-minutes: 60
+ strategy:
+ fail-fast: false
+ matrix:
+ shard: [1, 2, 3, 4]
services:
postgres:
image: pgvector/pgvector:pg16
@@ -536,13 +547,30 @@ jobs:
test/fixtures/pglite-snapshot.version
key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/company-brain/receipt-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- - name: Full e2e glob with coverage (all files, incl. engine-parity)
+ - name: Bootstrap isolated E2E schema
+ shell: bash
+ run: |
+ bootstrap_home=$(mktemp -d "$RUNNER_TEMP/e2e-bootstrap.XXXXXX")
+ trap 'rm -rf "$bootstrap_home"' EXIT
+ unset GBRAIN_DATABASE_URL GBRAIN_E2E_ALLOW_DB
+ HOME="$bootstrap_home" GBRAIN_HOME="$bootstrap_home" \
+ GBRAIN_TEST_KEEP_AMBIENT_ENV=0 GBRAIN_TEST_KEEP_PROVIDER_KEYS=0 \
+ bun --no-env-file \
+ --preload ./test/helpers/operator-env-preload.ts \
+ --preload ./test/helpers/provider-keys-preload.ts \
+ -e 'import { setupLegacyEmbeddingDB, teardownDB } from "./test/e2e/helpers.ts"; try { await setupLegacyEmbeddingDB(); } finally { await teardownDB(); }'
+ env:
+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
+ GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1'
+ GBRAIN_MODEL_DISCOVERY: 'off'
+ - name: Full e2e shard ${{ matrix.shard }}/4 with coverage
# run-e2e.sh redirects HOME, so COVERAGE_DIR must be absolute; its
# env scrub keeps non-GBRAIN vars, so COVERAGE_DIR and
# E2E_FILE_TIMEOUT_SECS survive. 300s/file absorbs instrumentation
# overhead on the slowest files (the default cap is 180s).
run: bash scripts/run-e2e.sh
env:
+ SHARD: ${{ matrix.shard }}/4
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
COVERAGE_DIR: ${{ runner.temp }}/coverage
@@ -553,15 +581,26 @@ jobs:
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
- name: coverage-full-e2e
+ name: coverage-full-e2e-${{ matrix.shard }}
path: ${{ runner.temp }}/coverage
retention-days: 14
if-no-files-found: ignore
overwrite: true
+ - name: Upload execution receipt
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: e2e-full-execution-${{ matrix.shard }}
+ path: |
+ ${{ runner.temp }}/coverage/lane-manifest.json
+ ${{ runner.temp }}/coverage/executed-files.txt
+ retention-days: 14
+ if-no-files-found: error
+ overwrite: true
coverage-full-report:
needs: [coverage-full-unit, coverage-full-serial, coverage-full-slow, coverage-full-e2e]
- if: always() && github.event_name == 'schedule'
+ if: always() && (github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus))
runs-on: ubicloud-standard-4-ubuntu-2404
timeout-minutes: 15
steps:
@@ -581,10 +620,15 @@ jobs:
env:
COVERAGE_CORPUS: fullCorpus
run: |
+ if [ "${{ needs.coverage-full-e2e.result }}" != "success" ]; then
+ echo "Full E2E did not succeed; refusing a complete report from prior-attempt artifacts"
+ exit 1
+ fi
+ bun scripts/verify-nightly-e2e.ts "$RUNNER_TEMP/coverage-artifacts" 4 "$GITHUB_SHA"
bun scripts/merge-lcov.ts \
--out-lcov "$RUNNER_TEMP/coverage-full-merged/lcov.info" \
--out-json "$RUNNER_TEMP/coverage-full-merged/summary.json" \
- --manifest-expect shard-1,shard-2,shard-3,shard-4,shard-5,shard-6,shard-7,shard-8,shard-9,shard-10,serial,slow,e2e \
+ --manifest-expect shard-1,shard-2,shard-3,shard-4,shard-5,shard-6,shard-7,shard-8,shard-9,shard-10,serial,slow,e2e-1,e2e-2,e2e-3,e2e-4 \
"$RUNNER_TEMP/coverage-artifacts"
- name: Coverage summary → step summary
run: bun scripts/render-coverage-summary.ts --summary "$RUNNER_TEMP/coverage-full-merged/summary.json" --structural scripts/structural-suites.tsv >> "$GITHUB_STEP_SUMMARY"
@@ -604,7 +648,7 @@ jobs:
if-no-files-found: ignore
overwrite: true
- # The stable aggregate includes nightly execution lanes on schedules.
+ # The stable aggregate includes full-profile execution lanes when requested.
# Coverage reporting itself remains advisory; failed tests never do.
e2e-status:
needs: [jsonb-parity, tier1, tier2, prepare-e2e, selected-e2e, coverage-full-unit, coverage-full-serial, coverage-full-slow, coverage-full-e2e]
@@ -613,6 +657,8 @@ jobs:
timeout-minutes: 5
steps:
- name: Aggregate result
+ env:
+ FULL_CORPUS: ${{ github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus) }}
run: |
JSONB="${{ needs.jsonb-parity.result }}"
TIER1="${{ needs.tier1.result }}"
@@ -628,7 +674,7 @@ jobs:
exit 1
fi
done
- if [ "$EVENT" = "schedule" ]; then
+ if [ "$FULL_CORPUS" = "true" ]; then
FULL_UNIT="${{ needs.coverage-full-unit.result }}"
FULL_SERIAL="${{ needs.coverage-full-serial.result }}"
FULL_SLOW="${{ needs.coverage-full-slow.result }}"
@@ -636,9 +682,24 @@ jobs:
echo "full-unit=$FULL_UNIT full-serial=$FULL_SERIAL full-slow=$FULL_SLOW full-e2e=$FULL_E2E"
for r in "$FULL_UNIT" "$FULL_SERIAL" "$FULL_SLOW" "$FULL_E2E"; do
if [ "$r" != "success" ]; then
- echo "✗ scheduled full-corpus job did not succeed (got $r) — E2E fail"
+ echo "✗ full-corpus job did not succeed (got $r) — E2E fail"
exit 1
fi
done
fi
- echo "✓ all required e2e jobs succeeded — E2E green"
+ echo "✓ all required e2e jobs succeeded"
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)
+ with:
+ bun-version: 1.3.13
+ - name: Download nightly execution receipts
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
+ with:
+ pattern: e2e-full-execution-*
+ path: ${{ runner.temp }}/e2e-execution
+ - name: Verify complete nightly execution
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)
+ run: bun scripts/verify-nightly-e2e.ts "$RUNNER_TEMP/e2e-execution" 4 "$GITHUB_SHA"
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 9a3a4ff820..4609caf186 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.58.0.0 -->
+<!-- gbrain-runbook-stamp: 0.58.1.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 704464f583..9502a905c2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,65 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.58.1.0] - 2026-09-24
+
+**Spend less time rebuilding test fixtures without dropping database coverage.**
+
+Contributors can check the same behavior with less repeated setup. Shared
+database checks keep their local and server-backed coverage, but no longer
+repeat the local half inside the server-backed lane. Ordinary database resets
+reuse an already-current migration history; tests of migration behavior still
+replay it explicitly.
+
+The complete nightly database collection now runs across four independent
+workers. A final check requires every expected file to be accounted for once,
+on the same revision, before accepting the run. Cancelled workers cannot report
+success, and one coverage run cannot overwrite another run's output.
+
+This release changes test infrastructure, not your stored memories or normal
+GBrain commands. It does not enable paid-provider tests or reduce the sustained
+durability workload.
+
+### For contributors
+
+Run the complete local gate with `bun run ci:local`. To exercise the complete
+scheduled coverage profile on demand, dispatch the E2E workflow with
+`full_corpus=true`; ordinary dispatches keep their existing scope.
+
+| Work | What changes | What stays covered |
+| --- | --- | --- |
+| Shared database contracts | Each backend has its own execution owner | Both PGLite and PostgreSQL assertions |
+| Database setup | Current migration history survives ordinary resets | Explicit cold replay, cleanup and embedding identity |
+| Large fixtures | Reuse setup and analyze the original seeded data | Original sizes, assertions and performance thresholds |
+| Nightly database checks | Four isolated workers with exact file receipts | The complete discovered collection |
+
+The matched sequential E2E benchmark on the audited baseline `31f257a` improved from
+43m05.91s to 37m48.30s, a 12.28% reduction. Both timing runs retained the same
+two host-environment failures; they are timing evidence, not passing gates.
+The integrated changes separately passed the complete clean Docker gate.
+The four-worker nightly benefit is not yet measured, and a 50% reduction in
+overall test time is not established.
+
+## To take advantage of v0.58.1.0
+
+No database migration, service change or user configuration is required.
+Contributors should use the updated runners and the coverage ownership guidance
+in [Testing](docs/TESTING.md).
+
+### Itemized changes
+
+- Select PostgreSQL before registering shared E2E suites, retaining local-only
+ cases in their unit owners and refusing missing or unsafe test databases.
+- Preserve the migration ledger and stored embedding identity during ordinary
+ fixture resets. Explicit legacy-width setup aligns both columns and identity.
+- Reuse the embedded admin fixture, batch configured-root fixtures, and analyze
+ dense graph and entity-card data without shrinking their workloads.
+- Validate native test reports, cancellation status, exclusive coverage roots
+ and exact same-revision nightly execution receipts.
+- Refresh full-profile scheduling weights from complete recorded runs and
+ document the separate unit, integration, durability and native coverage owners.
+
+
## [0.58.0.0] - 2026-09-24
**Separate confirmed attendance from mentions, and give question evidence room in recall.**
diff --git a/CLAUDE.md b/CLAUDE.md
index 53556fe011..073a2d0b56 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -379,11 +379,10 @@ four numeric segments are required first. Historical 3-segment versions
DRIFT_STALE_PKG / DRIFT_UNEXPECTED, and refuses to proceed on
DRIFT_UNEXPECTED. This is why the two must move together.
-**The CI version-gate** rejects pushes where `VERSION` and
-`package.json` disagree, OR where `VERSION` is not strictly greater
-than master's VERSION. If a queue collision claims your version on
-master before yours lands, /ship's queue-aware allocator (Step 12)
-will detect drift and re-bump on the next run.
+**Auto-renumber when needed; never ask.** Use `/ship`'s queue-aware allocator,
+update all version stamps and the PR title, then report the number. This overrides
+its ALREADY_BUMPED rebump prompt, not scope, merge or deployment approvals.
+CI rejects mismatched `VERSION`/`package.json` or versions not newer than master.
### Version consistency and conflict recovery
diff --git a/VERSION b/VERSION
index 440798bf1f..67eca6f61c 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.58.0.0
+0.58.1.0
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 1de12c4fb2..5b47dbb896 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -46,8 +46,26 @@ files and native harness use. `test/shared-skills-transports.test.ts` and
issuance and a new stdio process; they do not prove vendor-native activation.
`test/persistence-skill-bundles.serial.test.ts` and
`test/persistence-skill-crash.slow.test.ts` exercise typed file-set CAS and
-independent-process publication/restoration kills on both engines through
-`test/e2e/persistence-skill-bundles-postgres.test.ts`.
+independent-process publication/restoration kills on PGLite in the unit lane and
+PostgreSQL through `test/e2e/persistence-skill-bundles-postgres.test.ts`.
+
+Shared persistence suites use `test/helpers/test-backends.ts`: direct invocation
+defaults to PGLite, and a safe `DATABASE_URL` opts into both engines. Their E2E
+wrappers select PostgreSQL before registering tests, refusing a missing or unsafe
+database instead of silently running only the local backend. Backend selection is
+captured at registration so hooks retain it after the import environment restores.
+Every backend's assertions remain in the shared suites; engine-specific cases run
+in their owning lane.
+
+Ordinary PostgreSQL `setupDB()` clears fixture data, operator configuration and
+source sync identity while retaining `config.version` and the stored embedding
+identity, avoiding historical migration
+replay against an already-current schema. Migration-focused fixtures use
+`setupDB({ replayMigrations: true })`; an absent ledger also runs the cold chain.
+`test/e2e/fixture-reset-postgres.test.ts` checks both paths, cleanup and vector-shape
+preservation, including the deliberate legacy-width restoration helper. That
+helper aligns both the physical columns and stored embedding identity with the
+legacy test configuration; ordinary resets preserve that identity.
The required `shared-skills-compatibility` CI job builds the pinned pre-feature
executable with `scripts/build-shared-skills-baseline.sh` and supplies
@@ -105,8 +123,9 @@ Search reliability has real-planner and transport regressions in
restricted-reader and FORCE-RLS roles; the candidate tests distinguish natural
plans from forced-HNSW controls and prove server cancellation of exact fallback.
`test/e2e/projection-recovery-parity.test.ts` runs the shared Markdown/code
-recovery, graph-edge preservation and migration-origin contracts against both
-engines. PGLite work caps never count a Promise race as cancellation evidence.
+recovery, graph-edge preservation and migration-origin contracts against
+PostgreSQL; their root suites cover PGLite in the unit lane. PGLite work caps never
+count a Promise race as cancellation evidence.
The recovery parity entry also runs `symbol-resolver-projection-race.test.ts`:
paused resolver/rebuild ordering, atomic rollback, candidate revalidation, and
a real PostgreSQL lock-wait receipt before releasing the competing writer.
@@ -141,6 +160,41 @@ optional-write jobs, and saved pages with failed enrichment are positive control
maintenance handler with failed phases, incomplete children, budget deferrals,
abort/lock loss, and successful warning-only controls.
+### Coverage responsibilities before consolidation
+
+Assign ownership to an **assertion and its execution boundary**, not to a test
+filename or a shared helper. Record the contract, backend, runtime version,
+OS/architecture/libc, source-versus-compiled artifact, transport/authentication,
+process/storage/crash boundary, workload size and required cadence. Shared
+scenario code across two engines is not duplicate engine coverage: PostgreSQL
+JSONB, locking and pooler behavior are not established by a PGLite pass.
+
+| Responsibility | Execution owner | What it does not establish |
+|---|---|---|
+| Keyless behavior, structural guards and shared contracts | Unit shards and `verify` in `test.yml`; process-isolated serial and dedicated slow lanes where required | Real PostgreSQL, native activation or compiled behavior |
+| PostgreSQL behavior and engine parity | Named and diff-selected jobs in `e2e.yml`; the complete nightly runner corpus | Execution of key-gated or native-door assertions merely because their files were discovered |
+| Durable publication and recovery under sustained load | `persistence-validation.yml` and `scripts/persistence/README.md` | Power-loss safety, production authentication or equivalence to two smaller databases |
+| Native lock ABI and compiled-process exclusion | `native-locks.yml`, compiled smoke and release validation | All compiled CLI features or native-harness activation |
+| Browser journeys | Required `admin-browser` job and `admin/e2e/*.pw.ts` | Vendor-native agent behavior |
+| Native agent doors and heavier operational scenarios | Explicit jobs in `heavy-tests.yml` | A passing skipped door or generic protocol test is not native activation |
+| Live-provider and optional recipe/eval behavior | Their explicitly configured opt-in commands/jobs | A missing key, early return or skipped assertion is not live-provider evidence |
+| Line-coverage accounting | PR `prCorpus` and nightly `fullCorpus` reports | Subprocess coverage, all platforms or proof that every discovered case executed |
+
+Before removing repeated work, identify the surviving owner for the same
+contract **and every relevant boundary**, prove that owner actually executes,
+and retain its cadence, failure gate and coverage artifacts. A shared fixture
+can reduce maintenance while keeping both engine arms. Making one crash lane
+authoritative or collecting LCOV in a named owner requires a separate ownership
+change; nightly sharding alone makes neither change.
+
+Name the profile when reporting “all tests.” The local fast loop, `test:full`,
+`ci:local`, required PR checks and nightly `fullCorpus` are not interchangeable
+supersets. Native matrices, sustained persistence validation, browser tests and
+optional recipe/eval commands have separate responsibilities. A faster nightly
+E2E schedule does not shorten a PR critical path dominated by persistence.
+Report matched executed timings separately from dry-run partition estimates,
+including setup, queueing and retries; never count skip-only output as coverage.
+
### Test command tiers
The sequential E2E runner gives each test file a fresh `HOME` and `GBRAIN_HOME`.
@@ -480,7 +534,16 @@ per-file pools, and up to four selected E2E workers. E2E selection and exclusion
run once before setup; the resulting file lists are frozen and executed against
separate Postgres services. An explicit empty selection launches no tests;
selection errors, failed workers, cancellations, and unexpected skips fail the
-existing aggregate checks. Nightly full-corpus lanes remain separate.
+existing aggregate checks. Nightly full-corpus E2E uses four independent
+Postgres jobs with the same weighted partitioner and one fresh Bun process per
+file, sequential within each job. It does not use the selected-E2E exclusion
+list: default discovery includes every `test/e2e/*.test.ts` and
+`test/phantom-redirect-engine-parity.test.ts`.
+Each full-profile worker first initializes its own service schema with the
+guarded `setupLegacyEmbeddingDB()` helper, in a temporary home with provider
+keys stripped and local environment-file loading disabled. No partition relies
+on a preceding file to create shared tables. Bootstrap is a separate timed CI
+step and must be included in end-to-end comparisons.
Refresh after a large test wave or when the longest shard repeatedly exceeds
the mean shard execution time by 25%:
@@ -489,6 +552,7 @@ the mean shard execution time by 25%:
bun run weights:mine --lane unit --run <successful-test-run>
bun run weights:mine --lane serial --run <successful-test-run>
bun run weights:mine --lane e2e --run <successful-e2e-run>
+bun run weights:mine --lane e2e --e2e-profile full --run <successful-full-corpus-run>
```
The miner accepts `--from-file` or stdin for timestamped GitHub-format logs and
@@ -496,8 +560,8 @@ The miner accepts `--from-file` or stdin for timestamped GitHub-format logs and
unit matrix jobs, includes `evals/`, and closes the final file at the Bun summary.
Serial timing uses runner durations, never timestamps of buffered output. E2E
uses each file's Bun summary and merges partial selections into known weights.
-File/stdin imports also merge unobserved entries; only a complete GitHub unit or
-serial run replaces that lane's entire map. Captured artifacts need their final
+File/stdin imports also merge unobserved entries; only a complete GitHub unit,
+serial or explicit full-profile E2E run replaces that lane's entire map. Captured artifacts need their final
successful completion marker, and GitHub imports verify every expected job.
Incomplete or failed inputs leave the existing map intact. Sidecar metadata
records the source run/commit, units, and counts. Unit/E2E weights are milliseconds;
@@ -505,6 +569,18 @@ serial weights remain seconds. New files receive the corpus p75 estimate. Empty
maps and zero-cost ties distribute files deterministically; corrupt serial
weights warn and retain safe fallback scheduling.
+The default E2E miner reads selected jobs and merges partial observations.
+`--e2e-profile full` instead requires a successful GitHub run with a source SHA
+matching checkout HEAD. It pins the run attempt and full-job IDs, reconstructs
+default discovery using the committed runner and tracked test paths, and
+requires every source file exactly once across complete successful job logs.
+Missing/extra files, ambiguous basenames, duplicate execution or failed evidence
+leave weights and metadata untouched. Basename resolution preserves the
+outside-directory parity entry. Full mode replaces the complete map and records
+source SHA, attempt, jobs, log hash and corpus hash; file/stdin imports cannot
+claim full-profile provenance. These weights schedule work; they are not an
+observed parallel runtime.
+
CI retains timestamped unit/E2E logs, frozen E2E selection, and serial attempt
records for 14 days. Compare push-to-required-green time including queueing,
first failure, rescues/reruns, runner minutes, unique file counts, and coverage
@@ -613,6 +689,20 @@ batch (`-n 100000 -x`) so an argv overflow fails loud instead of spawning a
second, overwriting bun process. On a green run each lane writes
`$COVERAGE_DIR/lane-manifest.json` (`{lane, sha, lcovCount, complete}`); a red
run writes no manifest, which downstream merging treats as an incomplete lane.
+E2E shards use distinct `e2e-1` through `e2e-4` lane names (unsharded runs use
+`e2e`), with an `executed-files.txt` receipt written only after every selected
+file completes its native Bun report successfully. The runner requires a fresh
+parent-owned JUnit report for the selected file and matching final console
+pass/fail/skip totals. Python 3's standard XML parser validates the document
+and checks its actual testcase counts against each suite and the console;
+a zero exit without that report cannot borrow a nested child's summary as
+completion evidence. Each coverage invocation atomically creates its own
+`COVERAGE_DIR`; an existing destination, even an empty one, is refused without
+changing its contents. Use a new path for a rerun. Failed or cancelled runs
+write no completion receipt, and shorter or skip-only runs cannot inherit old
+coverage or delete another run's outputs.
+Skip-only files can emit no LCOV, so execution-file counts and LCOV counts are
+intentionally different measures.
`run-e2e.sh` specifics: `COVERAGE_DIR` is normalized to an absolute path
against the repo root before `HOME` moves (the script redirects
`HOME`/`GBRAIN_HOME` and E2E tests spawn CLI subprocesses with varying cwd —
@@ -628,19 +718,42 @@ non-`GBRAIN_`-prefixed so the hermetic env scrub keeps them.
three dedicated slow jobs (`slow-eval-longmemeval`,
`slow-entity-resolve-perf`, `slow-brainbench-e2e`). Deterministic (runs identically on every PR); this
is the corpus the gates run against.
-- **fullCorpus** — nightly, schedule-only in `.github/workflows/e2e.yml`:
+- **fullCorpus** — nightly or explicit manual opt-in in `.github/workflows/e2e.yml`:
`coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report`. Fully
self-contained (every lane re-runs with coverage inside that workflow,
- including the full `test/e2e/*` glob against real Postgres) — the honest
+ including the full default E2E discovery across four isolated Postgres
+ workers) — the honest
merged unit+serial+slow+e2e number, kept as the `coverage-full-merged` trend
artifact.
+The E2E workflow's manual `full_corpus` boolean defaults to `false`. Setting it
+to `true` executes the same full unit/serial/slow/E2E profile, report and receipt
+checks as a schedule; selected E2E receives the same explicit empty sentinel.
+Ordinary pushes, PRs and default manual runs retain their existing selection.
+Explicit full manual runs have a separate concurrency group, so they do not
+cancel ordinary validation on the same branch. To measure a branch before the
+next scheduled run, dispatch `e2e.yml` on that branch with `full_corpus=true`.
+
+The nightly E2E artifacts are `coverage-full-e2e-1` through `-4`, with one
+manifest per artifact and one coverage directory per Bun process. Lightweight
+`e2e-full-execution-*` artifacts also carry the manifest and executed-file list.
+Full-profile `e2e-status` requires the matrix job to succeed and validates all four
+same-commit receipts against the exact expected partitions using
+`scripts/verify-nightly-e2e.ts`. Missing artifacts, duplicate identities, wrong
+commits, omitted or repeated files, failures and cancellations cannot report
+complete execution. The report independently verifies these receipts before
+merging; missing execution evidence prevents publishing a full-corpus report.
+Coverage percentages remain advisory and the report job itself is not an
+`e2e-status` dependency. The receipts prove file execution, not execution of
+every optional assertion within a file.
+
**Merge** (`scripts/merge-lcov.ts`). Walks the input dirs for `lcov.info` +
`lane-manifest.json`, sums DA hits per file:line, normalizes paths
repo-relative, and emits a merged lcov plus a summary JSON: src-only
totals/per-dir/per-file percentages, a `lineHits` map (the diff gate's input),
and the never-loaded src file list. `--manifest-expect lane,lane,...` pins the
-expected lane set (`serial-1` through `serial-4` for PRs, `serial` nightly).
+expected lane set (`serial-1` through `serial-4` for PRs, `serial` nightly,
+and `e2e-1` through `e2e-4` nightly).
The merger checks commit SHA (`--sha` overrides checkout HEAD for offline
artifacts), duplicate identities, and actual per-lane LCOV counts; a missing or `complete: false` manifest, an unparseable
lcov, or a `shard` lane with `lcovCount != 1` marks the summary
@@ -1231,6 +1344,10 @@ When asked to "run all E2E tests" or "run tests", that means ALL tiers:
### E2E test DB lifecycle (ALWAYS follow this)
+The sequential E2E runner requires Python 3 for standard-library XML validation
+of Bun's native JUnit reports. CI and the local Docker runner provide it; direct
+host runs must have `python3` on `PATH` before launching tests.
+
`setupDB()` clears rows while preserving physical schema. Fixtures that seed
fixed legacy-width text vectors use `setupLegacyEmbeddingDB()` instead: it
establishes the canonical test shape after clearing the database, including
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.md
index 65827f710f..1651dea2c6 100644
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@ -33,7 +33,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/classify-tests.ts` + `scripts/structural-suites.tsv` — suite-level behavioral-vs-structural test classification (the intent axis described in docs/TESTING.md "File taxonomy"). Content-based detectors — repo-anchored `readFileSync`/`Bun.file` readers, exec-scan grep windows over `src|scripts|docs`, and the `doctorSource()`/`doctorFileSource()` helpers — mark a suite STRUCTURAL when its assertions read repo source/doc text rather than executing product code; tmpdir-anchored reads don't count, and files with detectors but no attributable suite land in an `unknown` bucket emitted as comment rows (surfaced, never silently dropped). Modes: bare = rewrite the TSV; `--check` = byte-for-byte regenerate-and-diff freshness (wired as `bun run check:structural-manifest` in `bun run verify` via `scripts/check-structural-manifest.sh`); `--summary` = counts only. Fix misclassifications in the detector list, never by hand-editing the TSV. `render-coverage-summary.ts` consumes the TSV for the behavioral-vs-structural line in the CI coverage report.
-- `scripts/e2e-matrix.ts` — freezes selected E2E paths after existing named/live exclusions into at most four weighted partitions. Explicit empty sentinel is the only no-op; malformed/missing input fails. Workers validate paths and filesystem confinement, pass argv directly, clear inherited SHARD and forward cancellation. `prepare-e2e` and every worker are required by e2e-status; each worker owns Postgres. Pinned by `test/scripts/e2e-matrix.test.ts` and workflow wiring tests.
+- `scripts/e2e-matrix.ts` — freezes selected E2E paths after existing named/live exclusions into at most four weighted partitions. Explicit empty sentinel is the only no-op; malformed/missing input fails. Workers validate paths and filesystem confinement, pass argv directly, clear inherited SHARD and register cancellation handlers before spawning, retaining any signal received before the child handle is available. `prepare-e2e` and every worker are required by e2e-status; each worker owns Postgres. Pinned by `test/scripts/e2e-matrix.test.ts` and workflow wiring tests.
+
+- `.github/workflows/e2e.yml` + `scripts/verify-nightly-e2e.ts` — full E2E discovery runs on four weighted, independent Postgres workers, sequential fresh Bun processes within each. Schedules and explicit default-false `full_corpus` manual dispatches share the same full-profile jobs, aggregation, reports and receipts; ordinary selection is unchanged and full manual runs have their own concurrency group. Each worker bootstraps its guarded service schema through `setupLegacyEmbeddingDB()` under a keyless temporary home before tests. No selected-lane exclusions apply. Workers publish distinct `e2e-N` coverage manifests and successful executed-file receipts; full-profile `e2e-status` requires successful job results plus exact, disjoint, same-commit partitions. The advisory report validates those receipts before merging all four multi-file LCOV lanes. Coverage count is not executed-file count: skip-only files may emit no LCOV. `test/scripts/nightly-e2e.test.ts`, `e2e-runner.test.ts`, `ci-gates.test.ts` and `merge-lcov.test.ts` pin discovery, isolation, failure/cancellation, artifacts and completeness. See docs/TESTING.md for cross-lane coverage responsibilities.
- `scripts/eval-spend-guard.sh` — hard spend cap for paid eval runs: `scripts/eval-spend-guard.sh <cap_usd> <estimate_usd> -- <command...>`. INVARIANT: a paid command never launches when ledger total + estimate would exceed the cap, and every launch is appended to the ledger whether or not it succeeded, so the running total can only under-state spend if the command itself lies about its cost. FAILS CLOSED on anything it cannot account for: a missing ledger (a missing file is NOT a $0 ledger — the first run sets `GBRAIN_EVAL_SPEND_LEDGER_INIT=1`, which prints a loud NEW LEDGER line), an unparseable ledger line (named by line number), a signed or malformed amount (a negative estimate would drive the ledger backwards). Ledger `$GBRAIN_EVAL_SPEND_LEDGER` (default `~/gbrain-lme-receipts/spend.jsonl`): every launch writes TWO rows sharing a `run_id` — a `status: running` reservation appended BEFORE the command starts (cost = the estimate, so a concurrent guard already counts it) and a `status: done` reconciliation after it exits (actual cost, exit code); the sum is reconciled rows + unreconciled reservations, so a guard killed by INT/TERM/HUP (trap-reconciled at the estimate) or SIGKILL (reservation left standing) never under-counts, and an unwritable ledger refuses the launch — the child gets TERM, then KILL after `GBRAIN_EVAL_SPEND_GUARD_KILL_GRACE_SECONDS` (default 10). Legacy single-row lines `{ts, estimate_usd, cost_usd, exit_code, command}` still count. The recorded cost comes from `$GBRAIN_EVAL_ACTUAL_COST_FILE` (exported to the child as a scratch path when unset; bare unsigned number or JSON with `cost_usd`) only when positive, else the estimate (over-stating is the safe direction). Amounts normalize to `%.6f`; awk/grep/sed only — no jq or bun at runtime. Exit: the wrapped command's code · 2 usage · 3 refused. Pinned by `test/eval-spend-guard.test.ts`.
@@ -43,7 +45,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/llms-config.ts` + `scripts/build-llms.ts` — Generator for `llms.txt` (llmstxt.org-spec web index) + `llms-full.txt` (inlined single-fetch bundle). Curated config drives both. Run `bun run build:llms` after adding a new doc. `LLMS_REPO_BASE` env lets forks regenerate with their own URL base. `FULL_SIZE_BUDGET` (600KB) caps the inline bundle; generator WARNs if exceeded. Committed output has no runtime consumer; committed for GitHub browsing and fork-safe fetching.
-- `scripts/merge-lcov.ts` + `scripts/coverage-diff-gate.ts` + `scripts/coverage-baseline-gate.ts` + `scripts/update-coverage-baseline.ts` + `scripts/render-coverage-summary.ts` + `scripts/coverage-gate-exemptions.txt` + `scripts/coverage-baseline.json` — the coverage measurement + gating cluster; the operating guide is docs/TESTING.md "Coverage lanes and gates". `merge-lcov.ts` walks artifact dirs for `lcov.info` + `lane-manifest.json`, sums DA hits per file:line, normalizes paths repo-relative, and emits a merged lcov + summary JSON (src-only totals/per-dir/per-file, the `lineHits` extension the diff gate consumes, and never-loaded src files as count + sorted list — deliberately never a percentage, since physical lines ≠ executable lines); `--manifest-expect` pins the lane set; SHA, duplicate identities, and actual per-lane LCOV counts are validated (`--sha` supports offline artifacts), and a missing/incomplete lane or a `shard` lane with `lcovCount != 1` (the xargs-batching tripwire) marks the summary `degraded: true` — still exit 0 (degraded is data, and both gates go report-only on it). `coverage-diff-gate.ts` gates added/changed gate-scoped lines (non-test, non-generated `src/**.ts`) at ≥80% covered plus zero changed-but-never-loaded files; report-only unless `COVERAGE_GATE_ENFORCE=1`; a `[coverage-exempt: reason]` commit trailer passes with a loud warning; `coverage-gate-exemptions.txt` rows (exact path or trailing-`/` prefix; SHRINK-ONLY — additions need a graduation review) are excluded from the gate but still reported (`[e2e-exempt]` / `[subprocess-undercount]`); exit contract: 0 = pass or report-only, 1 = fail while enforcing, 2 = infrastructure error (never conflated with a coverage verdict). `coverage-baseline-gate.ts` reads the baseline via `git show origin/master:scripts/coverage-baseline.json` (never the working tree, so a PR can't weaken its own bar) and compares corpus-matched sections only (`--corpus prCorpus|fullCorpus`), failing on >0.5pp global or >1.0pp per-dir drops; `provisional: true` in the baseline (the current state — both corpus sections unseeded) keeps it report-only regardless of enforcement; `update-coverage-baseline.ts` writes the working-tree baseline (per-file detail limited to the committed `watchlist`) and `--promote` flips `provisional: false`. `render-coverage-summary.ts` renders the summary JSON as markdown on stdout for `$GITHUB_STEP_SUMMARY`, including the behavioral-vs-structural counts from `scripts/structural-suites.tsv`. Wiring: 17 PR-corpus lanes in test.yml (10 matrix shards + four serial partitions + the three dedicated slow jobs) upload `coverage-*` artifacts and the advisory `coverage-report` job merges + renders + runs both gates report-only (deliberately absent from `test-status`/`cache-write` until graduation); schedule-only `coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report` in e2e.yml produce the self-contained nightly fullCorpus number (full e2e glob included) and the `coverage-full-merged` trend artifact. Collection is `COVERAGE_DIR`-opt-in in `test-shard.sh`/`run-serial-tests.sh`/`run-e2e.sh` — unique coverage dir per bun process (a reused dir overwrites `lcov.info`), lane manifest written only on a green run, `run-e2e.sh` requires an ABSOLUTE `COVERAGE_DIR` and honors `E2E_FILE_TIMEOUT_SECS` (both deliberately non-`GBRAIN_`-prefixed to survive the hermetic env scrub). Bun/JSC emits line records only (function coverage is informational) and no subprocess coverage, so `src/cli.ts` undercounts. Pinned by `test/scripts/merge-lcov.test.ts`, `test/scripts/coverage-diff-gate.test.ts`, `test/scripts/render-coverage-summary.test.ts`.
+- `scripts/merge-lcov.ts` + `scripts/coverage-diff-gate.ts` + `scripts/coverage-baseline-gate.ts` + `scripts/update-coverage-baseline.ts` + `scripts/render-coverage-summary.ts` + `scripts/coverage-gate-exemptions.txt` + `scripts/coverage-baseline.json` — the coverage measurement + gating cluster; the operating guide is docs/TESTING.md "Coverage lanes and gates". `merge-lcov.ts` walks artifact dirs for `lcov.info` + `lane-manifest.json`, sums DA hits per file:line, normalizes paths repo-relative, and emits a merged lcov + summary JSON (src-only totals/per-dir/per-file, the `lineHits` extension the diff gate consumes, and never-loaded src files as count + sorted list — deliberately never a percentage, since physical lines ≠ executable lines); `--manifest-expect` pins the lane set; SHA, duplicate identities, and actual per-lane LCOV counts are validated (`--sha` supports offline artifacts), and a missing/incomplete lane or a `shard` lane with `lcovCount != 1` (the xargs-batching tripwire) marks the summary `degraded: true` — still exit 0 (degraded is data, and both gates go report-only on it). `coverage-diff-gate.ts` gates added/changed gate-scoped lines (non-test, non-generated `src/**.ts`) at ≥80% covered plus zero changed-but-never-loaded files; report-only unless `COVERAGE_GATE_ENFORCE=1`; a `[coverage-exempt: reason]` commit trailer passes with a loud warning; `coverage-gate-exemptions.txt` rows (exact path or trailing-`/` prefix; SHRINK-ONLY — additions need a graduation review) are excluded from the gate but still reported (`[e2e-exempt]` / `[subprocess-undercount]`); exit contract: 0 = pass or report-only, 1 = fail while enforcing, 2 = infrastructure error (never conflated with a coverage verdict). `coverage-baseline-gate.ts` reads the baseline via `git show origin/master:scripts/coverage-baseline.json` (never the working tree, so a PR can't weaken its own bar) and compares corpus-matched sections only (`--corpus prCorpus|fullCorpus`), failing on >0.5pp global or >1.0pp per-dir drops; `provisional: true` in the baseline (the current state — both corpus sections unseeded) keeps it report-only regardless of enforcement; `update-coverage-baseline.ts` writes the working-tree baseline (per-file detail limited to the committed `watchlist`) and `--promote` flips `provisional: false`. `render-coverage-summary.ts` renders the summary JSON as markdown on stdout for `$GITHUB_STEP_SUMMARY`, including the behavioral-vs-structural counts from `scripts/structural-suites.tsv`. Wiring: 17 PR-corpus lanes in test.yml (10 matrix shards + four serial partitions + the three dedicated slow jobs) upload `coverage-*` artifacts and the advisory `coverage-report` job merges + renders + runs both gates report-only (deliberately absent from `test-status`/`cache-write` until graduation); scheduled or explicitly dispatched `coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report` in e2e.yml produce the self-contained fullCorpus number (full e2e glob included) and the `coverage-full-merged` trend artifact. Collection is `COVERAGE_DIR`-opt-in in `test-shard.sh`/`run-serial-tests.sh`/`run-e2e.sh` — unique coverage dir per bun process (a reused dir overwrites `lcov.info`), lane manifest written only on a green run, `run-e2e.sh` requires an ABSOLUTE `COVERAGE_DIR` and honors `E2E_FILE_TIMEOUT_SECS` (both deliberately non-`GBRAIN_`-prefixed to survive the hermetic env scrub). Bun/JSC emits line records only (function coverage is informational) and no subprocess coverage, so `src/cli.ts` undercounts. Pinned by `test/scripts/merge-lcov.test.ts`, `test/scripts/coverage-diff-gate.test.ts`, `test/scripts/render-coverage-summary.test.ts`.
- `scripts/persistence/{harness,schedules,worker,validate,failure-diagnostics}.ts` — executable concurrency gate using real journal/coordinator APIs: 1,000 seeded schedules per engine, eight actual process-kill publication boundaries, and 10,000 writes from four producer processes. Each phase owns a temporary disk PGLite datastore or a fresh test Postgres database. Independent accounting queries verify conservation; every soak receipt is compared to its canonical snapshot and file. JSON manifests separate actual counts and latency measurements from the configured Linux/Bun CI matrix. Failed runs preserve private fixtures and collect bounded, allowlisted request/queue/owner diagnostics without changing deadlines or hiding the original error. Cleanup commands read the existing test URL from the environment. The PGLite loopback endpoint is a fixture transport, not production authentication coverage. Contract and commands: `scripts/persistence/README.md`; smoke entries: `test/persistence-chaos.slow.test.ts`, `test/e2e/persistence-chaos.test.ts`; diagnostic/retention contracts: `test/persistence-failure-diagnostics.test.ts`.
@@ -55,13 +57,17 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL, so this lane must carry it). This wrapper is the database-URL opt-in boundary: it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (the e2e suite runs on `DATABASE_URL` only — an ambient `GBRAIN_DATABASE_URL` would pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable. It also preserves `GBRAIN_CI_DISABLE_TEST_ENV_FILE=1`, keeping CI runs from loading checkout-local `.env.testing` credentials after the shell-to-Bun handoff. It also exports `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` so the unit-lane provider-key strip preload (`test/helpers/provider-keys-preload.ts`) leaves the real keys that live embed/parity e2e tests skip-gate on. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (`skills.test.ts` gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare `bun` (no outer cap) is the fallback when neither timeout binary is installed. It activates the PGLite schema snapshot like the other runners: sources `scripts/lib/test-env.sh` + `ensure_pglite_snapshot` after the `--dry-run-list` early exit (list mode stays instant; non-fatal on build failure), re-exports `GBRAIN_PGLITE_SNAPSHOT` as an ABSOLUTE path (e2e tests spawn CLI subprocesses with varying cwd — a relative path silently misses the tar there), and its env keep-list preserves the var; e2e files that assert the path TO post-`initSchema()` state carry per-file `delete process.env.GBRAIN_PGLITE_SNAPSHOT` opt-outs with one-line reasons.
+ Every file needs a fresh parent-owned native JUnit report, its selected-file header and matching final console totals; zero exit alone or a nested child's summary cannot establish completion. All-skipped reports remain valid and explicit. Coverage runs atomically claim a new destination, refusing existing paths without deleting their contents, and write `executed-files.txt` plus a same-commit manifest only after all selected files succeed. `SHARD=N/M` produces lane `e2e-N`; unsharded runs retain `e2e`. The per-file LCOV directories remain independent, and the nightly validator accounts for every partition without equating LCOV count with executed-file count.
+
- `scripts/select-e2e.ts` + `scripts/e2e-test-map.ts` — Diff-aware E2E test selector. Reads three git sources (committed `origin/master...HEAD`, working-tree `HEAD`, and `git ls-files --others --exclude-standard` for untracked NOT-gitignored files), classifies as EMPTY / DOC_ONLY / SRC. Fail-closed: EMPTY → all files; DOC_ONLY (every path matches the README/CLAUDE/AGENTS/CHANGELOG/TODOS allowlist) → empty stdout; SRC → escape-hatch paths (schema, package.json, skills/) trigger all, else the hand-tuned `E2E_TEST_MAP` glob narrows, and an unmapped src/ change still emits ALL files (never silently nothing). Pure-function exports `selectTests`, `classify`, `matchGlob`. `bun run ci:select-e2e` prints the current selection on stdout. `test/select-e2e.test.ts` covers all 4 branches plus 3 guards (skills/, untracked files, unmapped src/) — 24 cases.
-- `scripts/sharding.ts` + `scripts/mine-shard-weights.ts` + `scripts/capture-test-log.ts` — shared deterministic weighted partitioning and timing refresh. CLI accepts lane-specific weights; missing entries use p75, equal loads prefer fewer files then shard index, and serial may explicitly opt into warning/fallback on bad advisory weights. `weights:mine --lane unit|serial|e2e` validates completed lane logs before replacement and records run/commit/unit metadata. Capture preserves stdout/stderr, records timestamped GitHub-format artifacts, forwards cancellation to its owned process group and marks failed runs unmineable. Unit and E2E artifact retention is 14 days.
+- `scripts/sharding.ts` + `scripts/mine-shard-weights.ts` + `scripts/capture-test-log.ts` — shared deterministic weighted partitioning and timing refresh. CLI accepts lane-specific weights; missing entries use p75, equal loads prefer fewer files then shard index, and serial may explicitly opt into warning/fallback on bad advisory weights. `weights:mine --lane unit|serial|e2e` validates completed lane logs before replacement and records run/commit/unit metadata. E2E defaults to merging selected-job observations; explicit `--e2e-profile full --run ID` requires a successful source-matched run, pins its attempt/job IDs, resolves basename headers against committed default discovery including the outside-directory parity entry, and replaces the map only after exact disjoint corpus validation. Metadata retains log/corpus hashes; file/stdin sources cannot claim full-profile provenance. Capture preserves stdout/stderr, records timestamped GitHub-format artifacts, forwards cancellation to its owned process group and marks failed runs unmineable. Unit and E2E artifact retention is 14 days.
- `test/e2e/codex-plugin-install-real.serial.test.ts` + `test/e2e/claude-plugin-install-real.serial.test.ts` — the plugin doors: clean-tree staging (`git archive HEAD`), real marketplace add/plugin add, snapshot + exec-bit + non-root-mcp.json pins, tools/list starter-surface oracle, cold-home fast-fail, --source-guard block/allow, coexistence + removal probes, auth-gated SMOKE turns. CI: the `plugin-doors` job in heavy-tests.yml (pinned binary provisioning + expected-pass-count refuse-green).
-- `test/e2e/helpers.ts` — shared guarded test database lifecycle. `setupDB()` preserves physical schema; fixed-width vector fixtures explicitly use `setupLegacyEmbeddingDB()` to align empty text-embedding columns with canonical legacy test configuration after truncation. This prevents earlier CLI-init fixtures from leaking a different width into weighted execution order. Custom-shape migration fixtures retain ordinary setup. `importFixtures()` accepts an explicit engine for fixtures that own a separate database. `test/db-guard-coverage.test.ts` recognizes both guarded entry points.
+- `test/e2e/helpers.ts` — shared guarded test database lifecycle. `setupDB()` preserves physical schema, stored embedding identity and the migration ledger while clearing data, other operator configuration and source sync identity; migration fixtures opt into cold replay, and a missing ledger also takes the cold path. `test/e2e/fixture-reset-postgres.test.ts` pins those boundaries. Fixed-width vector fixtures explicitly use `setupLegacyEmbeddingDB()` to align empty text-embedding columns and stored model/dimensions with canonical legacy test configuration after truncation. This prevents earlier CLI-init fixtures from leaking a different identity or width into weighted execution order. Custom-shape fixtures retain ordinary setup. `importFixtures()` accepts an explicit engine for fixtures that own a separate database. `test/db-guard-coverage.test.ts` recognizes both guarded entry points.
+
+- `test/helpers/test-backends.ts` — shared persistence-suite backend selection. Direct root suites retain local-only defaults and explicit dual-engine invocation; E2E wrappers capture PostgreSQL-only selection while registering tests and fail closed without a safe database. The unit and E2E lanes jointly retain every backend contract without repeating the local arm.
- `test/e2e/mechanical.test.ts` — the healthy-doctor block imports the full corpus into a fresh UUID-isolated Postgres database and directs every CLI connection there. It preserves unrelated OAuth/grant state in the shared E2E database; a retained confidential-client fixture with an empty secret hash must not invalidate this healthy-brain assertion. Both human and JSON doctor paths require exit zero, and JSON checks must contain no failures. Failure diagnostics retain failed-check names with bounded credential/connection redaction.
diff --git a/llms-full.txt b/llms-full.txt
index 3a6a644aae..8054683709 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -2189,11 +2189,10 @@ four numeric segments are required first. Historical 3-segment versions
DRIFT_STALE_PKG / DRIFT_UNEXPECTED, and refuses to proceed on
DRIFT_UNEXPECTED. This is why the two must move together.
-**The CI version-gate** rejects pushes where `VERSION` and
-`package.json` disagree, OR where `VERSION` is not strictly greater
-than master's VERSION. If a queue collision claims your version on
-master before yours lands, /ship's queue-aware allocator (Step 12)
-will detect drift and re-bump on the next run.
+**Auto-renumber when needed; never ask.** Use `/ship`'s queue-aware allocator,
+update all version stamps and the PR title, then report the number. This overrides
+its ALREADY_BUMPED rebump prompt, not scope, merge or deployment approvals.
+CI rejects mismatched `VERSION`/`package.json` or versions not newer than master.
### Version consistency and conflict recovery
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index c9857f4f57..19568d2488 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.58.0.0",
+ "version": "0.58.1.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index f651907544..44d8a701a9 100644
--- a/package.json
+++ b/package.json
@@ -179,7 +179,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.58.0.0",
+ "version": "0.58.1.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 251a1967de..4e92668f27 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.58.0.0",
+ "version": "0.58.1.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index f8b51d1ced..e2f088a040 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.58.0.0",
+ "version": "0.58.1.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index fc7ed62f09..c265d9979b 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.58.0.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.58.1.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 3ab1bb9b6a..0e8e89b6ae 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.58.0.0",
+ "version": "0.58.1.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 0774d23bc2..b147671e1f 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.58.0.0",
+ "version": "0.58.1.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 023b9a2cd3..6712ea7836 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.58.0.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.58.1.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index 24f0017f81..d65827c2e1 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.58.0.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.58.1.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/e2e-matrix.ts b/scripts/e2e-matrix.ts
index eb99470b2b..ae2e70ff94 100644
--- a/scripts/e2e-matrix.ts
+++ b/scripts/e2e-matrix.ts
@@ -63,12 +63,22 @@ export async function runRow(value: unknown, root = process.cwd()): Promise<numb
const env = { ...process.env };
delete env.SHARD; // The prepared list is already partitioned.
console.log(`selected E2E shard ${row.shard}: ${row.files.length} frozen files`);
- const child = Bun.spawn(["bash", "scripts/run-e2e.sh", ...row.files], { cwd: root, env, stdout: "inherit", stderr: "inherit" });
- const term = () => child.kill("SIGTERM");
- const interrupt = () => child.kill("SIGINT");
+ let child: ReturnType<typeof Bun.spawn> | undefined;
+ let pendingSignal: "SIGTERM" | "SIGINT" | undefined;
+ const forward = (signal: "SIGTERM" | "SIGINT") => {
+ pendingSignal = signal;
+ child?.kill(signal);
+ };
+ const term = () => forward("SIGTERM");
+ const interrupt = () => forward("SIGINT");
process.once("SIGTERM", term);
process.once("SIGINT", interrupt);
- try { return await child.exited; }
+ try {
+ child = Bun.spawn(["bash", "scripts/run-e2e.sh", ...row.files], { cwd: root, env, stdout: "inherit", stderr: "inherit" });
+ if (pendingSignal) child.kill(pendingSignal);
+ const code = await child.exited;
+ return pendingSignal ? (pendingSignal === "SIGINT" ? 130 : 143) : code;
+ }
finally { process.off("SIGTERM", term); process.off("SIGINT", interrupt); }
}
async function main() {
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 2bdf113842..02c0f7a2eb 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -206,6 +206,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/connection-manager.ts": ["test/e2e/persistence-runtime-matrix.test.ts", "test/e2e/pgbouncer-teardown.test.ts"],
"src/core/postgres-engine.ts": [
"test/e2e/unsupported-embedding-identity-postgres.test.ts",
+ "test/e2e/fixture-reset-postgres.test.ts",
"test/e2e/persistence-chaos.test.ts",
"test/e2e/db-lock-acquisition-token.test.ts",
"test/e2e/chunk-canonical-text-privacy.test.ts",
diff --git a/scripts/e2e-weights.json b/scripts/e2e-weights.json
index 86a080b185..69374e5562 100644
--- a/scripts/e2e-weights.json
+++ b/scripts/e2e-weights.json
@@ -1,223 +1,283 @@
{
- "test/e2e/anomalies-pglite.test.ts": 1510,
- "test/e2e/auth-permissions.test.ts": 1407,
- "test/e2e/auth-takes-holders-pglite.test.ts": 947,
- "test/e2e/autopilot-cooldown-parity.test.ts": 1900,
- "test/e2e/autopilot-fanout-postgres.test.ts": 1357,
- "test/e2e/autopilot-linux-lifecycle.serial.test.ts": 11590,
- "test/e2e/backfill-perf-pglite.test.ts": 4300,
- "test/e2e/bootstrap-attach.serial.test.ts": 4350,
- "test/e2e/bootstrap-compiled-binary.serial.test.ts": 3900,
- "test/e2e/bootstrap-degraded-modes.serial.test.ts": 4490,
- "test/e2e/bootstrap-harness-lifecycle.serial.test.ts": 7480,
- "test/e2e/bootstrap-hook-under-serve.serial.test.ts": 6160,
- "test/e2e/bootstrap-keyed-postgres.serial.test.ts": 897,
- "test/e2e/bootstrap-lifecycle.serial.test.ts": 5450,
- "test/e2e/bootstrap-magic-moment.serial.test.ts": 4270,
- "test/e2e/bootstrap-persistence.serial.test.ts": 781,
- "test/e2e/bootstrap-real-claude.serial.test.ts": 381,
- "test/e2e/bootstrap-real-codex.serial.test.ts": 388,
- "test/e2e/brainstorm-resume.test.ts": 1830,
- "test/e2e/cache-gate-pglite.test.ts": 2380,
- "test/e2e/calibration-profile-write.test.ts": 1900,
- "test/e2e/capture-generation-regression.test.ts": 1920,
- "test/e2e/chronicle-event-projection-parity.test.ts": 1890,
- "test/e2e/chronicle-last-seen-postgres.test.ts": 1016,
- "test/e2e/chunk-canonical-text-privacy.test.ts": 1880,
- "test/e2e/chunker-takes-strip.test.ts": 1166,
- "test/e2e/cjk-roundtrip.test.ts": 1499,
- "test/e2e/claude-plugin-install-real.serial.test.ts": 364,
- "test/e2e/claw-test.test.ts": 67970,
- "test/e2e/cli-source-scoping-pglite.test.ts": 1520,
- "test/e2e/client-grants.test.ts": 1630,
- "test/e2e/code-edges-jsonb-postgres.test.ts": 998,
- "test/e2e/code-edges-read-parity.test.ts": 1970,
- "test/e2e/code-indexing.test.ts": 2530,
- "test/e2e/code-intel-mcp-ops-pglite.test.ts": 3720,
- "test/e2e/codex-plugin-install-real.serial.test.ts": 363,
- "test/e2e/compile-context-pglite.test.ts": 1400,
- "test/e2e/concurrent-embed-race.test.ts": 1131,
- "test/e2e/connect-bearer.test.ts": 9870,
- "test/e2e/connector-sync-handler-pglite.test.ts": 1610,
- "test/e2e/connectors-sync-pglite.test.ts": 5840,
- "test/e2e/contextual-retrieval-pglite.test.ts": 2270,
- "test/e2e/conversation-parser-pglite.test.ts": 4690,
- "test/e2e/cross-modal-eval.test.ts": 157,
- "test/e2e/cycle-consolidate-postgres.test.ts": 1040,
- "test/e2e/cycle-recompute-emotional-weight-pglite.test.ts": 1187,
- "test/e2e/cycle.test.ts": 1730,
- "test/e2e/db-guard.test.ts": 279,
- "test/e2e/db-singleton-shared-recovery.test.ts": 213,
- "test/e2e/delegated-grants-withdrawal.test.ts": 1385,
- "test/e2e/delegated-http-worker.test.ts": 2230,
- "test/e2e/doctor-connectors-pglite.test.ts": 1730,
- "test/e2e/doctor-progress.test.ts": 7050,
- "test/e2e/doctor-silent-death-parity.test.ts": 2700,
- "test/e2e/dream-allow-list-pglite.test.ts": 1433,
- "test/e2e/dream-cycle-phase-order-pglite.test.ts": 2740,
- "test/e2e/dream-patterns-pglite.test.ts": 3410,
- "test/e2e/dream-synthesize-chunking.test.ts": 8300,
- "test/e2e/dream-synthesize-concurrency-postgres.test.ts": 9550,
- "test/e2e/dream-triage-postgres.test.ts": 1088,
- "test/e2e/dream.test.ts": 1610,
- "test/e2e/embed-stale-pagination.test.ts": 1490,
- "test/e2e/embedding-column-pglite.test.ts": 1202,
- "test/e2e/embedding-column-postgres.test.ts": 378,
- "test/e2e/engine-content-privacy.test.ts": 4180,
- "test/e2e/engine-parity-cjk.test.ts": 2260,
- "test/e2e/engine-parity-salience.test.ts": 4490,
- "test/e2e/enrich-pglite.test.ts": 5340,
- "test/e2e/eval-capture.test.ts": 387,
- "test/e2e/eval-contradictions-postgres.test.ts": 533,
- "test/e2e/eval-loop.test.ts": 1165,
- "test/e2e/eval-replay-column.test.ts": 989,
- "test/e2e/eval-takes-quality.test.ts": 983,
- "test/e2e/extract-atoms-discovery-sql.test.ts": 1016,
- "test/e2e/extraction-review-postgres.test.ts": 1173,
- "test/e2e/facts-context-injection-postgres.test.ts": 969,
- "test/e2e/facts-cross-source-isolation.test.ts": 975,
- "test/e2e/facts-fence-reconcile-postgres.test.ts": 980,
- "test/e2e/facts-forget.test.ts": 1010,
- "test/e2e/facts-notability-roundtrip.test.ts": 1015,
- "test/e2e/facts-recall-event-time-postgres.test.ts": 1004,
- "test/e2e/facts-recall-render.test.ts": 1041,
- "test/e2e/facts-separation-postgres.test.ts": 1018,
- "test/e2e/fresh-install-pglite.test.ts": 19980,
- "test/e2e/frontmatter-migration.test.ts": 3260,
- "test/e2e/global-basename-pglite.test.ts": 1700,
- "test/e2e/graph-quality.test.ts": 1810,
- "test/e2e/graph-signals-engine.test.ts": 1004,
- "test/e2e/graph-signals-eval.test.ts": 3220,
- "test/e2e/harness-access.test.ts": 4770,
- "test/e2e/health-parity-postgres.test.ts": 2040,
- "test/e2e/http-transport.test.ts": 1317,
- "test/e2e/import-credential-preflight.test.ts": 1530,
- "test/e2e/ingestion-roundtrip.test.ts": 2850,
- "test/e2e/init-fresh-pglite.test.ts": 39380,
- "test/e2e/install-real-grok.serial.test.ts": 300,
- "test/e2e/install-real-hermes.serial.test.ts": 278,
- "test/e2e/install-real-opencode.serial.test.ts": 282,
- "test/e2e/integrity-batch.test.ts": 1236,
- "test/e2e/jobs-agent-scope-postgres.test.ts": 998,
- "test/e2e/jobs-watch-readsnapshot.test.ts": 1120,
- "test/e2e/jsonb-batch-poison-postgres.test.ts": 1620,
- "test/e2e/legacy-chunk-privacy.test.ts": 4480,
- "test/e2e/link-source-check-repair-postgres.test.ts": 958,
- "test/e2e/list-all-sources-postgres.test.ts": 985,
- "test/e2e/list-pages-regression.test.ts": 1013,
- "test/e2e/mcp-budget-reservation-postgres.test.ts": 478,
- "test/e2e/migrate-chain.test.ts": 2970,
- "test/e2e/migrate-embeddings-postgres.test.ts": 1241,
- "test/e2e/migrate-engine-pglite-to-postgres.test.ts": 5970,
- "test/e2e/migrate-engine-sources-postgres.test.ts": 1800,
- "test/e2e/migration-drop-invalid-concurrent-index.test.ts": 962,
- "test/e2e/migration-flow.test.ts": 3940,
- "test/e2e/migration-v35-auto-rls.test.ts": 971,
- "test/e2e/migration-v35-event-trigger.test.ts": 949,
- "test/e2e/migration-v47-notability.test.ts": 947,
- "test/e2e/migration-v50-ingest-log-source-id.test.ts": 952,
- "test/e2e/minions-authority-parity.test.ts": 1082,
- "test/e2e/minions-budget-cathedral.test.ts": 1308,
- "test/e2e/minions-concurrency.test.ts": 1444,
- "test/e2e/minions-controller-bounce-only.test.ts": 1233,
- "test/e2e/minions-field-report-repro.test.ts": 26100,
- "test/e2e/minions-prefix-strip-smoke.test.ts": 1081,
- "test/e2e/minions-resilience.test.ts": 12360,
- "test/e2e/minions-self-fix-flow.test.ts": 1163,
- "test/e2e/minions-shell-pglite.test.ts": 1780,
- "test/e2e/minions-shell.test.ts": 1343,
- "test/e2e/mounts-routing-pglite.test.ts": 27570,
- "test/e2e/multi-source-bug-class.test.ts": 4130,
- "test/e2e/multi-source-emotional-weight-pglite.test.ts": 979,
- "test/e2e/multi-source.test.ts": 4950,
- "test/e2e/multimodal-postgres.test.ts": 1282,
- "test/e2e/non-tty-output.serial.test.ts": 5710,
- "test/e2e/oauth-grant-transactions.test.ts": 1090,
- "test/e2e/onboard-full-flow.test.ts": 1168,
- "test/e2e/ontology-merge-parity.test.ts": 1810,
- "test/e2e/openclaw-context-engine-plugin.test.ts": 215,
- "test/e2e/openclaw-plugin-load-real.test.ts": 154,
- "test/e2e/openclaw-reference-compat.test.ts": 979,
- "test/e2e/openrouter-anthropic-subagent-replay.live.test.ts": 1255,
- "test/e2e/openrouter-deepseek-subagent-replay.live.test.ts": 1255,
- "test/e2e/orphan-reduction.test.ts": 3170,
- "test/e2e/pgbouncer-teardown.test.ts": 185,
- "test/e2e/pglite-cli-exit.serial.test.ts": 32299.999999999996,
- "test/e2e/phantom-redirect.test.ts": 31570,
- "test/e2e/postgres-engine-disconnect-idempotency.test.ts": 245,
- "test/e2e/postgres-jsonb.test.ts": 945,
- "test/e2e/postgres-reconnect-singleton.test.ts": 265,
- "test/e2e/propose-takes-jsonb-postgres.test.ts": 962,
- "test/e2e/purge-deleted-dryrun-postgres.test.ts": 993,
- "test/e2e/qm-provisioning.test.ts": 24710,
- "test/e2e/quarantine-search-exclusion.test.ts": 2350,
- "test/e2e/read-enrichment-privacy.test.ts": 3630,
- "test/e2e/remote-privacy-journeys.test.ts": 17670,
- "test/e2e/restore-source-config-jsonb-postgres.test.ts": 954,
- "test/e2e/salience-anomalies-source-isolation-pglite.test.ts": 1257,
- "test/e2e/salience-llm-routing.test.ts": 156,
- "test/e2e/salience-pglite.test.ts": 1445,
- "test/e2e/schema-cathedral.test.ts": 4390,
- "test/e2e/schema-drift.test.ts": 4190,
- "test/e2e/search-exclude.test.ts": 1290,
- "test/e2e/search-quality.test.ts": 1140,
- "test/e2e/search-swamp.test.ts": 1110,
- "test/e2e/self-upgrade-binary-swap.test.ts": 177,
- "test/e2e/self-upgrade-marker.test.ts": 3800,
- "test/e2e/serve-http-consent.test.ts": 3830,
- "test/e2e/serve-http-ingest-webhook.test.ts": 25750,
- "test/e2e/serve-http-meta.test.ts": 928,
- "test/e2e/serve-http-oauth.test.ts": 16490,
- "test/e2e/serve-http-source-grant.test.ts": 3170,
- "test/e2e/serve-http-surface-ceiling.test.ts": 14820,
- "test/e2e/serve-http-takes-holders.test.ts": 3190,
- "test/e2e/serve-stdio-roundtrip.test.ts": 16309.999999999998,
- "test/e2e/skill-brain-first.test.ts": 488,
- "test/e2e/skillopt-loop.serial.test.ts": 4090,
- "test/e2e/skillopt-pglite.serial.test.ts": 1650,
- "test/e2e/skillpack-flow.test.ts": 10440,
- "test/e2e/skillpack-third-party.test.ts": 5490,
- "test/e2e/source-boundary-mutation-postgres.test.ts": 1049,
- "test/e2e/source-isolation-pglite.test.ts": 4040,
- "test/e2e/source-routing.test.ts": 1240,
- "test/e2e/sources-remote-mcp.test.ts": 7160,
- "test/e2e/status-pglite.test.ts": 2160,
- "test/e2e/storage-tiering.test.ts": 1530,
- "test/e2e/subagent-crash-replay-multi-provider.test.ts": 3080,
- "test/e2e/subagent-gateway-path.test.ts": 3220,
- "test/e2e/subagent-gateway-resume-reconciliation.test.ts": 2250,
- "test/e2e/symbol-resolver-pglite.test.ts": 1830,
- "test/e2e/sync-cjk-git.test.ts": 311,
- "test/e2e/sync-credential-preflight.test.ts": 2230,
- "test/e2e/sync-lock-recovery.test.ts": 4750,
- "test/e2e/sync-parallel.test.ts": 4750,
- "test/e2e/sync-sigkill-resume-postgres.test.ts": 11380,
- "test/e2e/sync-status-pglite.test.ts": 1269,
- "test/e2e/sync.test.ts": 3100,
- "test/e2e/synthesize-bigint-job-id-postgres.test.ts": 963,
- "test/e2e/system-of-record-invariant.test.ts": 2150,
- "test/e2e/takes-postgres.test.ts": 1075,
- "test/e2e/takes-scorecard-parity.test.ts": 1900,
- "test/e2e/takes-weight-rounding-postgres.test.ts": 990,
- "test/e2e/takes-write-ops-postgres.test.ts": 3040,
- "test/e2e/thin-client.test.ts": 13280,
- "test/e2e/think-source-isolation-pglite.test.ts": 1550,
- "test/e2e/think-trajectory-pglite.test.ts": 1800,
- "test/e2e/transcripts-ingest-pglite.test.ts": 7610,
- "test/e2e/transcripts-writeback-fidelity.test.ts": 2450,
- "test/e2e/type-unification-full-flow.test.ts": 2530,
- "test/e2e/upgrade-bun-link-arc.serial.test.ts": 5330,
- "test/e2e/upgrade.test.ts": 3120,
- "test/e2e/upsert-chunks-registry-column.test.ts": 1740,
- "test/e2e/v030_1-integration-pglite.test.ts": 28770,
- "test/e2e/v0_28_5-fix-wave.test.ts": 11550,
- "test/e2e/v0_29-mcp-dispatch-pglite.test.ts": 1247,
- "test/e2e/v0_30_3-fix-wave.test.ts": 10300,
- "test/e2e/vector-ef-search-postgres.test.ts": 2390,
- "test/e2e/volunteer-context-postgres.test.ts": 952,
- "test/e2e/whoknows.test.ts": 1690,
- "test/e2e/worker-abort-recovery.test.ts": 4770,
- "test/e2e/worker-lock-renewal-starvation.test.ts": 3740,
- "test/e2e/workspace-generic-compat.test.ts": 601,
- "test/e2e/zombie-reaping.test.ts": 9510
+ "test/e2e/anomalies-pglite.test.ts": 2180,
+ "test/e2e/auth-permissions.test.ts": 1810,
+ "test/e2e/auth-takes-holders-pglite.test.ts": 1070,
+ "test/e2e/autopilot-cooldown-parity.test.ts": 1950,
+ "test/e2e/autopilot-fanout-postgres.test.ts": 1308,
+ "test/e2e/autopilot-linux-lifecycle.serial.test.ts": 12420,
+ "test/e2e/backfill-perf-pglite.test.ts": 10760,
+ "test/e2e/backup-coverage-parity.test.ts": 2230,
+ "test/e2e/bootstrap-attach.serial.test.ts": 5010,
+ "test/e2e/bootstrap-compiled-binary.serial.test.ts": 4059.9999999999995,
+ "test/e2e/bootstrap-degraded-modes.serial.test.ts": 5730,
+ "test/e2e/bootstrap-harness-lifecycle.serial.test.ts": 8280,
+ "test/e2e/bootstrap-hook-under-serve.serial.test.ts": 9780,
+ "test/e2e/bootstrap-keyed-postgres.serial.test.ts": 2580,
+ "test/e2e/bootstrap-lifecycle.serial.test.ts": 6390,
+ "test/e2e/bootstrap-magic-moment.serial.test.ts": 4980,
+ "test/e2e/bootstrap-persistence.serial.test.ts": 806,
+ "test/e2e/bootstrap-real-claude.serial.test.ts": 559,
+ "test/e2e/bootstrap-real-codex.serial.test.ts": 593,
+ "test/e2e/brainstorm-resume.test.ts": 2170,
+ "test/e2e/cache-gate-pglite.test.ts": 2160,
+ "test/e2e/calibration-profile-write.test.ts": 2320,
+ "test/e2e/capture-generation-regression.test.ts": 1910,
+ "test/e2e/chronicle-event-projection-parity.test.ts": 2070,
+ "test/e2e/chronicle-last-seen-postgres.test.ts": 1055,
+ "test/e2e/chunk-canonical-text-privacy.test.ts": 2160,
+ "test/e2e/chunker-takes-strip.test.ts": 1260,
+ "test/e2e/cjk-roundtrip.test.ts": 1670,
+ "test/e2e/claude-plugin-install-real.serial.test.ts": 544,
+ "test/e2e/claw-test.test.ts": 185940,
+ "test/e2e/cli-source-scoping-pglite.test.ts": 1560,
+ "test/e2e/client-grants.test.ts": 1850,
+ "test/e2e/code-edges-jsonb-postgres.test.ts": 1149,
+ "test/e2e/code-edges-read-parity.test.ts": 2230,
+ "test/e2e/code-indexing.test.ts": 3100,
+ "test/e2e/code-intel-mcp-ops-pglite.test.ts": 2970,
+ "test/e2e/codex-plugin-install-real.serial.test.ts": 540,
+ "test/e2e/company-brain-receipts.test.ts": 846,
+ "test/e2e/compile-context-pglite.test.ts": 1640,
+ "test/e2e/concurrent-embed-race.test.ts": 1251,
+ "test/e2e/connect-bearer.test.ts": 10690,
+ "test/e2e/connector-sync-handler-pglite.test.ts": 1690,
+ "test/e2e/connectors-sync-pglite.test.ts": 5680,
+ "test/e2e/contextual-retrieval-pglite.test.ts": 2640,
+ "test/e2e/conversation-parser-pglite.test.ts": 3860,
+ "test/e2e/cross-modal-eval.test.ts": 176,
+ "test/e2e/cycle-consolidate-postgres.test.ts": 1160,
+ "test/e2e/cycle-recompute-emotional-weight-pglite.test.ts": 1307,
+ "test/e2e/cycle.test.ts": 2250,
+ "test/e2e/db-guard.test.ts": 288,
+ "test/e2e/db-lock-acquisition-token.test.ts": 438,
+ "test/e2e/db-singleton-shared-recovery.test.ts": 288,
+ "test/e2e/deep-research-http.test.ts": 2580,
+ "test/e2e/deep-research-source-id.test.ts": 4440,
+ "test/e2e/delegated-grants-withdrawal.test.ts": 1670,
+ "test/e2e/delegated-http-worker.test.ts": 2630,
+ "test/e2e/doctor-connectors-pglite.test.ts": 1670,
+ "test/e2e/doctor-progress.test.ts": 7650,
+ "test/e2e/doctor-silent-death-parity.test.ts": 3260,
+ "test/e2e/dream-allow-list-pglite.test.ts": 2490,
+ "test/e2e/dream-cycle-phase-order-pglite.test.ts": 3230,
+ "test/e2e/dream-patterns-pglite.test.ts": 4010,
+ "test/e2e/dream-synthesize-chunking.test.ts": 9090,
+ "test/e2e/dream-synthesize-concurrency-postgres.test.ts": 12860,
+ "test/e2e/dream-synthesize-pglite.test.ts": 14040,
+ "test/e2e/dream-triage-postgres.test.ts": 1329,
+ "test/e2e/dream.test.ts": 2100,
+ "test/e2e/embed-stale-pagination.test.ts": 1780,
+ "test/e2e/embedding-column-pglite.test.ts": 1494,
+ "test/e2e/embedding-column-postgres.test.ts": 565,
+ "test/e2e/engine-content-privacy.test.ts": 6270,
+ "test/e2e/engine-parity-cjk.test.ts": 2810,
+ "test/e2e/engine-parity-salience.test.ts": 5860,
+ "test/e2e/engine-parity.test.ts": 51460,
+ "test/e2e/enrich-pglite.test.ts": 5480,
+ "test/e2e/eval-capture.test.ts": 472,
+ "test/e2e/eval-contradictions-postgres.test.ts": 751,
+ "test/e2e/eval-loop.test.ts": 1455,
+ "test/e2e/eval-replay-column.test.ts": 1131,
+ "test/e2e/eval-takes-quality.test.ts": 1252,
+ "test/e2e/extract-atoms-discovery-sql.test.ts": 1354,
+ "test/e2e/extract-atoms-page-state.test.ts": 2650,
+ "test/e2e/extraction-review-postgres.test.ts": 1580,
+ "test/e2e/fact-backfill-resident.test.ts": 7820,
+ "test/e2e/fact-embedding-backfill-parity.test.ts": 5570,
+ "test/e2e/fact-vector-repair-parity.test.ts": 5000,
+ "test/e2e/facts-context-injection-postgres.test.ts": 1273,
+ "test/e2e/facts-cross-source-isolation.test.ts": 1244,
+ "test/e2e/facts-fence-reconcile-postgres.test.ts": 1119,
+ "test/e2e/facts-forget.test.ts": 1334,
+ "test/e2e/facts-notability-roundtrip.test.ts": 1271,
+ "test/e2e/facts-recall-event-time-postgres.test.ts": 1249,
+ "test/e2e/facts-recall-render.test.ts": 1270,
+ "test/e2e/facts-separation-postgres.test.ts": 1269,
+ "test/e2e/facts-worker-config.test.ts": 2420,
+ "test/e2e/fresh-install-pglite.test.ts": 23380,
+ "test/e2e/frontmatter-migration.test.ts": 3490,
+ "test/e2e/global-basename-pglite.test.ts": 2890,
+ "test/e2e/grandfather-projection-postgres.test.ts": 5350,
+ "test/e2e/graph-quality.test.ts": 3420,
+ "test/e2e/graph-signals-engine.test.ts": 1201,
+ "test/e2e/graph-signals-eval.test.ts": 4300,
+ "test/e2e/harness-access.test.ts": 5510,
+ "test/e2e/health-parity-postgres.test.ts": 2540,
+ "test/e2e/http-transport.test.ts": 1660,
+ "test/e2e/import-credential-preflight.test.ts": 1790,
+ "test/e2e/ingestion-roundtrip.test.ts": 2860,
+ "test/e2e/init-fresh-pglite.test.ts": 44500,
+ "test/e2e/install-real-grok.serial.test.ts": 557,
+ "test/e2e/install-real-hermes.serial.test.ts": 521,
+ "test/e2e/install-real-opencode.serial.test.ts": 509,
+ "test/e2e/integrity-batch.test.ts": 1580,
+ "test/e2e/job-isolation.test.ts": 2230,
+ "test/e2e/jobs-agent-scope-postgres.test.ts": 1352,
+ "test/e2e/jobs-watch-readsnapshot.test.ts": 1230,
+ "test/e2e/jsonb-batch-poison-postgres.test.ts": 2009.9999999999998,
+ "test/e2e/jsonb-roundtrip.test.ts": 1270,
+ "test/e2e/legacy-chunk-privacy.test.ts": 6140,
+ "test/e2e/link-source-check-repair-postgres.test.ts": 1276,
+ "test/e2e/list-all-sources-postgres.test.ts": 1322,
+ "test/e2e/list-pages-regression.test.ts": 1143,
+ "test/e2e/managed-atom-compaction.test.ts": 6290,
+ "test/e2e/managed-atom-regressions.test.ts": 11080,
+ "test/e2e/managed-connector-fencing.test.ts": 19870,
+ "test/e2e/managed-connector-recovery.test.ts": 69810,
+ "test/e2e/managed-connector-retry.test.ts": 107360,
+ "test/e2e/managed-connector-routing.test.ts": 111810,
+ "test/e2e/managed-extract-atoms.test.ts": 14550,
+ "test/e2e/managed-facts-backstop.test.ts": 12030,
+ "test/e2e/managed-facts-compaction.test.ts": 34970,
+ "test/e2e/managed-facts-embedding.test.ts": 36200,
+ "test/e2e/managed-maintenance.test.ts": 85980,
+ "test/e2e/managed-sync-failures.test.ts": 56060,
+ "test/e2e/managed-synthesis-postprocess.test.ts": 20490,
+ "test/e2e/mcp-budget-reservation-postgres.test.ts": 582,
+ "test/e2e/mcp.test.ts": 473,
+ "test/e2e/mechanical.test.ts": 68280,
+ "test/e2e/migrate-chain.test.ts": 3460,
+ "test/e2e/migrate-embeddings-postgres.test.ts": 1760,
+ "test/e2e/migrate-engine-pglite-to-postgres.test.ts": 7000,
+ "test/e2e/migrate-engine-sources-postgres.test.ts": 2320,
+ "test/e2e/migration-drop-invalid-concurrent-index.test.ts": 1278,
+ "test/e2e/migration-flow.test.ts": 4290,
+ "test/e2e/migration-preview-safety.test.ts": 12610,
+ "test/e2e/migration-v35-auto-rls.test.ts": 1251,
+ "test/e2e/migration-v35-event-trigger.test.ts": 1297,
+ "test/e2e/migration-v47-notability.test.ts": 1258,
+ "test/e2e/migration-v50-ingest-log-source-id.test.ts": 1257,
+ "test/e2e/minions-authority-parity.test.ts": 1426,
+ "test/e2e/minions-budget-cathedral.test.ts": 1394,
+ "test/e2e/minions-concurrency.test.ts": 1730,
+ "test/e2e/minions-controller-bounce-only.test.ts": 1305,
+ "test/e2e/minions-field-report-repro.test.ts": 26470,
+ "test/e2e/minions-prefix-strip-smoke.test.ts": 1417,
+ "test/e2e/minions-resilience.test.ts": 12690,
+ "test/e2e/minions-self-fix-flow.test.ts": 1243,
+ "test/e2e/minions-shell-pglite.test.ts": 2050,
+ "test/e2e/minions-shell.test.ts": 1680,
+ "test/e2e/mounts-routing-pglite.test.ts": 31030,
+ "test/e2e/multi-source-bug-class.test.ts": 3520,
+ "test/e2e/multi-source-emotional-weight-pglite.test.ts": 1168,
+ "test/e2e/multi-source.test.ts": 5470,
+ "test/e2e/multimodal-postgres.test.ts": 1690,
+ "test/e2e/non-tty-output.serial.test.ts": 6580,
+ "test/e2e/oauth-grant-transactions.test.ts": 1550,
+ "test/e2e/onboard-full-flow.test.ts": 1314,
+ "test/e2e/ontology-merge-parity.test.ts": 2270,
+ "test/e2e/op-checkpoint-jsonb-parity.test.ts": 1276,
+ "test/e2e/openclaw-context-engine-plugin.test.ts": 322,
+ "test/e2e/openclaw-plugin-load-real.test.ts": 179,
+ "test/e2e/openclaw-reference-compat.test.ts": 1372,
+ "test/e2e/openrouter-anthropic-subagent-replay.live.test.ts": 1560,
+ "test/e2e/openrouter-deepseek-subagent-replay.live.test.ts": 1500,
+ "test/e2e/orphan-reduction.test.ts": 4090,
+ "test/e2e/persistence-admin-intent.test.ts": 10430,
+ "test/e2e/persistence-chaos.test.ts": 28520,
+ "test/e2e/persistence-embedding-effects.test.ts": 148840,
+ "test/e2e/persistence-recovery.test.ts": 20220,
+ "test/e2e/persistence-runtime-matrix.test.ts": 345,
+ "test/e2e/persistence-skill-bundles-postgres.test.ts": 61040,
+ "test/e2e/pgbouncer-teardown.test.ts": 279,
+ "test/e2e/pglite-cli-exit.serial.test.ts": 37690,
+ "test/e2e/phantom-redirect.test.ts": 32350,
+ "test/e2e/postgres-bootstrap.test.ts": 2730,
+ "test/e2e/postgres-engine-disconnect-idempotency.test.ts": 320,
+ "test/e2e/postgres-jsonb.test.ts": 1275,
+ "test/e2e/postgres-reconnect-singleton.test.ts": 338,
+ "test/e2e/projection-readiness-currency.test.ts": 1324,
+ "test/e2e/projection-recovery-parity.test.ts": 21780,
+ "test/e2e/projection-statistics-postgres.test.ts": 368,
+ "test/e2e/propose-takes-jsonb-postgres.test.ts": 1276,
+ "test/e2e/purge-deleted-dryrun-postgres.test.ts": 1256,
+ "test/e2e/put-page-persistence-postgres.test.ts": 12410,
+ "test/e2e/qm-provisioning.test.ts": 28260,
+ "test/e2e/quarantine-search-exclusion.test.ts": 2760,
+ "test/e2e/read-enrichment-privacy.test.ts": 5630,
+ "test/e2e/reconcile-crash-unactivated.test.ts": 97900,
+ "test/e2e/reconcile-crash.test.ts": 97840,
+ "test/e2e/reconcile-pgbouncer.test.ts": 482,
+ "test/e2e/remote-privacy-journeys.test.ts": 19870,
+ "test/e2e/restore-source-config-jsonb-postgres.test.ts": 1246,
+ "test/e2e/salience-anomalies-source-isolation-pglite.test.ts": 1610,
+ "test/e2e/salience-llm-routing.test.ts": 177,
+ "test/e2e/salience-pglite.test.ts": 2200,
+ "test/e2e/schema-cathedral.test.ts": 4320,
+ "test/e2e/schema-drift.test.ts": 4600,
+ "test/e2e/search-exclude.test.ts": 1650,
+ "test/e2e/search-quality.test.ts": 1499,
+ "test/e2e/search-query-contract-postgres.test.ts": 2300,
+ "test/e2e/search-readiness-http.test.ts": 8650,
+ "test/e2e/search-swamp.test.ts": 1408,
+ "test/e2e/self-upgrade-binary-swap.test.ts": 194,
+ "test/e2e/self-upgrade-marker.test.ts": 4420,
+ "test/e2e/serve-http-consent.test.ts": 4290,
+ "test/e2e/serve-http-ingest-webhook.test.ts": 31480,
+ "test/e2e/serve-http-meta.test.ts": 1302,
+ "test/e2e/serve-http-multi-agent.test.ts": 19360,
+ "test/e2e/serve-http-oauth.test.ts": 21020,
+ "test/e2e/serve-http-source-grant.test.ts": 3530,
+ "test/e2e/serve-http-surface-ceiling.test.ts": 16810,
+ "test/e2e/serve-http-takes-holders.test.ts": 3340,
+ "test/e2e/serve-stdio-roundtrip.test.ts": 19790,
+ "test/e2e/shared-skills-rls.test.ts": 2070,
+ "test/e2e/shared-skills-transports.test.ts": 15630,
+ "test/e2e/skill-brain-first.test.ts": 828,
+ "test/e2e/skillopt-loop.serial.test.ts": 6290,
+ "test/e2e/skillopt-pglite.serial.test.ts": 1980,
+ "test/e2e/skillpack-flow.test.ts": 13680,
+ "test/e2e/skillpack-third-party.test.ts": 6400,
+ "test/e2e/skills.test.ts": 318,
+ "test/e2e/source-boundary-mutation-postgres.test.ts": 1152,
+ "test/e2e/source-isolation-pglite.test.ts": 4280,
+ "test/e2e/source-routing.test.ts": 1411,
+ "test/e2e/sources-remote-mcp.test.ts": 14180,
+ "test/e2e/status-pglite.test.ts": 1950,
+ "test/e2e/storage-tiering.test.ts": 1950,
+ "test/e2e/subagent-crash-replay-multi-provider.test.ts": 2620,
+ "test/e2e/subagent-gateway-path.test.ts": 2690,
+ "test/e2e/subagent-gateway-resume-reconciliation.test.ts": 2240,
+ "test/e2e/symbol-resolver-pglite.test.ts": 1820,
+ "test/e2e/sync-cjk-git.test.ts": 386,
+ "test/e2e/sync-credential-preflight.test.ts": 2600,
+ "test/e2e/sync-delegation-under-serve.serial.test.ts": 113410,
+ "test/e2e/sync-lock-overlap-postgres.test.ts": 10270,
+ "test/e2e/sync-lock-recovery.test.ts": 5480,
+ "test/e2e/sync-parallel.test.ts": 7650,
+ "test/e2e/sync-reconcile-postgres.test.ts": 2090,
+ "test/e2e/sync-sigkill-resume-postgres.test.ts": 13620,
+ "test/e2e/sync-status-pglite.test.ts": 1570,
+ "test/e2e/sync.test.ts": 3740,
+ "test/e2e/synthesize-bigint-job-id-postgres.test.ts": 1272,
+ "test/e2e/system-of-record-invariant.test.ts": 3300,
+ "test/e2e/takes-postgres.test.ts": 1419,
+ "test/e2e/takes-scorecard-parity.test.ts": 2090,
+ "test/e2e/takes-weight-rounding-postgres.test.ts": 1074,
+ "test/e2e/takes-write-ops-postgres.test.ts": 15360,
+ "test/e2e/thin-client.test.ts": 14770,
+ "test/e2e/think-source-isolation-pglite.test.ts": 1860,
+ "test/e2e/think-trajectory-pglite.test.ts": 2000,
+ "test/e2e/transcripts-ingest-pglite.test.ts": 8590,
+ "test/e2e/transcripts-writeback-fidelity.test.ts": 2590,
+ "test/e2e/type-unification-full-flow.test.ts": 2670,
+ "test/e2e/upgrade-bun-link-arc.serial.test.ts": 9250,
+ "test/e2e/upgrade.test.ts": 3180,
+ "test/e2e/upsert-chunks-registry-column.test.ts": 2520,
+ "test/e2e/v030_1-integration-pglite.test.ts": 31010,
+ "test/e2e/v0_28_5-fix-wave.test.ts": 12890,
+ "test/e2e/v0_29-mcp-dispatch-pglite.test.ts": 1710,
+ "test/e2e/v0_30_3-fix-wave.test.ts": 11110,
+ "test/e2e/vector-candidate-safety-postgres.test.ts": 26430,
+ "test/e2e/vector-ef-search-postgres.test.ts": 5330,
+ "test/e2e/volunteer-context-postgres.test.ts": 1241,
+ "test/e2e/voyage-multimodal.test.ts": 175,
+ "test/e2e/voyage-rerank-live.test.ts": 162,
+ "test/e2e/whoknows.test.ts": 2450,
+ "test/e2e/worker-abort-recovery.test.ts": 5050,
+ "test/e2e/worker-lock-renewal-starvation.test.ts": 4040,
+ "test/e2e/workspace-generic-compat.test.ts": 1028,
+ "test/e2e/zeroentropy-live.test.ts": 192,
+ "test/e2e/zombie-reaping.test.ts": 10290,
+ "test/phantom-redirect-engine-parity.test.ts": 2500
}
diff --git a/scripts/e2e-weights.metadata.json b/scripts/e2e-weights.metadata.json
index 3e544ab9fd..5a212b9561 100644
--- a/scripts/e2e-weights.metadata.json
+++ b/scripts/e2e-weights.metadata.json
@@ -1,10 +1,20 @@
{
"lane": "e2e",
"unit": "milliseconds",
- "run": "34998157990",
- "commit": "f1fbdfba193383785b555b507f5c817003944aea",
+ "run": "35964154815",
+ "commit": "31f257a0a7b218b40e03d302bc6913c99f26f0ec",
"source": "github",
- "measuredFiles": 221,
- "totalFiles": 221,
- "mergeExisting": true
+ "measuredFiles": 281,
+ "totalFiles": 281,
+ "mergeExisting": false,
+ "e2eProfile": "full",
+ "attempt": 1,
+ "jobs": [
+ {
+ "name": "coverage-full-e2e",
+ "databaseId": 107518932797
+ }
+ ],
+ "logSha256": "1dc25d62f3e77b869a0e8b86ee4c322de0f28664faf98a1a4c9b1f860f12751a",
+ "corpusSha256": "d7a0ea816cc73b3c0b98ddada578cc5f97252ac9f26c0f67990940e352407d55"
}
diff --git a/scripts/mine-shard-weights.ts b/scripts/mine-shard-weights.ts
index 69324fb6e0..cd0d8aff49 100644
--- a/scripts/mine-shard-weights.ts
+++ b/scripts/mine-shard-weights.ts
@@ -2,17 +2,21 @@
/** Mine timings from successful CI execution in its real execution mode.
* Unit: consecutive headers + final Bun summary, milliseconds.
* Serial: per-file runner PASS records, seconds (not buffered log timestamps).
- * E2E: per-file Bun summaries, milliseconds. Partial selections merge old weights.
+ * E2E: per-file Bun summaries, milliseconds. Partial selections merge old weights;
+ * explicit full-profile runs replace them after source-corpus validation.
* Refresh after large test additions or sustained shard imbalance.
*/
import { spawnSync } from "node:child_process";
-import { readFileSync, writeFileSync, renameSync, rmSync, existsSync } from "node:fs";
-import { dirname, resolve } from "node:path";
+import { readFileSync, writeFileSync, renameSync, rmSync, existsSync, mkdtempSync, mkdirSync } from "node:fs";
+import { basename, dirname, join, resolve } from "node:path";
+import { tmpdir } from "node:os";
+import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { loadWeights } from "./sharding.ts";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
export type Lane = "unit" | "serial" | "e2e";
+type E2EProfile = "selected" | "full";
const OUTPUTS = { unit: "test-weights", serial: "serial-weights", e2e: "e2e-weights" };
interface TimingEvent { job: string; timestampMs: number; file: string; summaryCount?: number; failures?: number }
interface LogLine { job: string; step: string; timestampMs: number; text: string }
@@ -23,9 +27,10 @@ function logLines(raw: string): LogLine[] {
return [{ job: m[1]!.trim(), step: m[2]!.trim(), timestampMs: Date.parse(m[3]!), text: m[4]!.replace(/\x1b\[[0-9;]*m/g, "") }];
});
}
-function isJob(job: string, lane: Lane): boolean {
+function isJob(job: string, lane: Lane, e2eProfile: E2EProfile = "selected"): boolean {
if (lane === "unit") return /^test \(\d+\)$/.test(job);
if (lane === "serial") return /^serial-tests(?: \(\d+\))?$/.test(job);
+ if (e2eProfile === "full") return /^coverage-full-e2e(?: \(\d+\))?$/.test(job);
return /^Selected E2E \(diff-relevant\)(?: \(\d+\)| \d+)?$/.test(job);
}
@@ -65,8 +70,17 @@ export function computeWeights(events: TimingEvent[]): Map<string, number> {
}
/** Refuse partial/failed sources before any output is replaced. */
-export function mineWeights(raw: string, lane: Lane, opts: { expectedJobs?: readonly string[] } = {}): Map<string, number> {
- const lines = logLines(raw).filter(line => isJob(line.job, lane));
+export function mineWeights(raw: string, lane: Lane, opts: { expectedJobs?: readonly string[]; e2eProfile?: E2EProfile; expectedFiles?: readonly string[] } = {}): Map<string, number> {
+ const full = opts.e2eProfile === "full";
+ const fullPaths = new Map<string, string>();
+ if (full) {
+ if (lane !== "e2e" || !opts.expectedFiles?.length) throw new Error("full E2E requires an authoritative source corpus");
+ for (const file of opts.expectedFiles) {
+ if (fullPaths.has(basename(file))) throw new Error(`full E2E: ambiguous or duplicate basename ${basename(file)}`);
+ fullPaths.set(basename(file), file);
+ }
+ }
+ const lines = logLines(raw).filter(line => isJob(line.job, lane, opts.e2eProfile));
if (lines.some(l => /^##\[error\]/.test(l.text))) throw new Error(`${lane}: failed job log`);
const byJob = new Map<string, LogLine[]>();
for (const line of lines) {
@@ -113,6 +127,13 @@ export function mineWeights(raw: string, lane: Lane, opts: { expectedJobs?: read
const found = new Map<string, number>();
let expected: number | undefined, current: string | undefined;
let failures: number | undefined;
+ let completed: { duration: number; failures: number | undefined } | undefined;
+ const finishFile = () => {
+ if (!current || !completed || completed.failures !== 0 || found.has(current)) throw new Error(`${job}: missing, failed or duplicate file ${current}`);
+ found.set(current, completed.duration);
+ current = undefined;
+ completed = undefined;
+ };
for (const { text } of records) {
if (lane === "serial") {
const pass = /^\[serial-tests\] PASS ([\d.]+)s (test\/\S+\.serial\.test\.ts)(?:\s|$)/.exec(text);
@@ -122,31 +143,43 @@ export function mineWeights(raw: string, lane: Lane, opts: { expectedJobs?: read
} else {
const start = /^=== ([^/]+\.test\.ts) ===$/.exec(text);
if (start) {
- if (current) throw new Error(`${job}: file missing Bun summary: ${current}`);
- current = `test/e2e/${start[1]}`;
+ if (current) finishFile();
+ if (expected !== undefined) throw new Error(`${job}: file after E2E completion`);
+ current = full ? fullPaths.get(start[1]!) : `test/e2e/${start[1]}`;
+ if (!current) throw new Error(`${job}: file outside the full source corpus: ${start[1]}`);
failures = undefined;
}
const fail = /^\s*(\d+) fail\s*$/.exec(text);
if (fail) failures = Number(fail[1]);
const summary = /^Ran \d+ tests? across 1 file\. \[([\d.]+)(ms|s)\]/.exec(text);
if (current && summary) {
- if (failures !== 0 || found.has(current)) throw new Error(`${job}: failed or duplicate file ${current}`);
- found.set(current, duration(summary[1]!, summary[2] === "s" ? 1000 : 1, job));
- current = undefined;
+ completed = { duration: duration(summary[1]!, summary[2] === "s" ? 1000 : 1, job), failures };
+ failures = undefined;
+ }
+ const end = /^Files: (\d+) total, (\d+) passed, (\d+) failed$/.exec(text);
+ if (end) {
+ if (current) finishFile();
+ if (Number(end[3]) !== 0 || end[1] !== end[2]) throw new Error(`${job}: failed or inconsistent E2E totals`);
+ expected = Number(end[1]);
}
- const end = /^Files: (\d+) total, \d+ passed, (\d+) failed$/.exec(text);
- if (end && Number(end[2]) === 0) expected = Number(end[1]);
if (/^ERROR: HOME isolation breach/.test(text)) throw new Error(`${job}: isolation failure`);
}
}
// Only the runner's explicit no-work sentinel permits a job without a
// summary. Setup-only/truncated jobs must not disappear from the evidence.
- if (lane === 'e2e' && !found.size && expected === undefined && !current &&
+ if (!full && lane === 'e2e' && !found.size && expected === undefined && !current &&
records.some(line => line.text === 'selected E2E: explicit empty selection; no tests launched')) continue;
if (current || expected === undefined || expected !== found.size) throw new Error(`${job}: incomplete ${lane} execution`);
- for (const [file, duration] of found) weights.set(file, Math.max(weights.get(file) ?? 0, duration));
+ for (const [file, duration] of found) {
+ if (full && weights.has(file)) throw new Error(`full E2E: duplicate execution across jobs: ${file}`);
+ weights.set(file, Math.max(weights.get(file) ?? 0, duration));
+ }
}
if (!weights.size) throw new Error(`${lane}: no complete timing data`);
+ if (full) {
+ const missing = opts.expectedFiles!.filter(file => !weights.has(file));
+ if (missing.length) throw new Error(`full E2E: missing source files: ${missing.join(', ')}`);
+ }
return weights;
}
export function serializeWeights(weights: Map<string, number>): string {
@@ -160,45 +193,87 @@ function gh(args: string[]): string {
if (r.status !== 0) throw new Error(`gh ${args.join(" ")} failed: ${r.stderr}`);
return r.stdout;
}
+function git(args: string[]): string {
+ const r = spawnSync("git", args, { cwd: ROOT, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${r.stderr}`);
+ return r.stdout.trimEnd();
+}
+export function sourceE2ECorpus(commit: string): string[] {
+ if (commit !== git(["rev-parse", "HEAD"])) throw new Error("full E2E source SHA differs from checkout HEAD");
+ const tracked = git(["ls-tree", "-r", "--name-only", commit]).split("\n").filter(file => file.endsWith(".test.ts"));
+ const root = mkdtempSync(join(tmpdir(), "gbrain-full-e2e-source-"));
+ try {
+ mkdirSync(join(root, "scripts"));
+ writeFileSync(join(root, "scripts/run-e2e.sh"), git(["show", `${commit}:scripts/run-e2e.sh`]));
+ for (const file of tracked) {
+ mkdirSync(dirname(join(root, file)), { recursive: true });
+ writeFileSync(join(root, file), "");
+ }
+ const r = spawnSync("bash", ["scripts/run-e2e.sh", "--dry-run-list"], {
+ cwd: root, encoding: "utf8", env: { ...process.env, HOME: root, GBRAIN_HOME: root, SHARD: "", COVERAGE_DIR: "" },
+ });
+ if (r.status !== 0) throw new Error(`source E2E discovery failed: ${r.stderr}`);
+ const files = r.stdout.trim().split("\n").filter(Boolean);
+ if (!files.length || new Set(files).size !== files.length || files.some(file => !tracked.includes(file))) throw new Error("source E2E discovery contains missing or duplicate paths");
+ return files;
+ } finally { rmSync(root, { recursive: true, force: true }); }
+}
async function main(): Promise<void> {
let lane: Lane = "unit", run: string | undefined, input: string | undefined, out: string | undefined;
+ let e2eProfile: E2EProfile = "selected";
const argv = process.argv.slice(2);
for (let i = 0; i < argv.length; i++) {
const arg = argv[i]!;
if (arg === "--help" || arg === "-h") {
- console.log("usage: bun run weights:mine [--lane unit|serial|e2e] [--run ID | --from-file PATH | <stdin>] [--out PATH]");
+ console.log("usage: bun run weights:mine [--lane unit|serial|e2e] [--e2e-profile selected|full] [--run ID | --from-file PATH | <stdin>] [--out PATH]\nfull E2E requires --lane e2e --run and a matching source checkout");
return;
}
- if (!["--lane", "--run", "--run-id", "--from-file", "--out"].includes(arg) || !argv[i + 1] || argv[i + 1]!.startsWith("--")) throw new Error(`unknown/incomplete option: ${arg}`);
+ if (!["--lane", "--e2e-profile", "--run", "--run-id", "--from-file", "--out"].includes(arg) || !argv[i + 1] || argv[i + 1]!.startsWith("--")) throw new Error(`unknown/incomplete option: ${arg}`);
const value = argv[++i]!;
if (arg === "--lane") {
if (!["unit", "serial", "e2e"].includes(value)) throw new Error(`invalid lane: ${value}`);
lane = value as Lane;
+ } else if (arg === "--e2e-profile") {
+ if (value !== "selected" && value !== "full") throw new Error(`invalid E2E profile: ${value}`);
+ e2eProfile = value;
} else if (arg === "--run" || arg === "--run-id") run = value;
else if (arg === "--from-file") input = value;
else out = resolve(value);
}
if (run && input) throw new Error("choose --run or --from-file, not both");
+ const full = e2eProfile === "full";
+ if (full && (lane !== "e2e" || !run)) throw new Error("full E2E requires --lane e2e --run for verified source provenance");
out ??= resolve(ROOT, `scripts/${OUTPUTS[lane]}.json`);
let commit: string | null = null;
let expectedJobs: string[] | undefined;
+ let expectedFiles: string[] | undefined;
+ let attempt: number | undefined;
+ let fullJobs: Array<{ name: string; databaseId: number }> = [];
if (run) {
- const info = JSON.parse(gh(["run", "view", run, "--json", "conclusion,headSha,jobs"]));
+ const info = JSON.parse(gh(["run", "view", run, "--json", full ? "attempt,conclusion,headSha,jobs" : "conclusion,headSha,jobs"]));
if (info.conclusion !== "success") throw new Error(`run ${run} is not successful`);
- const jobs = info.jobs.filter((j: { name: string }) => isJob(j.name, lane));
+ const jobs = info.jobs.filter((j: { name: string }) => isJob(j.name, lane, e2eProfile));
if (!jobs.length || jobs.some((j: { conclusion: string }) => j.conclusion !== "success")) throw new Error(`run ${run} has no complete ${lane} lane`);
expectedJobs = jobs.map((j: { name: string }) => j.name);
commit = info.headSha;
+ if (full) {
+ if (!Number.isInteger(info.attempt) || info.attempt < 1 || jobs.some((j: { databaseId: number }) => !Number.isInteger(j.databaseId) || j.databaseId < 1)) throw new Error("full E2E: missing attempt or job identity");
+ attempt = info.attempt;
+ fullJobs = jobs.map(({ name, databaseId }: { name: string; databaseId: number }) => ({ name, databaseId }));
+ expectedFiles = sourceE2ECorpus(info.headSha);
+ }
}
- const raw = run ? gh(["run", "view", run, "--log"]) : input ? readFileSync(input, "utf8") : await new Response(Bun.stdin.stream()).text();
- const measured = mineWeights(raw, lane, { expectedJobs });
+ const raw = full ? fullJobs.map(job => gh(["run", "view", run!, "--attempt", String(attempt), "--job", String(job.databaseId), "--log"])).join("\n") : run ? gh(["run", "view", run, "--log"]) : input ? readFileSync(input, "utf8") : await new Response(Bun.stdin.stream()).text();
+ const measured = mineWeights(raw, lane, { expectedJobs, e2eProfile, expectedFiles });
// Downloaded artifacts/stdin may cover only one shard. Only an authoritative
- // complete GitHub unit/serial run replaces the full map; selected E2E always
+ // complete GitHub unit/serial/full-E2E run replaces the full map; selected E2E always
// merges because its executed corpus depends on the diff.
- const mergeExisting = !run || lane === "e2e";
+ const mergeExisting = !full && (!run || lane === "e2e");
const weights = mergeExisting && existsSync(out) ? loadWeights(out) : new Map<string, number>();
for (const [file, duration] of measured) weights.set(file, duration);
- const metadata = { lane, unit: lane === "serial" ? "seconds" : "milliseconds", run: run ?? null, commit, source: run ? "github" : input ? "file" : "stdin", measuredFiles: measured.size, totalFiles: weights.size, mergeExisting };
+ const metadata = { lane, unit: lane === "serial" ? "seconds" : "milliseconds", run: run ?? null, commit, source: run ? "github" : input ? "file" : "stdin", measuredFiles: measured.size, totalFiles: weights.size, mergeExisting,
+ ...(full ? { e2eProfile, attempt, jobs: fullJobs, logSha256: createHash("sha256").update(raw).digest("hex"), corpusSha256: createHash("sha256").update([...expectedFiles!].sort().join("\n") + "\n").digest("hex") } : {}),
+ };
const temp = `${out}.${process.pid}.tmp`;
try {
writeFileSync(temp, serializeWeights(weights));
diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh
index c0a6b300c4..8df8509a85 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -205,6 +205,19 @@ if [ "${#files[@]}" -eq 0 ]; then
exit 0
fi
+if ! command -v python3 >/dev/null 2>&1; then
+ echo "ERROR: python3 is required to validate native E2E JUnit reports." >&2
+ exit 1
+fi
+
+if [ -n "${COVERAGE_DIR:-}" ]; then
+ mkdir -p "$(dirname "$COVERAGE_DIR")"
+ if ! mkdir "$COVERAGE_DIR"; then
+ echo "ERROR: COVERAGE_DIR must be a new, unused directory for each E2E invocation." >&2
+ exit 1
+ fi
+fi
+
# PGLite snapshot fast path — ~90 e2e files boot in-memory PGLite; a cold boot
# replays every migration (~3.5x per booting file). Every other runner already
# activates this; the env scrub above deliberately keep-lists the var. Placed
@@ -228,6 +241,60 @@ total_pass=0
total_fail=0
file_idx=0
+completed_e2e_passes() {
+ python3 - "${1#./}" "$E2E_TMP_HOME/current.junit.xml" "$E2E_TMP_HOME/current.log" <<'PY'
+import re
+import sys
+import xml.etree.ElementTree as ET
+
+expected, report, log = sys.argv[1:]
+try:
+ root = ET.parse(report).getroot()
+ suites = root.findall('testsuite')
+ if root.tag != 'testsuites' or len(suites) != 1 or suites[0].get('file') != expected:
+ raise ValueError('wrong selected-file suite')
+ for node in [root, *root.iter('testsuite')]:
+ cases = list(node.iter('testcase'))
+ skipped = sum(case.find('skipped') is not None for case in cases)
+ if any(case.find('failure') is not None or case.find('error') is not None for case in cases):
+ raise ValueError('failed testcase')
+ for key, count in [('tests', len(cases)), ('failures', 0), ('skipped', skipped)]:
+ if node.get(key) != str(count):
+ raise ValueError(f'inconsistent {key} count')
+ if node.get('errors', '0') != '0':
+ raise ValueError('reported errors')
+ tests = int(root.get('tests'))
+ skipped = int(root.get('skipped'))
+ header = False
+ counts = {}
+ final = None
+ with open(log) as stream:
+ for raw in stream:
+ line = re.sub(r'\x1b\[[0-9;]*m', '', raw.rstrip('\n'))
+ header = header or line in (expected + ':', '::group::' + expected + ':')
+ count = re.fullmatch(r'\s*(\d+) (pass|fail|skip|todo)\s*', line)
+ if count:
+ value, kind = count.groups()
+ if kind == 'pass':
+ counts = {'skip': 0, 'todo': 0}
+ counts[kind] = int(value)
+ summary = re.match(r'^Ran (\d+) tests? across (\d+) files?\. \[[0-9.]+(?:ms|s)\]', line)
+ if summary:
+ final = (int(summary[1]), int(summary[2]), counts.copy())
+ if not header or final is None:
+ raise ValueError('missing final console report')
+ final_tests, final_files, counts = final
+ if final_tests != tests or final_files != 1 or counts.get('pass') != tests - skipped or counts.get('fail') != 0:
+ raise ValueError('missing or inconsistent final console report')
+ if counts.get('skip', 0) + counts.get('todo', 0) != skipped:
+ raise ValueError('inconsistent skipped/todo count')
+ print(tests - skipped)
+except (OSError, ET.ParseError, ValueError, TypeError) as error:
+ print(f'E2E report validation: {error}', file=sys.stderr)
+ sys.exit(1)
+PY
+}
+
for f in "${files[@]}"; do
name=$(basename "$f")
file_idx=$((file_idx + 1))
@@ -290,16 +357,21 @@ for f in "${files[@]}"; do
FILE_HOME="$E2E_TMP_HOME/file-$file_idx"
mkdir -p "$FILE_HOME/.gbrain"
rc=0
- HOME="$FILE_HOME" GBRAIN_HOME="$FILE_HOME" $TIMEOUT_CMD bun test --timeout=60000 ${COVERAGE_ARGS[@]+"${COVERAGE_ARGS[@]}"} "$f" > "$E2E_TMP_HOME/current.log" 2>&1 &
+ rm -f "$E2E_TMP_HOME/current.junit.xml"
+ HOME="$FILE_HOME" GBRAIN_HOME="$FILE_HOME" $TIMEOUT_CMD bun test --timeout=60000 --reporter=junit --reporter-outfile="$E2E_TMP_HOME/current.junit.xml" ${COVERAGE_ARGS[@]+"${COVERAGE_ARGS[@]}"} "$f" > "$E2E_TMP_HOME/current.log" 2>&1 &
ACTIVE_E2E_PID=$!
wait "$ACTIVE_E2E_PID" || rc=$?
ACTIVE_E2E_PID=""
output=$(cat "$E2E_TMP_HOME/current.log")
rm -rf "$FILE_HOME"
+ if [ "$rc" -eq 0 ] && ! p=$(completed_e2e_passes "$f"); then
+ echo "FAILED: $name did not produce a complete native Bun report for the selected file"
+ rc=1
+ fi
if [ "$rc" -eq 0 ]; then
if [ "$f" = "test/e2e/pgbouncer-teardown.test.ts" ] && \
[ "${GBRAIN_CI_REQUIRE_PGBOUNCER:-0}" = "1" ] && \
- ! grep -qE '^[[:space:]]*[1-9][0-9]* pass$' <<< "$output"; then
+ [ "$p" -eq 0 ]; then
fail_files=$((fail_files + 1))
fail_list+=("$name")
echo "$output"
@@ -307,8 +379,6 @@ for f in "${files[@]}"; do
continue
fi
pass_files=$((pass_files + 1))
- # Extract pass/fail counts from bun's summary (e.g., "123 pass")
- p=$(echo "$output" | grep -oE '[0-9]+ pass' | tail -1 | grep -oE '[0-9]+' || echo 0)
total_pass=$((total_pass + p))
echo "$output" | tail -8
else
@@ -378,6 +448,10 @@ fi
# complete:true means the lcov data represents the whole E2E lane.
if [ -n "${COVERAGE_DIR:-}" ]; then
LCOV_COUNT=$(find "$COVERAGE_DIR" -name 'lcov.info' 2>/dev/null | grep -c '^' || true)
- printf '{"lane":"e2e","sha":"%s","lcovCount":%s,"complete":true}\n' \
- "$(git rev-parse HEAD)" "${LCOV_COUNT:-0}" > "$COVERAGE_DIR/lane-manifest.json"
+ LANE="e2e"
+ [ -z "$RUNNER_SHARD" ] || LANE="e2e-$shard_n"
+ RUN_SHA=$(git rev-parse HEAD)
+ printf '%s\n' "${files[@]}" > "$COVERAGE_DIR/executed-files.txt"
+ printf '{"lane":"%s","sha":"%s","lcovCount":%s,"complete":true}\n' \
+ "$LANE" "$RUN_SHA" "${LCOV_COUNT:-0}" > "$COVERAGE_DIR/lane-manifest.json"
fi
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index c92c75b06e..df8e027c7c 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -262,10 +262,13 @@ test/scripts/ci-local-rendering.test.ts required PgBouncer execution through run
test/scripts/ci-runner-routing.test.ts CI runner routing 5 readFileSync
test/scripts/classify-tests.test.ts classify-tests detectors 18 bun-file,doctor-source-helper,exec-scan,readFileSync
test/scripts/coverage-diff-gate.test.ts exemptions 3 readFileSync
+test/scripts/e2e-runner.test.ts second 5 readFileSync
+test/scripts/e2e-runner.test.ts sequential E2E runner (GITHUB_ACTIONS=${githubActions}) 7 readFileSync
test/scripts/e2e-wiring.test.ts e2e file claim ratchet 5 readFileSync
test/scripts/e2e-wiring.test.ts selected-e2e job wiring 6 readFileSync
test/scripts/heavy-door-workflow.test.ts heavy door supply chain and coverage gates 4 readFileSync
test/scripts/native-lock-prebuilds.test.ts native lock distribution integrity 2 readFileSync
+test/scripts/nightly-e2e.test.ts nightly E2E scheduling 4 readFileSync
test/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coverage 1 readFileSync
test/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSync
test/scripts/test-shard.slow.test.ts test-shard.sh — exclusion contract 6 readFileSync
diff --git a/scripts/verify-nightly-e2e.ts b/scripts/verify-nightly-e2e.ts
new file mode 100644
index 0000000000..d4f3d7f9f3
--- /dev/null
+++ b/scripts/verify-nightly-e2e.ts
@@ -0,0 +1,46 @@
+import { Glob } from 'bun';
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { loadWeights, partition } from './sharding.ts';
+
+export function verifyNightlyE2E(artifacts: string, expected: string[][], sha: string): void {
+ if (!sha || !expected.length || expected.some(files => !files.length)) throw new Error('missing expected E2E corpus or commit');
+ const corpus = expected.flat();
+ if (new Set(corpus).size !== corpus.length) throw new Error('expected E2E partitions overlap');
+ const manifests = [...new Glob('*/lane-manifest.json').scanSync({ cwd: artifacts })]
+ .map(path => ({ path, data: JSON.parse(readFileSync(join(artifacts, path), 'utf8')) }))
+ .filter(({ data }) => typeof data.lane === 'string' && /^e2e(?:-|$)/.test(data.lane));
+ const lanes = expected.map((_, index) => `e2e-${index + 1}`);
+ if (manifests.length !== lanes.length || manifests.some(({ data }) => !lanes.includes(data.lane))) {
+ throw new Error(`expected exactly ${lanes.join(',')} execution manifests`);
+ }
+ for (const [index, lane] of lanes.entries()) {
+ const matches = manifests.filter(({ data }) => data.lane === lane);
+ if (matches.length !== 1) throw new Error(`${lane}: missing or duplicate execution manifest`);
+ const { data, path } = matches[0];
+ if (data.sha !== sha || data.complete !== true) throw new Error(`${lane}: incomplete or wrong-commit execution`);
+ const files = readFileSync(join(artifacts, dirname(path), 'executed-files.txt'), 'utf8').trimEnd().split('\n');
+ if (JSON.stringify(files.sort()) !== JSON.stringify([...expected[index]].sort())) {
+ throw new Error(`${lane}: executed files differ from the full-corpus partition`);
+ }
+ }
+}
+
+if (import.meta.main) {
+ try {
+ const [artifacts, count, sha] = process.argv.slice(2);
+ const shards = Number(count);
+ if (!artifacts || !sha || !Number.isInteger(shards) || shards < 1) throw new Error('usage: bun scripts/verify-nightly-e2e.ts <artifacts> <shards> <sha>');
+ const discovered = spawnSync('bash', ['scripts/run-e2e.sh', '--dry-run-list'], {
+ encoding: 'utf8', env: { ...process.env, SHARD: '', COVERAGE_DIR: '' },
+ });
+ if (discovered.status !== 0) throw new Error(`full E2E discovery failed: ${discovered.stderr}`);
+ const files = discovered.stdout.trim().split('\n').filter(Boolean);
+ verifyNightlyE2E(artifacts, partition(files, loadWeights('scripts/e2e-weights.json'), shards), sha);
+ console.log(`nightly E2E: all ${files.length} files accounted for across ${shards} isolated workers`);
+ } catch (error) {
+ console.error(`nightly E2E: ${error instanceof Error ? error.message : error}`);
+ process.exitCode = 1;
+ }
+}
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 0563f261da..8cfae8d69d 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.58.0.0 -->
+<!-- gbrain-template-stamp: 0.58.1.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/admin-embed-spawn.serial.test.ts b/test/admin-embed-spawn.serial.test.ts
index 52ffbb1493..106f90f4c4 100644
--- a/test/admin-embed-spawn.serial.test.ts
+++ b/test/admin-embed-spawn.serial.test.ts
@@ -23,7 +23,7 @@
* No DATABASE_URL needed; PGLite is the engine. Serial because it binds
* a TCP port and reads/writes a tmpdir.
*/
-import { describe, test, expect } from 'bun:test';
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
@@ -113,20 +113,26 @@ async function spawnServer(): Promise<ServeProc> {
}
const cleanup = async () => {
- try { proc.kill('SIGTERM'); } catch { /* already exited */ }
- // Give it 2s to exit cleanly, then SIGKILL.
- await Promise.race([
- proc.exited,
- new Promise(r => setTimeout(r, 2000)),
- ]);
- try { proc.kill('SIGKILL'); } catch { /* already gone */ }
- try { rmSync(home, { recursive: true, force: true }); } catch { /* best effort */ }
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ try { proc.kill('SIGTERM'); } catch { /* already exited */ }
+ await Promise.race([
+ proc.exited,
+ new Promise<void>(resolve => { timer = setTimeout(resolve, 2000); }),
+ ]);
+ if (proc.exitCode === null) {
+ try { proc.kill('SIGKILL'); } catch { /* already exited */ }
+ await proc.exited;
+ }
+ } finally {
+ if (timer) clearTimeout(timer);
+ rmSync(home, { recursive: true, force: true });
+ }
};
if (!ready) {
- // Capture some diagnostics for the failure message before tearing down.
- const stderrText = await new Response(proc.stderr).text().catch(() => '');
await cleanup();
+ const stderrText = await new Response(proc.stderr).text().catch(() => '');
throw new Error(
`serve --http never became ready on port ${port} after 30s. stderr: ${stderrText.slice(0, 2000)}`,
);
@@ -136,98 +142,83 @@ async function spawnServer(): Promise<ServeProc> {
}
describe('admin embed E2E — /admin served from embedded manifest (v0.36.1.x #1090)', () => {
+ let server: ServeProc;
+
+ beforeAll(async () => {
+ server = await spawnServer();
+ }, 90_000);
+
+ afterAll(async () => {
+ if (server) await server.cleanup();
+ });
+
test('GET /admin/ returns 200 with the React SPA shell HTML', async () => {
- const s = await spawnServer();
- try {
- const res = await fetch(`http://127.0.0.1:${s.port}/admin/`, {
- signal: AbortSignal.timeout(5000),
- });
- expect(res.status).toBe(200);
- const html = await res.text();
- // The actual admin/dist/index.html declares <title>GBrain Admin</title>
- // and mounts the SPA on <div id="root">. Both must be present, otherwise
- // we're not serving the embedded asset.
- expect(html).toContain('GBrain Admin');
- expect(html).toContain('<div id="root">');
- // Content-Type is text/html, not application/octet-stream (which would
- // mean the mime lookup in ADMIN_ASSETS regressed).
- expect(res.headers.get('content-type') ?? '').toMatch(/text\/html/);
- } finally {
- await s.cleanup();
- }
+ const res = await fetch(`http://127.0.0.1:${server.port}/admin/`, {
+ signal: AbortSignal.timeout(5000),
+ });
+ expect(res.status).toBe(200);
+ const html = await res.text();
+ // The actual admin/dist/index.html declares <title>GBrain Admin</title>
+ // and mounts the SPA on <div id="root">. Both must be present, otherwise
+ // we're not serving the embedded asset.
+ expect(html).toContain('GBrain Admin');
+ expect(html).toContain('<div id="root">');
+ // Content-Type is text/html, not application/octet-stream (which would
+ // mean the mime lookup in ADMIN_ASSETS regressed).
+ expect(res.headers.get('content-type') ?? '').toMatch(/text\/html/);
}, 90_000);
test('GET /admin (no trailing slash) redirects to /admin/', async () => {
- const s = await spawnServer();
- try {
- const res = await fetch(`http://127.0.0.1:${s.port}/admin`, {
- signal: AbortSignal.timeout(5000),
- redirect: 'manual',
- });
- // Pre-fix this 404'd: the embedded-manifest branch only registered
- // '/admin/{*path}', which requires the literal '/' before the
- // wildcard segment and never matches a bare '/admin' request.
- expect([301, 302, 303, 307, 308]).toContain(res.status);
- expect(res.headers.get('location')).toBe('/admin/');
-
- // Following the redirect lands on the same SPA shell as GET /admin/.
- const followed = await fetch(`http://127.0.0.1:${s.port}/admin`, {
- signal: AbortSignal.timeout(5000),
- });
- expect(followed.status).toBe(200);
- const html = await followed.text();
- expect(html).toContain('GBrain Admin');
- expect(html).toContain('<div id="root">');
- } finally {
- await s.cleanup();
- }
+ const res = await fetch(`http://127.0.0.1:${server.port}/admin`, {
+ signal: AbortSignal.timeout(5000),
+ redirect: 'manual',
+ });
+ // Pre-fix this 404'd: the embedded-manifest branch only registered
+ // '/admin/{*path}', which requires the literal '/' before the
+ // wildcard segment and never matches a bare '/admin' request.
+ expect([301, 302, 303, 307, 308]).toContain(res.status);
+ expect(res.headers.get('location')).toBe('/admin/');
+
+ // Following the redirect lands on the same SPA shell as GET /admin/.
+ const followed = await fetch(`http://127.0.0.1:${server.port}/admin`, {
+ signal: AbortSignal.timeout(5000),
+ });
+ expect(followed.status).toBe(200);
+ const html = await followed.text();
+ expect(html).toContain('GBrain Admin');
+ expect(html).toContain('<div id="root">');
}, 90_000);
test('GET /admin/index.html (explicit path) also returns the SPA HTML', async () => {
- const s = await spawnServer();
- try {
- const res = await fetch(`http://127.0.0.1:${s.port}/admin/index.html`, {
- signal: AbortSignal.timeout(5000),
- });
- expect(res.status).toBe(200);
- const html = await res.text();
- expect(html).toContain('GBrain Admin');
- } finally {
- await s.cleanup();
- }
+ const res = await fetch(`http://127.0.0.1:${server.port}/admin/index.html`, {
+ signal: AbortSignal.timeout(5000),
+ });
+ expect(res.status).toBe(200);
+ const html = await res.text();
+ expect(html).toContain('GBrain Admin');
}, 90_000);
test('GET /admin/agents (SPA-routed deep link) falls back to index.html', async () => {
- const s = await spawnServer();
- try {
- const res = await fetch(`http://127.0.0.1:${s.port}/admin/agents`, {
- signal: AbortSignal.timeout(5000),
- });
- expect(res.status).toBe(200);
- const html = await res.text();
- // SPA fallback: any unmatched /admin/* path serves index.html so
- // client-side routing takes over.
- expect(html).toContain('GBrain Admin');
- expect(html).toContain('<div id="root">');
- } finally {
- await s.cleanup();
- }
+ const res = await fetch(`http://127.0.0.1:${server.port}/admin/agents`, {
+ signal: AbortSignal.timeout(5000),
+ });
+ expect(res.status).toBe(200);
+ const html = await res.text();
+ // SPA fallback: any unmatched /admin/* path serves index.html so
+ // client-side routing takes over.
+ expect(html).toContain('GBrain Admin');
+ expect(html).toContain('<div id="root">');
}, 90_000);
test('GET /admin/api/stats (API route) is NOT swallowed by the SPA fallback — returns auth challenge', async () => {
- const s = await spawnServer();
- try {
- const res = await fetch(`http://127.0.0.1:${s.port}/admin/api/stats`, {
- signal: AbortSignal.timeout(5000),
- });
- // No session cookie → 401/403 from requireAdmin, NOT 200 + HTML.
- // The regression we guard against: SPA fallback grabbing /admin/api/*
- // would silently return HTML to a JSON client and break the dashboard.
- expect(res.status).not.toBe(200);
- const body = await res.text().catch(() => '');
- expect(body).not.toContain('<div id="root">');
- } finally {
- await s.cleanup();
- }
+ const res = await fetch(`http://127.0.0.1:${server.port}/admin/api/stats`, {
+ signal: AbortSignal.timeout(5000),
+ });
+ // No session cookie → 401/403 from requireAdmin, NOT 200 + HTML.
+ // The regression we guard against: SPA fallback grabbing /admin/api/*
+ // would silently return HTML to a JSON client and break the dashboard.
+ expect(res.status).not.toBe(200);
+ const body = await res.text().catch(() => '');
+ expect(body).not.toContain('<div id="root">');
}, 90_000);
});
diff --git a/test/code-projection-edge-recovery.test.ts b/test/code-projection-edge-recovery.test.ts
index 621b4bb5df..f6aaea943f 100644
--- a/test/code-projection-edge-recovery.test.ts
+++ b/test/code-projection-edge-recovery.test.ts
@@ -7,18 +7,22 @@ import { resolveSymbolEdgesIncremental } from '../src/core/chunkers/symbol-resol
import { resolveCodeReadiness } from '../src/core/code-graph-readiness.ts';
import { operationsByName, type OperationContext } from '../src/core/operations.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+const backends = testBackends();
describe('code projection recovery preserves graph correctness', () => {
const engines: BrainEngine[] = [];
let closePostgres: (() => Promise<void>) | undefined;
beforeAll(async () => {
- const lite = new PGLiteEngine();
- await lite.connect({});
- await lite.initSchema();
- engines.push(lite);
- if (process.env.DATABASE_URL) {
- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ if (backends.includes('pglite')) {
+ const lite = new PGLiteEngine();
+ await lite.connect({});
+ await lite.initSchema();
+ engines.push(lite);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
engines.push(pg.engine);
closePostgres = pg.close;
}
diff --git a/test/e2e/fixture-reset-postgres.test.ts b/test/e2e/fixture-reset-postgres.test.ts
new file mode 100644
index 0000000000..8faab662ef
--- /dev/null
+++ b/test/e2e/fixture-reset-postgres.test.ts
@@ -0,0 +1,112 @@
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { LATEST_VERSION } from '../../src/core/migrate.ts';
+import { runSchemaTransition } from '../../src/core/embedding-migration.ts';
+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';
+import { getEngine, hasDatabase, setupDB, setupLegacyEmbeddingDB, teardownDB } from './helpers.ts';
+
+(hasDatabase() ? describe : describe.skip)('PostgreSQL fixture reset lifecycle', () => {
+ beforeAll(async () => { await setupLegacyEmbeddingDB(); }, 120_000);
+ afterAll(teardownDB);
+
+ test('ordinary reset clears data, operator config and source sync identity without replaying a current ledger', async () => {
+ const original = getEngine();
+ await original.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('fixture-other','fixture-other','/fixture-other')");
+ await original.executeRaw("UPDATE sources SET local_path='/fixture-default',last_commit='fixture-commit',last_sync_at=now() WHERE id='default'");
+ await original.putPage('fixture-page', { type: 'note', title: 'Fixture', compiled_truth: 'Fixture content' });
+ await original.addTag('fixture-page', 'fixture-tag');
+ await original.setConfig('fixture.operator-setting', 'must-not-survive');
+ const migrations = spyOn(PostgresEngine.prototype, 'runMigration');
+ try {
+ const reset = await setupDB();
+ expect(migrations).not.toHaveBeenCalled();
+ expect(await reset.getConfig('version')).toBe(String(LATEST_VERSION));
+ expect(await reset.getConfig('fixture.operator-setting')).toBeNull();
+ expect(await reset.getPage('fixture-page')).toBeNull();
+ expect(await reset.executeRaw('SELECT tag FROM tags')).toEqual([]);
+ expect(await reset.executeRaw("SELECT id FROM sources WHERE id<>'default'")).toEqual([]);
+ expect(await reset.executeRaw("SELECT local_path,last_commit,last_sync_at FROM sources WHERE id='default'"))
+ .toEqual([{ local_path: null, last_commit: null, last_sync_at: null }]);
+ } finally { migrations.mockRestore(); }
+ });
+
+ test('explicit replay runs the cold migration chain and warm reset preserves its seeded defaults', async () => {
+ const migrations = spyOn(PostgresEngine.prototype, 'runMigration');
+ try {
+ const reset = await setupDB({ replayMigrations: true });
+ expect(migrations.mock.calls.length).toBeGreaterThan(0);
+ expect(await reset.getConfig('version')).toBe(String(LATEST_VERSION));
+ const defaults = async (engine: PostgresEngine) => ({
+ config: await engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config ORDER BY key'),
+ source: await engine.executeRaw("SELECT id,name,config,incarnation,chunker_version FROM sources WHERE id='default'"),
+ persistence: await engine.executeRaw('SELECT singleton,brain_id,enabled FROM persistence_brain'),
+ skills: await engine.executeRaw('SELECT singleton,serving_epoch,length(token_secret) AS secret_length FROM shared_skill_state'),
+ clock: await engine.executeRaw('SELECT id,value FROM page_generation_clock'),
+ });
+ const seeded = await defaults(reset);
+ expect(Object.fromEntries(seeded.config.map(row => [row.key, row.value]))).toMatchObject({
+ version: String(LATEST_VERSION), schema_version: '1', chunk_strategy: 'semantic',
+ });
+ expect(seeded.source).toHaveLength(1);
+ expect(seeded.persistence).toHaveLength(1);
+ expect(seeded.skills).toHaveLength(1);
+ expect(seeded.clock).toHaveLength(1);
+ migrations.mockClear();
+ expect(await defaults(await setupDB())).toEqual(seeded);
+ expect(migrations).not.toHaveBeenCalled();
+ } finally { migrations.mockRestore(); }
+ });
+
+ test('a missing ledger cannot be mistaken for an already-migrated fixture', async () => {
+ await getEngine().unsetConfig('version');
+ const migrations = spyOn(PostgresEngine.prototype, 'runMigration');
+ try {
+ const reset = await setupDB();
+ expect(migrations.mock.calls.length).toBeGreaterThan(0);
+ expect(await reset.getConfig('version')).toBe(String(LATEST_VERSION));
+ } finally { migrations.mockRestore(); }
+ });
+
+ test('ordinary reset preserves custom vector shape while legacy reset deliberately restores it', async () => {
+ const dimensions = (engine: PostgresEngine) => engine.executeRaw<{ dims: number }>(
+ `SELECT a.atttypmod AS dims FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid
+ JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public'
+ AND c.relname IN ('content_chunks','query_cache','facts','takes') AND a.attname='embedding'
+ AND a.attnum>0 AND NOT a.attisdropped ORDER BY c.relname`);
+ try {
+ await runSchemaTransition(getEngine(), 64);
+ await getEngine().executeRaw('ALTER TABLE takes ALTER COLUMN embedding TYPE vector(64) USING NULL');
+ expect((await dimensions(await setupDB())).map(row => row.dims)).toEqual([64, 64, 64, 64]);
+ expect((await dimensions(await setupLegacyEmbeddingDB())).map(row => row.dims))
+ .toEqual(Array(4).fill(LEGACY_EMBEDDING_CONFIG.embedding_dimensions));
+ } finally { await setupLegacyEmbeddingDB(); }
+ });
+
+ test('legacy reset aligns stored embedding identity with its columns and later ordinary resets', async () => {
+ const state = async (engine: PostgresEngine) => ({
+ model: await engine.getConfig('embedding_model'),
+ dimensions: await engine.getConfig('embedding_dimensions'),
+ columns: (await engine.executeRaw<{ dims: number }>(
+ `SELECT a.atttypmod AS dims FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid
+ JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public'
+ AND c.relname IN ('content_chunks','query_cache','facts','takes') AND a.attname='embedding'
+ AND a.attnum>0 AND NOT a.attisdropped ORDER BY c.relname`)).map(row => row.dims),
+ });
+ try {
+ await runSchemaTransition(getEngine(), 1024);
+ await getEngine().executeRaw('ALTER TABLE takes ALTER COLUMN embedding TYPE vector(1024) USING NULL');
+ await getEngine().setConfig('embedding_model', 'voyage:voyage-4');
+ await getEngine().setConfig('embedding_dimensions', '1024');
+ expect(await state(await setupDB())).toEqual({
+ model: 'voyage:voyage-4', dimensions: '1024', columns: [1024, 1024, 1024, 1024],
+ });
+ const expected = {
+ model: LEGACY_EMBEDDING_CONFIG.embedding_model,
+ dimensions: String(LEGACY_EMBEDDING_CONFIG.embedding_dimensions),
+ columns: Array(4).fill(LEGACY_EMBEDDING_CONFIG.embedding_dimensions),
+ };
+ expect(await state(await setupLegacyEmbeddingDB())).toEqual(expected);
+ expect(await state(await setupDB())).toEqual(expected);
+ } finally { await setupLegacyEmbeddingDB(); }
+ });
+});
diff --git a/test/e2e/helpers.ts b/test/e2e/helpers.ts
index 86a0288176..83d88274ec 100644
--- a/test/e2e/helpers.ts
+++ b/test/e2e/helpers.ts
@@ -58,7 +58,6 @@ const ALL_TABLES = [
// join), but stale rows poison stats/count assertions across runs.
'context_volunteer_events',
'pages', // last because of foreign keys
- 'config',
'minion_attachments',
'minion_inbox',
'minion_jobs',
@@ -79,10 +78,11 @@ export function hasDatabase(): boolean {
export { assertSafeE2eDatabaseUrl };
/**
- * Connect to DB, run schema init, truncate all tables.
+ * Connect to DB and clear fixture data while retaining the migration ledger.
+ * Explicit migration fixtures can opt into replaying the cold migration chain.
* Call in beforeAll() of each test file.
*/
-export async function setupDB(): Promise<PostgresEngine> {
+export async function setupDB(options: { replayMigrations?: boolean } = {}): Promise<PostgresEngine> {
if (!DATABASE_URL) {
throw new Error('DATABASE_URL not set. Copy .env.testing.example to .env.testing and configure it.');
}
@@ -111,6 +111,8 @@ export async function setupDB(): Promise<PostgresEngine> {
}
}
+ await conn.unsafe(options.replayMigrations ? 'TRUNCATE config' : "DELETE FROM config WHERE key <> 'version'");
+
// Re-seed config (initSchema inserts default config rows)
await conn.unsafe(`
INSERT INTO config (key, value) VALUES ('schema_version', '1')
@@ -181,6 +183,10 @@ export async function setupLegacyEmbeddingDB(): Promise<PostgresEngine> {
// trigram-based). This empty test table also receives fixed-width seeds.
await target.executeRaw(`ALTER TABLE takes ALTER COLUMN embedding TYPE ${takes.type_name}(${dims}) USING NULL`);
}
+ await target.transaction(async tx => {
+ await tx.setConfig('embedding_model', LEGACY_EMBEDDING_CONFIG.embedding_model);
+ await tx.setConfig('embedding_dimensions', String(dims));
+ });
return target;
}
diff --git a/test/e2e/managed-connector-fencing.test.ts b/test/e2e/managed-connector-fencing.test.ts
index 06a9bfe4c4..3670351df7 100644
--- a/test/e2e/managed-connector-fencing.test.ts
+++ b/test/e2e/managed-connector-fencing.test.ts
@@ -1 +1,3 @@
-import '../persistence-connector-fencing.test.ts';
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../persistence-connector-fencing.test.ts'));
diff --git a/test/e2e/managed-connector-recovery.test.ts b/test/e2e/managed-connector-recovery.test.ts
index a3b39ae279..fbbaa51297 100644
--- a/test/e2e/managed-connector-recovery.test.ts
+++ b/test/e2e/managed-connector-recovery.test.ts
@@ -1 +1,3 @@
-import '../persistence-connector-recovery.test.ts';
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../persistence-connector-recovery.test.ts'));
diff --git a/test/e2e/managed-connector-retry.test.ts b/test/e2e/managed-connector-retry.test.ts
index 742e227fa7..7a2d0f975a 100644
--- a/test/e2e/managed-connector-retry.test.ts
+++ b/test/e2e/managed-connector-retry.test.ts
@@ -1 +1,3 @@
-import '../persistence-connector-retry.test.ts';
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../persistence-connector-retry.test.ts'));
diff --git a/test/e2e/managed-connector-routing.test.ts b/test/e2e/managed-connector-routing.test.ts
index f5ce5312fe..b1f0ba9cc6 100644
--- a/test/e2e/managed-connector-routing.test.ts
+++ b/test/e2e/managed-connector-routing.test.ts
@@ -1,2 +1,6 @@
-import '../managed-connector-routing.serial.test.ts';
-import '../persistence-connectors.test.ts';
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(
+ () => import('../managed-connector-routing.serial.test.ts'),
+ () => import('../persistence-connectors.test.ts'),
+);
diff --git a/test/e2e/managed-maintenance.test.ts b/test/e2e/managed-maintenance.test.ts
index e10882316c..669dc4b358 100644
--- a/test/e2e/managed-maintenance.test.ts
+++ b/test/e2e/managed-maintenance.test.ts
@@ -1 +1,3 @@
-import '../managed-maintenance.test.ts';
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../managed-maintenance.test.ts'));
diff --git a/test/e2e/managed-sync-failures.test.ts b/test/e2e/managed-sync-failures.test.ts
index dcbd3ada7e..5bae2645ba 100644
--- a/test/e2e/managed-sync-failures.test.ts
+++ b/test/e2e/managed-sync-failures.test.ts
@@ -1 +1,3 @@
-import '../persistence-sync-failures.serial.test.ts';
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../persistence-sync-failures.serial.test.ts'));
diff --git a/test/e2e/managed-synthesis-postprocess.test.ts b/test/e2e/managed-synthesis-postprocess.test.ts
index 1b9b5a2aaa..e94a704665 100644
--- a/test/e2e/managed-synthesis-postprocess.test.ts
+++ b/test/e2e/managed-synthesis-postprocess.test.ts
@@ -1 +1,3 @@
-import '../managed-synthesis-postprocess.test.ts';
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../managed-synthesis-postprocess.test.ts'));
diff --git a/test/e2e/migrate-chain.test.ts b/test/e2e/migrate-chain.test.ts
index f3ae21a7de..c3b9a3cfb2 100644
--- a/test/e2e/migrate-chain.test.ts
+++ b/test/e2e/migrate-chain.test.ts
@@ -35,7 +35,7 @@ const describeE2E = SKIP ? describe.skip : describe;
describeE2E('PR #356 — post-migration schema invariants (v15→v23 end state)', () => {
beforeAll(async () => {
- await setupDB();
+ await setupDB({ replayMigrations: true });
}, 30_000);
afterAll(async () => {
await teardownDB();
@@ -86,17 +86,13 @@ describeE2E('PR #356 — post-migration schema invariants (v15→v23 end state)'
expect(names).toEqual(['error', 'file_id', 'status', 'storage_path_new', 'storage_path_old', 'updated_at']);
});
- // Note: config.version is truncated by setupDB's ALL_TABLES list so we
- // can't assert it reached LATEST here. The schema-invariant tests above
- // (composite unique present, old FK gone, page_id column, ledger table)
- // are the real proof that the v15→v23 chain's DDL ran to completion.
});
describeE2E('PR #356 — doctor --locks detects real idle-in-transaction connections', () => {
let secondary: ReturnType<typeof postgres> | null = null;
beforeAll(async () => {
- await setupDB();
+ await setupDB({ replayMigrations: true });
}, 30_000);
afterAll(async () => {
if (secondary) {
@@ -148,7 +144,7 @@ describeE2E('PR #356 — doctor --locks detects real idle-in-transaction connect
describeE2E('PR #356 — runMigrationsUpTo + setConfigVersion helpers', () => {
beforeAll(async () => {
- await setupDB();
+ await setupDB({ replayMigrations: true });
}, 30_000);
afterAll(async () => {
await teardownDB();
@@ -184,7 +180,7 @@ describeE2E('PR #356 — runMigrationsUpTo + setConfigVersion helpers', () => {
describeE2E('PR #356 — withReservedConnection round-trip', () => {
beforeAll(async () => {
- await setupDB();
+ await setupDB({ replayMigrations: true });
}, 30_000);
afterAll(async () => {
await teardownDB();
diff --git a/test/e2e/migrate-embeddings-postgres.test.ts b/test/e2e/migrate-embeddings-postgres.test.ts
index ee18bc72f4..4d583df206 100644
--- a/test/e2e/migrate-embeddings-postgres.test.ts
+++ b/test/e2e/migrate-embeddings-postgres.test.ts
@@ -84,7 +84,7 @@ d('embedding migration (live Postgres + pgvector)', () => {
savedEnv[k] = process.env[k];
delete process.env[k];
}
- engine = await setupDB();
+ engine = await setupDB({ replayMigrations: true });
originalDims = await columnDims();
resetGateway();
diff --git a/test/e2e/migrate-engine-sources-postgres.test.ts b/test/e2e/migrate-engine-sources-postgres.test.ts
index 4e3e1653e3..cb6b2c5141 100644
--- a/test/e2e/migrate-engine-sources-postgres.test.ts
+++ b/test/e2e/migrate-engine-sources-postgres.test.ts
@@ -9,7 +9,7 @@ describePg('migrate-engine source copy PGLite to Postgres', () => {
let source: PGLiteEngine;
beforeAll(async () => {
- await setupDB();
+ await setupDB({ replayMigrations: true });
source = new PGLiteEngine();
await source.connect({});
await source.initSchema();
diff --git a/test/e2e/migration-drop-invalid-concurrent-index.test.ts b/test/e2e/migration-drop-invalid-concurrent-index.test.ts
index 0fcad66da1..24b74a3fd8 100644
--- a/test/e2e/migration-drop-invalid-concurrent-index.test.ts
+++ b/test/e2e/migration-drop-invalid-concurrent-index.test.ts
@@ -66,7 +66,7 @@ async function plantInvalidIndex(indexName: string, createSQL: string): Promise<
describeE2E('migration invalid-remnant recovery (#1178)', () => {
beforeAll(async () => {
- await setupDB();
+ await setupDB({ replayMigrations: true });
await runMigrationsUpTo(getEngine(), LATEST_VERSION);
}, 30_000);
diff --git a/test/e2e/migration-v35-auto-rls.test.ts b/test/e2e/migration-v35-auto-rls.test.ts
index 2069522822..4874761b6c 100644
--- a/test/e2e/migration-v35-auto-rls.test.ts
+++ b/test/e2e/migration-v35-auto-rls.test.ts
@@ -31,7 +31,7 @@ const v35Sql = (v35?.sqlFor as any)?.postgres ?? '';
describeE2E('migration v35: auto_rls_event_trigger', () => {
beforeAll(async () => {
- await setupDB();
+ await setupDB({ replayMigrations: true });
// setupDB() runs db.initSchema() (SCHEMA_SQL only, no migrations).
// Advance through every migration so v35 is actually installed.
await runMigrationsUpTo(getEngine(), LATEST_VERSION);
diff --git a/test/e2e/migration-v35-event-trigger.test.ts b/test/e2e/migration-v35-event-trigger.test.ts
index d4df9733fe..a52ebecce9 100644
--- a/test/e2e/migration-v35-event-trigger.test.ts
+++ b/test/e2e/migration-v35-event-trigger.test.ts
@@ -36,7 +36,7 @@ const v35Sql =
describeE2E('migration v35 — event trigger converges idempotently (#3603)', () => {
// Fresh DBs apply the full migration chain in setupDB — allow for it.
beforeAll(async () => {
- await setupDB();
+ await setupDB({ replayMigrations: true });
}, 120_000);
afterAll(async () => {
diff --git a/test/e2e/migration-v47-notability.test.ts b/test/e2e/migration-v47-notability.test.ts
index 5ac1ebc872..0a74affd5d 100644
--- a/test/e2e/migration-v47-notability.test.ts
+++ b/test/e2e/migration-v47-notability.test.ts
@@ -115,7 +115,7 @@ async function readNamedCheckExists(): Promise<boolean> {
describeE2E('migration v47: facts.notability ALTER', () => {
beforeAll(async () => {
- await setupDB();
+ await setupDB({ replayMigrations: true });
// setupDB() runs db.initSchema() (SCHEMA_SQL only, no migrations).
// Advance to LATEST_VERSION so v45 lands and the facts table exists.
await runMigrationsUpTo(getEngine(), LATEST_VERSION);
diff --git a/test/e2e/migration-v50-ingest-log-source-id.test.ts b/test/e2e/migration-v50-ingest-log-source-id.test.ts
index 036022621d..a2720a3a48 100644
--- a/test/e2e/migration-v50-ingest-log-source-id.test.ts
+++ b/test/e2e/migration-v50-ingest-log-source-id.test.ts
@@ -84,7 +84,7 @@ async function readIndexExists(): Promise<boolean> {
describeE2E('migration v50: ingest_log.source_id ALTER', () => {
beforeAll(async () => {
- await setupDB();
+ await setupDB({ replayMigrations: true });
await runMigrationsUpTo(getEngine(), LATEST_VERSION);
}, 30_000);
diff --git a/test/e2e/persistence-embedding-effects.test.ts b/test/e2e/persistence-embedding-effects.test.ts
index 4d9b28599d..6b1ed6876d 100644
--- a/test/e2e/persistence-embedding-effects.test.ts
+++ b/test/e2e/persistence-embedding-effects.test.ts
@@ -1,2 +1,6 @@
-import '../persistence-effect-retry.test.ts';
-import '../persistence-embedding-effects.test.ts';
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(
+ () => import('../persistence-effect-retry.test.ts'),
+ () => import('../persistence-embedding-effects.test.ts'),
+);
diff --git a/test/e2e/persistence-recovery.test.ts b/test/e2e/persistence-recovery.test.ts
index 0ec968d22d..d8a0c837da 100644
--- a/test/e2e/persistence-recovery.test.ts
+++ b/test/e2e/persistence-recovery.test.ts
@@ -1,2 +1,6 @@
-import '../persistence-admin-recovery.test.ts';
-import '../persistence-onboarding.test.ts';
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(
+ () => import('../persistence-admin-recovery.test.ts'),
+ () => import('../persistence-onboarding.test.ts'),
+);
diff --git a/test/e2e/persistence-skill-bundles-postgres.test.ts b/test/e2e/persistence-skill-bundles-postgres.test.ts
index 653256ab2e..c16296564f 100644
--- a/test/e2e/persistence-skill-bundles-postgres.test.ts
+++ b/test/e2e/persistence-skill-bundles-postgres.test.ts
@@ -2,13 +2,14 @@ import { expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';
-(process.env.DATABASE_URL ? test : test.skip)('shared skill persistence parity and independent crash recovery on Postgres', async () => {
- assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);
+requirePostgresTestDatabase();
+
+test('shared skill persistence parity and independent crash recovery on Postgres', async () => {
const home = mkdtempSync(join(tmpdir(), 'gbrain-bundle-parity-e2e-'));
const child = Bun.spawn([process.execPath, 'test', 'test/persistence-skill-bundles.serial.test.ts', 'test/persistence-skill-crash.slow.test.ts'], {
- cwd: join(import.meta.dir, '../..'), env: { ...process.env, GBRAIN_HOME: home, GBRAIN_TEST_ALLOW_DATABASE_URL: '1' },
+ cwd: join(import.meta.dir, '../..'), env: { ...process.env, GBRAIN_HOME: home, GBRAIN_TEST_ALLOW_DATABASE_URL: '1', GBRAIN_TEST_BACKEND: 'postgres' },
stdout: 'pipe', stderr: 'pipe',
});
const timer = setTimeout(() => child.kill('SIGKILL'), 360_000);
diff --git a/test/e2e/projection-recovery-parity.test.ts b/test/e2e/projection-recovery-parity.test.ts
index 329e502177..a7396ff0d7 100644
--- a/test/e2e/projection-recovery-parity.test.ts
+++ b/test/e2e/projection-recovery-parity.test.ts
@@ -1,12 +1,9 @@
-import { test } from 'bun:test';
-import { hasDatabase } from './helpers.ts';
+import { registerPostgresTests } from '../helpers/test-backends.ts';
-if (hasDatabase()) {
- await import('../page-projection-origin.test.ts');
- await import('../page-projection-vector-preservation.test.ts');
- await import('../page-projection-code-recovery.test.ts');
- await import('../code-projection-edge-recovery.test.ts');
- await import('../symbol-resolver-projection-race.test.ts');
-} else {
- test.skip('projection recovery parity requires PostgreSQL', () => {});
-}
+await registerPostgresTests(
+ () => import('../page-projection-origin.test.ts'),
+ () => import('../page-projection-vector-preservation.test.ts'),
+ () => import('../page-projection-code-recovery.test.ts'),
+ () => import('../code-projection-edge-recovery.test.ts'),
+ () => import('../symbol-resolver-projection-race.test.ts'),
+);
diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.ts
index b5407d706c..a82ec2cfd4 100644
--- a/test/e2e/serve-http-oauth.test.ts
+++ b/test/e2e/serve-http-oauth.test.ts
@@ -16,7 +16,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { createHash } from 'crypto';
import { auth, extractWWWAuthenticateParams, type OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
-import { hasDatabase } from './helpers.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const skip = !hasDatabase();
@@ -45,6 +45,7 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {
const dcrClientIds: string[] = [];
beforeAll(async () => {
+ await setupDB();
const { execSync, spawn } = await import('child_process');
// Register a test OAuth client via CLI.
@@ -125,6 +126,7 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {
console.error(`[afterAll] revoke-client cleanup failed for ${id}: ${e.message}`);
}
}
+ await teardownDB();
}, 30_000);
// Helper: mint a token with given scopes
diff --git a/test/entity-card-perf.slow.test.ts b/test/entity-card-perf.slow.test.ts
index b277a8d722..9966dc2b21 100644
--- a/test/entity-card-perf.slow.test.ts
+++ b/test/entity-card-perf.slow.test.ts
@@ -154,6 +154,7 @@ beforeAll(async () => {
'world', 'medium', NOW(), 'perf-seed', 1.0, NOW()
FROM generate_series(0, ${TARGET_ENTITIES - 1}) t, generate_series(1, 20) g`,
);
+ await engine.executeRaw('ANALYZE pages, links, page_aliases, facts');
}, 300_000);
afterAll(async () => {
diff --git a/test/helpers/connector-fixture.ts b/test/helpers/connector-fixture.ts
index 2958e64a4c..39d256365a 100644
--- a/test/helpers/connector-fixture.ts
+++ b/test/helpers/connector-fixture.ts
@@ -9,6 +9,7 @@ import { claimWorktree } from '../../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
import { isolatedPersistencePostgres } from './persistence-postgres.ts';
import { syncLockId } from '../../src/core/db-lock.ts';
+import { testBackends } from './test-backends.ts';
export const options = { noEmbed: true, noExtract: true, noSchemaPack: true };
export const json = (body: unknown, status = 200, headers = {}) => new Response(JSON.stringify(body), {
@@ -40,17 +41,20 @@ export async function sourceCheckpoint(engine: BrainEngine, id: string) {
}
export function createConnectorFixture() {
+ const backends = testBackends();
const home = mkdtempSync(join(tmpdir(), 'gbrain-connector-parity-'));
const engines: BrainEngine[] = [];
let closePostgres: (() => Promise<void>) | undefined;
const env = { GBRAIN_HOME: home, CONNECTOR_TEST_TOKEN: 'synthetic-local-fixture' };
const setup = async () => {
- const lite = new PGLiteEngine();
- await lite.connect({ database_path: join(home, 'database') });
- await lite.initSchema();
- engines.push(lite);
- if (process.env.DATABASE_URL) {
- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ if (backends.includes('pglite')) {
+ const lite = new PGLiteEngine();
+ await lite.connect({ database_path: join(home, 'database') });
+ await lite.initSchema();
+ engines.push(lite);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
engines.push(pg.engine);
closePostgres = pg.close;
}
@@ -110,5 +114,5 @@ export function createConnectorFixture() {
}
}
- return { home, engines, env, setup, teardown, source, boundSource, standaloneConnector };
+ return { home, engines, env, backends, setup, teardown, source, boundSource, standaloneConnector };
}
diff --git a/test/helpers/dense-hub.ts b/test/helpers/dense-hub.ts
index 441b53bd1d..8e7ac55a83 100644
--- a/test/helpers/dense-hub.ts
+++ b/test/helpers/dense-hub.ts
@@ -49,5 +49,6 @@ export async function seedDenseHub(engine: BrainEngine, ringOffsets = 5): Promis
for (let i = 0; i < links.length; i += 500) {
await engine.addLinksBatch(links.slice(i, i + 500));
}
+ await engine.executeRaw('ANALYZE pages, links');
return { edges: links.length };
}
diff --git a/test/helpers/test-backends.ts b/test/helpers/test-backends.ts
new file mode 100644
index 0000000000..e9ceb35ff6
--- /dev/null
+++ b/test/helpers/test-backends.ts
@@ -0,0 +1,26 @@
+import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
+import { withEnv } from './with-env.ts';
+
+export type TestBackend = 'pglite' | 'postgres';
+
+export function requirePostgresTestDatabase(env: Record<string, string | undefined> = process.env): string {
+ if (!env.DATABASE_URL) throw new Error('PostgreSQL test lane requires DATABASE_URL; refusing to skip its backend');
+ assertSafeE2eDatabaseUrl(env.DATABASE_URL, env);
+ return env.DATABASE_URL;
+}
+
+export function testBackends(env: Record<string, string | undefined> = process.env): TestBackend[] {
+ if (env.GBRAIN_TEST_BACKEND === 'postgres') {
+ requirePostgresTestDatabase(env);
+ return ['postgres'];
+ }
+ if (env.GBRAIN_TEST_BACKEND !== undefined) throw new Error('Unknown GBRAIN_TEST_BACKEND; expected postgres or unset');
+ return env.DATABASE_URL ? ['pglite', 'postgres'] : ['pglite'];
+}
+
+export async function registerPostgresTests(...loaders: Array<() => Promise<unknown>>): Promise<void> {
+ requirePostgresTestDatabase();
+ await withEnv({ GBRAIN_TEST_BACKEND: 'postgres' }, async () => {
+ for (const load of loaders) await load();
+ });
+}
diff --git a/test/import-configured-root-guard.serial.test.ts b/test/import-configured-root-guard.serial.test.ts
index c9a6421dbc..7e77190b48 100644
--- a/test/import-configured-root-guard.serial.test.ts
+++ b/test/import-configured-root-guard.serial.test.ts
@@ -1,4 +1,4 @@
-import { afterAll, afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
@@ -10,6 +10,7 @@ import {
} from '../src/commands/import.ts';
import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
let engine: PGLiteEngine;
let root: string;
@@ -22,10 +23,14 @@ function tempDir(prefix: string): string {
return dir;
}
-beforeEach(async () => {
+beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
root = tempDir('gbrain-configured-root-');
outside = tempDir('gbrain-configured-outside-');
writeFileSync(join(root, 'canonical.md'), '# canonical\n');
@@ -37,12 +42,9 @@ beforeEach(async () => {
);
});
-afterEach(async () => {
- await engine.disconnect();
-});
-
-afterAll(() => {
- for (const dir of scratch) rmSync(dir, { recursive: true, force: true });
+afterAll(async () => {
+ try { await engine?.disconnect(); }
+ finally { for (const dir of scratch) rmSync(dir, { recursive: true, force: true }); }
});
describe('configuredRootImportError', () => {
diff --git a/test/managed-connector-routing.serial.test.ts b/test/managed-connector-routing.serial.test.ts
index f112a287af..36c95fee6f 100644
--- a/test/managed-connector-routing.serial.test.ts
+++ b/test/managed-connector-routing.serial.test.ts
@@ -12,7 +12,9 @@ import { APPLICATION_AUTHORITY, withSubmissionAuthority } from '../src/core/mini
import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+const backends = testBackends();
const directory = mkdtempSync(join(tmpdir(), 'gbrain-connector-routing-'));
const engines: BrainEngine[] = [];
let closePostgres: (() => Promise<void>) | undefined;
@@ -22,9 +24,11 @@ const issue = { number: 1, title: 'Routing example', state: 'open', body: 'A dur
const json = (body: unknown) => new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' } });
beforeAll(async () => {
- const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
- if (process.env.DATABASE_URL) {
- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ if (backends.includes('pglite')) {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
engines.push(pg.engine); closePostgres = pg.close;
}
}, 120_000);
diff --git a/test/managed-maintenance.test.ts b/test/managed-maintenance.test.ts
index 79d84217e7..eeecab4062 100644
--- a/test/managed-maintenance.test.ts
+++ b/test/managed-maintenance.test.ts
@@ -25,16 +25,20 @@ import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
import { withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
import type { WriteRequest } from '../src/core/persistence/model.ts';
+import { testBackends } from './helpers/test-backends.ts';
+const backends = testBackends();
const engines: BrainEngine[] = [];
const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-maintenance-db-'));
let closePostgres: (() => Promise<void>) | undefined;
beforeAll(async () => {
configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
- const engine = new PGLiteEngine();
- await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);
- if (process.env.DATABASE_URL) {
- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
engines.push(pg.engine); closePostgres = pg.close;
}
}, 120_000);
diff --git a/test/managed-synthesis-postprocess.test.ts b/test/managed-synthesis-postprocess.test.ts
index b4ff46d6d4..4abf4c7ffc 100644
--- a/test/managed-synthesis-postprocess.test.ts
+++ b/test/managed-synthesis-postprocess.test.ts
@@ -13,19 +13,23 @@ import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedT
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
import * as staleEmbedding from '../src/core/embed-stale.ts';
+import { testBackends } from './helpers/test-backends.ts';
+const backends = testBackends();
const engines: BrainEngine[] = [];
let dataDir: string;
let closePostgres: (() => Promise<void>) | undefined;
beforeAll(async () => {
dataDir = mkdtempSync(join(tmpdir(), 'gbrain-synth-postprocess-db-'));
configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
- const engine = new PGLiteEngine();
- await engine.connect({ database_path: dataDir });
- await engine.initSchema();
- engines.push(engine);
- if (process.env.DATABASE_URL) {
- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir });
+ await engine.initSchema();
+ engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
engines.push(pg.engine);
closePostgres = pg.close;
}
diff --git a/test/page-projection-code-recovery.test.ts b/test/page-projection-code-recovery.test.ts
index 62e674288a..27fdc973b4 100644
--- a/test/page-projection-code-recovery.test.ts
+++ b/test/page-projection-code-recovery.test.ts
@@ -11,7 +11,9 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+const backends = testBackends();
const home = mkdtempSync(join(tmpdir(), 'gbrain-code-recovery-'));
const engines: BrainEngine[] = [];
let closePostgres: (() => Promise<void>) | undefined;
@@ -19,8 +21,10 @@ const sourceId = 'code-recovery-example';
const body = 'export function beta() { return 3; }\nexport function alpha() { return beta(); }\n';
beforeAll(async () => {
- const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
- if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ if (backends.includes('pglite')) {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
for (const engine of engines) await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
}, 120_000);
afterAll(async () => {
diff --git a/test/page-projection-origin.test.ts b/test/page-projection-origin.test.ts
index c9af7758a2..f0b80dc6c0 100644
--- a/test/page-projection-origin.test.ts
+++ b/test/page-projection-origin.test.ts
@@ -8,7 +8,9 @@ import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { installFixtureChunks } from './helpers/page-projection.ts';
import { withEnv } from './helpers/with-env.ts';
import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';
+import { testBackends } from './helpers/test-backends.ts';
+const backends = testBackends();
const engines: BrainEngine[] = [];
let closePostgres: (() => Promise<void>) | undefined;
const sourceId = 'projection-origin-test';
@@ -16,12 +18,14 @@ const body = Array.from({ length: 80 }, (_, i) => `Example sentence ${i} describ
const chunk = (text: string) => ({ chunk_index: 0, chunk_source: 'compiled_truth' as const, chunk_text: text });
beforeAll(async () => {
- const lite = new PGLiteEngine();
- await lite.connect({});
- await lite.initSchema();
- engines.push(lite);
- if (process.env.DATABASE_URL) {
- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ if (backends.includes('pglite')) {
+ const lite = new PGLiteEngine();
+ await lite.connect({});
+ await lite.initSchema();
+ engines.push(lite);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
engines.push(pg.engine);
closePostgres = pg.close;
}
diff --git a/test/page-projection-vector-preservation.test.ts b/test/page-projection-vector-preservation.test.ts
index bcd279dda4..777ca6845a 100644
--- a/test/page-projection-vector-preservation.test.ts
+++ b/test/page-projection-vector-preservation.test.ts
@@ -7,8 +7,10 @@ import { MIGRATIONS } from '../src/core/migrate.ts';
import { installPageEmbeddings, installPageProjection, PageProjectionConflictError, preparePageProjection,
readProjectionSnapshot, rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
const databaseUrl = process.env.DATABASE_URL;
+const backends = testBackends();
const sourceId = 'projection-vector-test';
const neighborId = 'projection-vector-neighbor';
const slug = 'same-page';
@@ -28,7 +30,7 @@ interface StoredChunk {
embedding_projection_test?: string | null;
}
-for (const kind of ['pglite', ...(databaseUrl ? ['postgres'] : [])]) {
+for (const kind of backends) {
describe(`projection vector preservation ${kind}`, () => {
let engine: BrainEngine;
let closePostgres: (() => Promise<void>) | undefined;
diff --git a/test/persistence-admin-recovery.test.ts b/test/persistence-admin-recovery.test.ts
index 45b4e48760..d1f54f8274 100644
--- a/test/persistence-admin-recovery.test.ts
+++ b/test/persistence-admin-recovery.test.ts
@@ -18,8 +18,10 @@ import { parsePersistenceAdminArgs } from '../src/commands/persistence-admin.ts'
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
-for (const kind of ['pglite', 'postgres'] as const) describe.skipIf(kind === 'postgres' && !process.env.DATABASE_URL)(`writer recovery (${kind})`, () => {
+const backends = testBackends();
+for (const kind of backends) describe(`writer recovery (${kind})`, () => {
const directory = mkdtempSync(join(tmpdir(), 'gbrain-admin-recovery-'));
let engine: BrainEngine, close: (() => Promise<void>) | undefined;
beforeAll(async () => {
@@ -198,7 +200,7 @@ for (const kind of ['pglite', 'postgres'] as const) describe.skipIf(kind === 'po
}), 30_000);
});
-test('writer parser accepts explicit self-transfer and cleanup opt-ins', () => {
+test.skipIf(!backends.includes('pglite'))('writer parser accepts explicit self-transfer and cleanup opt-ins', () => {
expect(parsePersistenceAdminArgs('writer', ['transfer', 'prepare', 'default', '--self-transfer']).params.self_transfer).toBe(true);
expect(parsePersistenceAdminArgs('writer', ['activate', '--confirm-quiesced', '--cleanup-dead-local-locks']).params.cleanup_dead_local_locks).toBe(true);
});
diff --git a/test/persistence-connector-retry.test.ts b/test/persistence-connector-retry.test.ts
index 50f19d3a05..8a91c67943 100644
--- a/test/persistence-connector-retry.test.ts
+++ b/test/persistence-connector-retry.test.ts
@@ -13,7 +13,7 @@ import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';
import { withEnv } from './helpers/with-env.ts';
import { createConnectorFixture, options, json, googleConfig, githubConfig, contact, issueFixture, githubFetch, sourceCheckpoint } from './helpers/connector-fixture.ts';
-const { engines, env, source, boundSource, standaloneConnector, setup, teardown } = createConnectorFixture();
+const { engines, env, backends, source, boundSource, standaloneConnector, setup, teardown } = createConnectorFixture();
beforeAll(setup, 120_000);
afterAll(teardown);
@@ -30,6 +30,7 @@ test('explicit connector retry replaces a real storage failure without changing
'test', import.meta.path, '--test-name-pattern', '^explicit connector retry replaces a real storage failure without changing ordinary replay or the cursor$'], {
env: { PATH: process.env.PATH, HOME: childHome, GBRAIN_HOME: childHome, TMPDIR: childHome,
DATABASE_URL: process.env.DATABASE_URL, GBRAIN_TEST_ALLOW_DATABASE_URL: '1', GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1',
+ GBRAIN_TEST_BACKEND: backends.includes('pglite') ? undefined : 'postgres',
GBRAIN_PGLITE_SNAPSHOT: process.env.GBRAIN_PGLITE_SNAPSHOT, GBRAIN_TEST_CONNECTOR_UNPRIVILEGED: '1' },
stdout: 'pipe', stderr: 'pipe',
});
diff --git a/test/persistence-effect-retry.test.ts b/test/persistence-effect-retry.test.ts
index 5916fdcf77..2b14b1207e 100644
--- a/test/persistence-effect-retry.test.ts
+++ b/test/persistence-effect-retry.test.ts
@@ -20,11 +20,12 @@ import { persistenceSocketPathForConfig, requestPersistenceAdministration, start
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
const databaseUrl = process.env.DATABASE_URL;
const model = 'openai:text-embedding-3-small';
const signature = `${model}:1536`;
-for (const kind of ['pglite', ...(databaseUrl ? ['postgres' as const] : [])] as const) {
+for (const kind of testBackends()) {
describe(`effect retry ${kind}`, () => {
let engine: BrainEngine;
let scratch: string;
diff --git a/test/persistence-embedding-effects.test.ts b/test/persistence-embedding-effects.test.ts
index 5c7f2d0263..8d0a2e3c62 100644
--- a/test/persistence-embedding-effects.test.ts
+++ b/test/persistence-embedding-effects.test.ts
@@ -18,10 +18,11 @@ import { MAX_RATE_LIMIT_RETRIES } from '../src/core/embed-retry.ts';
import { AIConfigError } from '../src/core/ai/errors.ts';
import { invokeAI, isAIInvocationPolicyError, withAIInvocationGuard } from '../src/core/ai/invocation-guard.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
const databaseUrl = process.env.DATABASE_URL;
-for (const kind of ['pglite', ...(databaseUrl ? ['postgres'] : [])] as const) {
+for (const kind of testBackends()) {
describe(`embedding effects ${kind}`, () => {
let engine: BrainEngine;
let scratch: string;
diff --git a/test/persistence-onboarding.test.ts b/test/persistence-onboarding.test.ts
index 0f33bc5d89..10e4b08172 100644
--- a/test/persistence-onboarding.test.ts
+++ b/test/persistence-onboarding.test.ts
@@ -13,11 +13,12 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { persistenceHome } from '../src/core/persistence/identity.ts';
import { PHYSICAL_ROOT_MARKER } from '../src/core/persistence/physical-root-record.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
import { withEnv } from './helpers/with-env.ts';
import { makeGitFixture } from './helpers/git-fixture.ts';
-for (const kind of ['pglite', 'postgres'] as const) describe.skipIf(kind === 'postgres' && !process.env.DATABASE_URL)(`deliberate onboarding (${kind})`, () => {
+for (const kind of testBackends()) describe(`deliberate onboarding (${kind})`, () => {
let engine: BrainEngine, close: (() => Promise<void>) | undefined;
const home = mkdtempSync(join(tmpdir(), 'gbrain-onboarding-')), root = join(home, 'canonical');
beforeAll(async () => {
diff --git a/test/persistence-skill-bundles.serial.test.ts b/test/persistence-skill-bundles.serial.test.ts
index a27269f622..fe0d4338fa 100644
--- a/test/persistence-skill-bundles.serial.test.ts
+++ b/test/persistence-skill-bundles.serial.test.ts
@@ -25,7 +25,9 @@ import { managedSyncAuthority } from '../src/core/persistence/sync-authority.ts'
import { SHARED_SKILLS_PERSISTENCE_SCHEMA_STATEMENTS } from '../src/core/shared-skills/persistence-schema.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { makeGitFixture } from './helpers/git-fixture.ts';
+import { testBackends } from './helpers/test-backends.ts';
+const backends = testBackends();
const home = mkdtempSync(join(tmpdir(), 'gbrain-skill-persistence-'));
const oldHome = process.env.GBRAIN_HOME;
const fixtures: Array<{ engine: BrainEngine; root: string; binding: WorktreeBinding; close(): Promise<void> }> = [];
@@ -35,10 +37,13 @@ let hostId: string;
beforeAll(async () => {
process.env.GBRAIN_HOME = home;
hostId = localHostId();
- const local = new PGLiteEngine();
- await local.connect({}); await local.initSchema();
- const engines = [{ engine: local as BrainEngine, close: () => local.disconnect() }];
- if (process.env.DATABASE_URL) engines.push(await isolatedPersistencePostgres(process.env.DATABASE_URL));
+ const engines: Array<{ engine: BrainEngine; close(): Promise<void> }> = [];
+ if (backends.includes('pglite')) {
+ const local = new PGLiteEngine();
+ await local.connect({}); await local.initSchema();
+ engines.push({ engine: local, close: () => local.disconnect() });
+ }
+ if (backends.includes('postgres')) engines.push(await isolatedPersistencePostgres(process.env.DATABASE_URL!));
for (const item of engines) {
for (const statement of SHARED_SKILLS_PERSISTENCE_SCHEMA_STATEMENTS) await item.engine.executeRaw(statement);
const gitRoot = join(home, item.engine.kind); mkdirSync(gitRoot);
diff --git a/test/persistence-skill-crash.slow.test.ts b/test/persistence-skill-crash.slow.test.ts
index ee986cb673..e90dbed7ed 100644
--- a/test/persistence-skill-crash.slow.test.ts
+++ b/test/persistence-skill-crash.slow.test.ts
@@ -5,11 +5,13 @@ import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import postgres from 'postgres';
import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';
+import { testBackends } from './helpers/test-backends.ts';
+const backends = testBackends();
const worker = join(import.meta.dir, 'fixtures/persistence-skill-worker.ts');
test('independent SIGKILL bundle publication and repeated restoration preserve receipts and quotas', async () => {
- for (const kind of process.env.DATABASE_URL ? ['pglite', 'postgres'] : ['pglite']) {
+ for (const kind of backends) {
const home = mkdtempSync(join(tmpdir(), 'gbrain-bundle-crash-'));
const configPath = join(home, 'worker.json');
const database = `gbrain_test_bundle_${randomUUID().replaceAll('-', '')}`;
diff --git a/test/persistence-sync-failures.serial.test.ts b/test/persistence-sync-failures.serial.test.ts
index de26502018..0ed5355c86 100644
--- a/test/persistence-sync-failures.serial.test.ts
+++ b/test/persistence-sync-failures.serial.test.ts
@@ -25,7 +25,9 @@ import { localHostId } from '../src/core/persistence/identity.ts';
import { currentExitCode, _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
+import { testBackends } from './helpers/test-backends.ts';
+const backends = testBackends();
const home = mkdtempSync(join(tmpdir(), 'gbrain-sync-failures-'));
const engines: BrainEngine[] = [];
let closePostgres: (() => Promise<void>) | undefined;
@@ -44,8 +46,10 @@ async function fixture(engine: BrainEngine, files: Record<string, string>) {
return { id, root, head };
}
beforeAll(async () => {
- const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
- if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ if (backends.includes('pglite')) {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
}, 120_000);
afterAll(async () => {
for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
@@ -273,7 +277,7 @@ test('local single and all-source CLI JSON carry durable diagnostics and fail th
}
}), 120_000);
-test('a new process reads the same failed receipt from a persisted PGLite brain', async () => withEnv(env, async () => {
+test.skipIf(!backends.includes('pglite'))('a new process reads the same failed receipt from a persisted PGLite brain', async () => withEnv(env, async () => {
const database = join(home, 'restart-db');
const engine = new PGLiteEngine(); await engine.connect({ database_path: database }); await engine.initSchema();
let expected: Awaited<ReturnType<typeof performManagedSync>>, sourceId: string;
diff --git a/test/scripts/capture-test-log.test.ts b/test/scripts/capture-test-log.test.ts
index 51271dffcf..d197eca378 100644
--- a/test/scripts/capture-test-log.test.ts
+++ b/test/scripts/capture-test-log.test.ts
@@ -123,8 +123,10 @@ process.exitCode = 7;
for (const signal of ['SIGTERM', 'SIGINT'] as const) {
it(`forwards ${signal} to its owned child and grandchild`, async () => {
const f = fixture(`
+import { renameSync } from 'node:fs';
const child = Bun.spawn([process.execPath, '-e', 'setInterval(() => {}, 1000)'], { stdout: 'ignore', stderr: 'ignore' });
-await Bun.write(process.argv[2], JSON.stringify([process.pid, child.pid]));
+await Bun.write(process.argv[2] + '.tmp', JSON.stringify([process.pid, child.pid]));
+renameSync(process.argv[2] + '.tmp', process.argv[2]);
setInterval(() => {}, 1000);
`);
const pidsFile = join(f.root, 'pids.json');
@@ -143,6 +145,7 @@ setInterval(() => {}, 1000);
for (let i = 0; i < 100 && !existsSync(pidsFile); i++) await Bun.sleep(20);
expect(existsSync(pidsFile)).toBe(true);
pids = JSON.parse(readFileSync(pidsFile, 'utf8'));
+ expect(pids).toHaveLength(2);
expect(pids.every(alive)).toBe(true);
proc.kill(signal);
expect(await proc.exited).toBe(signal === 'SIGINT' ? 130 : 143);
diff --git a/test/scripts/ci-gates.test.ts b/test/scripts/ci-gates.test.ts
index 3137c54e38..693eb68944 100644
--- a/test/scripts/ci-gates.test.ts
+++ b/test/scripts/ci-gates.test.ts
@@ -6,18 +6,24 @@ import { spawnSync } from 'node:child_process';
import { safeLoad } from 'js-yaml';
const root = join(import.meta.dir, '..', '..');
-type Job = { needs?: string | string[]; if?: string; steps: Array<{ name?: string; run?: string; uses?: string }> };
+type Job = { needs?: string | string[]; if?: string; steps: Array<{ name?: string; run?: string; uses?: string; env?: Record<string, string> }> };
type Workflow = { on: Record<string, { paths?: string[] }>; jobs: Record<string, Job> };
const loadWorkflow = (name: string) => safeLoad(readFileSync(join(root, '.github/workflows', name), 'utf8')) as Workflow;
const unit = loadWorkflow('test.yml');
const e2e = loadWorkflow('e2e.yml');
-function aggregate(workflow: Workflow, name: string, event: string, results: Record<string, string>) {
- const script = workflow.jobs[name].steps.find(step => step.name === 'Aggregate result')!.run!
+const fullProfile = "github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)";
+function aggregate(workflow: Workflow, name: string, event: string, results: Record<string, string>, fullCorpus = false) {
+ const step = workflow.jobs[name].steps.find(step => step.name === 'Aggregate result')!;
+ const render = (value: string) => value
.replace(/\$\{\{ needs\.([\w-]+)\.result \}\}/g, (_, job) => results[job] ?? 'success')
+ .replaceAll('${{ ' + fullProfile + ' }}', String(event === 'schedule' || (event === 'workflow_dispatch' && fullCorpus)))
.replace(/\$\{\{ github.event_name \}\}/g, event);
+ const script = render(step.run!);
+ const env = Object.fromEntries(Object.entries(step.env ?? {}).map(([key, value]) => [key, render(value)]));
expect(script).not.toContain('${{');
- return spawnSync('bash', ['-e', '-c', script], { encoding: 'utf8' }).status;
+ expect(Object.values(env).join('\n')).not.toContain('${{');
+ return spawnSync('bash', ['-e', '-c', script], { encoding: 'utf8', env: { ...process.env, ...env } }).status;
}
describe('CI execution evidence', () => {
@@ -64,8 +70,10 @@ describe('CI execution evidence', () => {
for (const job of needs) {
for (const result of ['failure', 'cancelled', 'skipped']) {
expect(aggregate(e2e, 'e2e-status', 'schedule', { [job]: result }), `${job}: ${result}`).toBe(1);
+ expect(aggregate(e2e, 'e2e-status', 'workflow_dispatch', { [job]: result }, true), `manual full ${job}: ${result}`).toBe(1);
}
}
+ expect(aggregate(e2e, 'e2e-status', 'workflow_dispatch', {}, true)).toBe(0);
});
test('admin manifest changes trigger the security scan and CI installs are frozen', () => {
diff --git a/test/scripts/ci-local-rendering.test.ts b/test/scripts/ci-local-rendering.test.ts
index 30f3ca3162..472c2e9d87 100644
--- a/test/scripts/ci-local-rendering.test.ts
+++ b/test/scripts/ci-local-rendering.test.ts
@@ -247,7 +247,22 @@ describe('required PgBouncer execution through run-e2e', () => {
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"
-printf ' %s pass\\n 0 fail\\n' "$FAKE_PASSES"
+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 });
diff --git a/test/scripts/e2e-matrix.test.ts b/test/scripts/e2e-matrix.test.ts
index a8f81fca05..c0c33f8476 100644
--- a/test/scripts/e2e-matrix.test.ts
+++ b/test/scripts/e2e-matrix.test.ts
@@ -58,41 +58,75 @@ describe('frozen E2E matrix', () => {
writeFileSync(join(root, 'scripts/run-e2e.sh'), 'exit 17\n');
expect(worker(root, { shard: 1, files: [paths[0]], empty: false }).status).toBe(17);
}));
- test.each(['SIGTERM', 'SIGINT'] as const)('forwards %s cancellation to its owned runner and preserves its exit status', async (signal) => {
- const root = mkdtempSync(join(tmpdir(), 'gbrain-e2e-matrix-cancel-'));
- let child: ReturnType<typeof Bun.spawn> | undefined;
- let runnerPid = 0;
- try {
- mkdirSync(join(root, 'scripts'));
- mkdirSync(join(root, 'test/e2e'), { recursive: true });
- writeFileSync(join(root, paths[0]), '// frozen fixture');
- // Trap the actual signal in a portable shell child. Its completion marker
- // proves the wrapper forwarded cancellation instead of merely dying.
- writeFileSync(join(root, 'scripts/run-e2e.sh'), `trap 'printf "SIGTERM\\n" > received.txt; exit 143' TERM
+ test.each(['SIGTERM', 'SIGINT'] as const)('preserves %s cancellation when its runner has already finished', signal => fixture(root => {
+ const result = spawnSync(process.execPath, ['-e', `
+ const { runRow } = await import(${JSON.stringify(join(repo, 'scripts/e2e-matrix.ts'))});
+ Bun.spawn = () => {
+ process.emit(${JSON.stringify(signal)});
+ return { exited: Promise.resolve(0), kill(signal) { console.log('FORWARDED:' + signal); } };
+ };
+ process.exitCode = await runRow(JSON.parse(process.env.E2E_MATRIX_ROW));
+ `], {
+ cwd: root, encoding: 'utf8',
+ env: { ...process.env, E2E_MATRIX_ROW: JSON.stringify({ shard: 1, files: [paths[0]], empty: false }) },
+ });
+ expect(result.status, result.stderr).toBe(signal === 'SIGINT' ? 130 : 143);
+ expect(result.stdout).toContain(`FORWARDED:${signal}`);
+ }));
+ for (const delaySpawnReturn of [false, true]) {
+ test.each(['SIGTERM', 'SIGINT'] as const)(delaySpawnReturn
+ ? 'forwards %s cancellation received before spawn returns'
+ : 'forwards %s cancellation to its owned runner and preserves its exit status', async (signal) => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-e2e-matrix-cancel-'));
+ let child: ReturnType<typeof Bun.spawn> | undefined;
+ let runnerPid = 0;
+ try {
+ mkdirSync(join(root, 'scripts'));
+ mkdirSync(join(root, 'test/e2e'), { recursive: true });
+ writeFileSync(join(root, paths[0]), '// frozen fixture');
+ // Trap the actual signal in a portable shell child. Its completion marker
+ // proves the wrapper forwarded cancellation instead of merely dying.
+ writeFileSync(join(root, 'scripts/run-e2e.sh'), `trap 'printf "SIGTERM\\n" > received.txt; exit 143' TERM
trap 'printf "SIGINT\\n" > received.txt; exit 130' INT
-printf '%s\\n' "$$" > runner.pid
+printf '%s\\n' "$$" > runner.pid.tmp
+mv runner.pid.tmp runner.pid
while :; do sleep 0.05; done
`);
- child = Bun.spawn([process.execPath, join(repo, 'scripts/e2e-matrix.ts'), 'run'], {
- cwd: root,
- env: { ...process.env, SHARD: '4/4', E2E_MATRIX_ROW: JSON.stringify({ shard: 1, files: [paths[0]], empty: false }) },
- stdout: 'ignore', stderr: 'ignore',
- });
- const readyDeadline = Date.now() + 5000;
- while (!existsSync(join(root, 'runner.pid')) && Date.now() < readyDeadline) await Bun.sleep(20);
- expect(existsSync(join(root, 'runner.pid'))).toBe(true);
- runnerPid = Number(readFileSync(join(root, 'runner.pid'), 'utf8'));
- child.kill(signal);
- const exitDeadline = Date.now() + 5000;
- while (child.exitCode === null && Date.now() < exitDeadline) await Bun.sleep(20);
- expect(child.exitCode).toBe(signal === 'SIGINT' ? 130 : 143);
- expect(readFileSync(join(root, 'received.txt'), 'utf8').trim()).toBe(signal);
- expect(() => process.kill(runnerPid, 0)).toThrow();
- } finally {
- child?.kill('SIGKILL');
- if (runnerPid) { try { process.kill(runnerPid, 'SIGKILL'); } catch { /* already reaped */ } }
- if (child) await child.exited;
- rmSync(root, { recursive: true, force: true });
- }
- }, 15000);
+ const command = delaySpawnReturn ? [process.execPath, '-e', `
+ const { existsSync } = await import('node:fs');
+ const spawn = Bun.spawn;
+ Bun.spawn = (...args) => {
+ const child = spawn(...args);
+ const deadline = Date.now() + 5000;
+ while (!existsSync('cancellation-sent') && Date.now() < deadline) Bun.sleepSync(5);
+ return child;
+ };
+ const { runRow } = await import(${JSON.stringify(join(repo, 'scripts/e2e-matrix.ts'))});
+ process.exitCode = await runRow(JSON.parse(process.env.E2E_MATRIX_ROW));
+ `] : [process.execPath, join(repo, 'scripts/e2e-matrix.ts'), 'run'];
+ child = Bun.spawn(command, {
+ cwd: root,
+ env: { ...process.env, SHARD: '4/4', E2E_MATRIX_ROW: JSON.stringify({ shard: 1, files: [paths[0]], empty: false }) },
+ stdout: 'ignore', stderr: 'ignore',
+ });
+ const readyDeadline = Date.now() + 5000;
+ while (!existsSync(join(root, 'runner.pid')) && Date.now() < readyDeadline) await Bun.sleep(20);
+ expect(existsSync(join(root, 'runner.pid'))).toBe(true);
+ runnerPid = Number(readFileSync(join(root, 'runner.pid'), 'utf8'));
+ expect(runnerPid).toBeGreaterThan(0);
+ child.kill(signal);
+ if (delaySpawnReturn) writeFileSync(join(root, 'cancellation-sent'), 'sent');
+ const exitDeadline = Date.now() + 5000;
+ while (child.exitCode === null && Date.now() < exitDeadline) await Bun.sleep(20);
+ expect(child.exitCode).toBe(signal === 'SIGINT' ? 130 : 143);
+ expect(readFileSync(join(root, 'received.txt'), 'utf8').trim()).toBe(signal);
+ expect(() => process.kill(runnerPid, 0)).toThrow();
+ } finally {
+ child?.kill('SIGKILL');
+ if (runnerPid) { try { process.kill(runnerPid, 'SIGKILL'); } catch { /* already reaped */ } }
+ if (child) await child.exited;
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 15000);
+ }
});
diff --git a/test/scripts/e2e-runner.test.ts b/test/scripts/e2e-runner.test.ts
index 9d8c90967f..1729590441 100644
--- a/test/scripts/e2e-runner.test.ts
+++ b/test/scripts/e2e-runner.test.ts
@@ -12,11 +12,11 @@ function setup() {
for (const name of ['a', 'b']) writeFileSync(join(root, `test/e2e/${name}.test.ts`), `import {test,expect} from 'bun:test'; test('isolated routing',()=>{ expect(process.env.SHARD).toBeUndefined(); expect(process.env.COVERAGE_DIR ?? '').toBe(''); });`);
return root;
}
-const env = { ...process.env, GBRAIN_NO_SNAPSHOT: '1', DATABASE_URL: '', GBRAIN_DATABASE_URL: '', SHARD: '', COVERAGE_DIR: '' };
-function run(root: string, args: string[], shard = '') {
- return spawnSync('bash', ['scripts/run-e2e.sh', ...args], { cwd: root, encoding: 'utf8', env: { ...env, SHARD: shard } });
-}
-describe('sequential E2E runner', () => {
+for (const githubActions of ['', 'true']) describe(`sequential E2E runner (GITHUB_ACTIONS=${githubActions})`, () => {
+ const env = { ...process.env, GITHUB_ACTIONS: githubActions, GBRAIN_NO_SNAPSHOT: '1', DATABASE_URL: '', GBRAIN_DATABASE_URL: '', SHARD: '', COVERAGE_DIR: '' };
+ function run(root: string, args: string[], shard = '') {
+ return spawnSync('bash', ['scripts/run-e2e.sh', ...args], { cwd: root, encoding: 'utf8', env: { ...env, SHARD: shard } });
+ }
test('weighted shards cover exactly the explicit input; empty shards launch nothing', () => {
const root = setup();
try {
@@ -44,6 +44,160 @@ describe('sequential E2E runner', () => {
expect(bad.stdout).toContain('Files: 2 total, 1 passed, 1 failed');
} finally { rmSync(root, { recursive: true, force: true }); }
});
+ test('coverage keeps fresh processes, disjoint LCOV directories, shard identity and successful execution receipts', () => {
+ const root = setup();
+ try {
+ const coverage = join(root, 'coverage');
+ const files = ['test/e2e/a.test.ts', 'test/e2e/b.test.ts'];
+ writeFileSync(join(root, 'bin/git'), '#!/bin/sh\nprintf fixture-commit\n', { mode: 0o755 });
+ writeFileSync(join(root, 'test/e2e/source.ts'), 'export const answer = () => 42;');
+ for (const file of files) writeFileSync(join(root, file), `import {test,expect} from 'bun:test';
+import {appendFileSync} from 'node:fs';
+import {answer} from './source';
+test('fresh process',()=>{
+ expect(process.env.SHARD).toBeUndefined();
+ expect((globalThis as any).priorFile).toBeUndefined();
+ (globalThis as any).priorFile = true;
+ expect(answer()).toBe(42);
+ appendFileSync(${JSON.stringify(join(root, 'pids.txt'))}, process.pid+'\\n');
+});`);
+ const coverageEnv = { ...env, SHARD: '1/1', COVERAGE_DIR: coverage, PATH: `${join(root, 'bin')}:${process.env.PATH}` };
+ const good = spawnSync('bash', ['scripts/run-e2e.sh', ...files], { cwd: root, env: coverageEnv, encoding: 'utf8' });
+ expect(good.status, good.stdout + good.stderr).toBe(0);
+ expect(new Set(readFileSync(join(root, 'pids.txt'), 'utf8').trim().split('\n')).size).toBe(2);
+ expect(existsSync(join(coverage, 'e2e-1/lcov.info'))).toBe(true);
+ expect(existsSync(join(coverage, 'e2e-2/lcov.info'))).toBe(true);
+ expect(JSON.parse(readFileSync(join(coverage, 'lane-manifest.json'), 'utf8'))).toEqual({ lane: 'e2e-1', sha: 'fixture-commit', lcovCount: 2, complete: true });
+ expect(readFileSync(join(coverage, 'executed-files.txt'), 'utf8').trim().split('\n').sort()).toEqual(files);
+ const shorterCoverage = join(root, 'shorter-coverage');
+ const shorter = spawnSync('bash', ['scripts/run-e2e.sh', files[0]], { cwd: root, env: { ...coverageEnv, COVERAGE_DIR: shorterCoverage }, encoding: 'utf8' });
+ expect(shorter.status, shorter.stdout + shorter.stderr).toBe(0);
+ expect(existsSync(join(shorterCoverage, 'e2e-2/lcov.info'))).toBe(false);
+ expect(JSON.parse(readFileSync(join(shorterCoverage, 'lane-manifest.json'), 'utf8')).lcovCount).toBe(1);
+ expect(readFileSync(join(shorterCoverage, 'executed-files.txt'), 'utf8')).toBe(files[0] + '\n');
+ writeFileSync(join(root, files[0]), "import {test} from 'bun:test';test.skip('optional',()=>{});");
+ const skippedCoverage = join(root, 'skipped-coverage');
+ const skipped = spawnSync('bash', ['scripts/run-e2e.sh', files[0]], { cwd: root, env: { ...coverageEnv, COVERAGE_DIR: skippedCoverage }, encoding: 'utf8' });
+ expect(skipped.status, skipped.stdout + skipped.stderr).toBe(0);
+ expect(existsSync(join(skippedCoverage, 'e2e-1/lcov.info'))).toBe(false);
+ expect(JSON.parse(readFileSync(join(skippedCoverage, 'lane-manifest.json'), 'utf8')).lcovCount).toBe(0);
+ expect(existsSync(join(coverage, 'e2e-2/lcov.info'))).toBe(true);
+ expect(JSON.parse(readFileSync(join(coverage, 'lane-manifest.json'), 'utf8')).lcovCount).toBe(2);
+ writeFileSync(join(root, files[0]), "import {test,expect} from 'bun:test';test('failure',()=>expect(1).toBe(2));");
+ const failedCoverage = join(root, 'failed-coverage');
+ const bad = spawnSync('bash', ['scripts/run-e2e.sh', ...files], { cwd: root, env: { ...coverageEnv, COVERAGE_DIR: failedCoverage }, encoding: 'utf8' });
+ expect(bad.status).toBe(1);
+ expect(existsSync(join(failedCoverage, 'lane-manifest.json'))).toBe(false);
+ expect(existsSync(join(failedCoverage, 'executed-files.txt'))).toBe(false);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+ test.each(['empty', 'populated'])('refuses an existing %s coverage destination without changing its files', kind => {
+ const root = setup();
+ try {
+ const coverage = join(root, 'coverage');
+ mkdirSync(coverage);
+ const prior: Record<string, string> = kind === 'empty' ? {} : {
+ 'e2e-1/lcov.info': 'numbered prior result',
+ 'other/lcov.info': 'unrelated prior result',
+ 'lane-manifest.json': '{"complete":true,"sha":"prior-commit"}',
+ 'executed-files.txt': 'prior file receipt',
+ };
+ for (const [file, contents] of Object.entries(prior)) {
+ mkdirSync(join(coverage, file, '..'), { recursive: true });
+ writeFileSync(join(coverage, file), contents);
+ }
+ const result = spawnSync('bash', ['scripts/run-e2e.sh', 'test/e2e/a.test.ts'], {
+ cwd: root, encoding: 'utf8', env: { ...env, COVERAGE_DIR: coverage },
+ });
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('must be a new, unused directory');
+ expect(result.stdout).not.toContain('=== a.test.ts ===');
+ for (const [file, contents] of Object.entries(prior)) expect(readFileSync(join(coverage, file), 'utf8')).toBe(contents);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+ test('a fully skipped file has execution evidence but need not emit LCOV', () => {
+ const root = setup();
+ try {
+ writeFileSync(join(root, 'bin/git'), '#!/bin/sh\nprintf fixture-commit\n', { mode: 0o755 });
+ writeFileSync(join(root, 'test/e2e/a.test.ts'), "import {test} from 'bun:test'; test.skip('requires optional fixture',()=>{});");
+ const result = spawnSync('bash', ['scripts/run-e2e.sh', 'test/e2e/a.test.ts'], {
+ cwd: root, encoding: 'utf8', env: { ...env, COVERAGE_DIR: 'coverage', PATH: `${join(root, 'bin')}:${process.env.PATH}` },
+ });
+ expect(result.status, result.stdout + result.stderr).toBe(0);
+ expect(JSON.parse(readFileSync(join(root, 'coverage/lane-manifest.json'), 'utf8'))).toEqual({ lane: 'e2e', sha: 'fixture-commit', lcovCount: 0, complete: true });
+ expect(readFileSync(join(root, 'coverage/executed-files.txt'), 'utf8')).toBe('test/e2e/a.test.ts\n');
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+ test('native reports retain nested imported suites, skips and todos within the selected file', () => {
+ const root = setup();
+ try {
+ writeFileSync(join(root, 'test/imported.ts'), `import {describe,test,expect} from 'bun:test';
+describe('imported',()=>{
+ test('pass',()=>expect(1).toBe(1));
+ describe('nested',()=>test.skip('skip',()=>{}));
+});
+describe('second',()=>test.todo('todo'));`);
+ writeFileSync(join(root, 'test/e2e/a.test.ts'), "import '../imported';");
+ const result = run(root, ['test/e2e/a.test.ts']);
+ expect(result.status, result.stdout + result.stderr).toBe(0);
+ expect(result.stdout).toContain('1 pass');
+ expect(result.stdout).toContain('1 skip');
+ expect(result.stdout).toContain('1 todo');
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+ test.each(['early exit', 'nested summary without parent', 'nested summary with parent'])('%s requires the selected Bun process to finish', kind => {
+ const root = setup();
+ try {
+ writeFileSync(join(root, 'bin/git'), '#!/bin/sh\nprintf fixture-commit\n', { mode: 0o755 });
+ writeFileSync(join(root, 'test/child.test.ts'), "import {test,expect} from 'bun:test'; test('child',()=>expect(1).toBe(1));");
+ writeFileSync(join(root, 'test/e2e/a.test.ts'), `import {test,expect} from 'bun:test';
+import {spawnSync} from 'node:child_process';
+test('parent',()=>{
+ if (${kind !== 'early exit'}) {
+ const child = spawnSync(process.execPath, ['test', 'test/child.test.ts'], {encoding:'utf8'});
+ console.log(child.stdout);
+ console.error(child.stderr);
+ expect(child.status).toBe(0);
+ }
+ if (${kind !== 'nested summary with parent'}) process.exit(0);
+});`);
+ const result = spawnSync('bash', ['scripts/run-e2e.sh', 'test/e2e/a.test.ts'], {
+ cwd: root, encoding: 'utf8', env: { ...env, COVERAGE_DIR: 'coverage', PATH: `${join(root, 'bin')}:${process.env.PATH}` },
+ });
+ const complete = kind === 'nested summary with parent';
+ expect(result.status, result.stdout + result.stderr).toBe(complete ? 0 : 1);
+ expect(existsSync(join(root, 'coverage/lane-manifest.json'))).toBe(complete);
+ expect(existsSync(join(root, 'coverage/executed-files.txt'))).toBe(complete);
+ if (!complete) expect(result.stdout).toContain('did not produce a complete native Bun report');
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+ test.each(['missing console summary', 'missing pass count', 'wrong console file', 'wrong report file', 'reported failure', 'missing testcases', 'truncated XML', 'mismatched XML', 'hidden failure', 'wrong suite count'])('%s cannot turn zero exit into completion', kind => {
+ const root = setup();
+ try {
+ const selected = 'test/e2e/a.test.ts';
+ const header = kind === 'wrong console file' ? 'test/e2e/other.test.ts' : selected;
+ const file = kind === 'wrong report file' ? 'test/e2e/other.test.ts' : selected;
+ const failures = kind === 'reported failure' ? 1 : 0;
+ const counts = kind === 'missing pass count' ? ' 0 fail\n' : ` ${1 - failures} pass\n ${failures} fail\n`;
+ const output = `bun test v1.3.13\n\n${githubActions ? '::group::' : ''}${header}:\n${counts}${kind === 'missing console summary' ? '' : 'Ran 1 test across 1 file. [1.00ms]\n'}`;
+ const testcase = kind === 'missing testcases' ? '' : `<testcase name="parent" file="${file}">${failures || kind === 'hidden failure' ? '<failure />' : ''}</testcase>`;
+ let xml = `<testsuites tests="1" failures="${failures}" skipped="0">\n <testsuite file="${file}" tests="${kind === 'wrong suite count' ? 2 : 1}" failures="${failures}" skipped="0">${testcase}</testsuite>\n</testsuites>\n`;
+ if (kind === 'truncated XML') xml = xml.slice(0, xml.indexOf('</testsuites>'));
+ if (kind === 'mismatched XML') xml = xml.replace('</testcase>', '</broken>');
+ writeFileSync(join(root, 'bin/bun'), `#!/bin/sh
+for arg do case "$arg" in --reporter-outfile=*) report="\${arg#*=}" ;; esac; done
+printf '%s' '${xml}' > "$report"
+printf '%s' '${output}'
+`, { mode: 0o755 });
+ const result = spawnSync('bash', ['scripts/run-e2e.sh', selected], {
+ cwd: root, encoding: 'utf8', env: { ...env, COVERAGE_DIR: 'coverage', PATH: `${join(root, 'bin')}:${process.env.PATH}` },
+ });
+ expect(result.status, result.stdout + result.stderr).toBe(1);
+ expect(result.stdout).toContain('did not produce a complete native Bun report');
+ expect(existsSync(join(root, 'coverage/lane-manifest.json'))).toBe(false);
+ expect(existsSync(join(root, 'coverage/executed-files.txt'))).toBe(false);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
for (const firstFails of [false, true]) test(`each file has a fresh home after a ${firstFails ? 'failing' : 'passing'} config writer`, () => {
const root = setup();
try {
@@ -81,22 +235,32 @@ describe('sequential E2E runner', () => {
for (const home of selected) expect(existsSync(home)).toBe(false);
} finally { rmSync(root, { recursive: true, force: true }); }
});
- test('cancellation terminates its owned interrupt-resistant child', async () => {
+ test.each(['SIGTERM', 'SIGINT'] as const)('%s terminates its owned interrupt-resistant child', async signal => {
const root = setup();
let child: ReturnType<typeof Bun.spawn> | undefined;
let pid: number | undefined;
try {
const fake = join(root, 'bin/bun');
- writeFileSync(fake, `#!/usr/bin/env bash\necho $$ > '${join(root, 'child.pid')}'\ntrap '' INT TERM\nwhile true; do sleep 1; done\n`);
+ const coverage = join(root, 'coverage');
+ writeFileSync(fake, `#!/usr/bin/env bash\ntrap '' INT TERM\necho $$ > '${join(root, 'child.pid.tmp')}'\nmv '${join(root, 'child.pid.tmp')}' '${join(root, 'child.pid')}'\nwhile true; do sleep 1; done\n`);
chmodSync(fake, 0o755);
- child = Bun.spawn(['bash', 'scripts/run-e2e.sh', 'test/e2e/a.test.ts'], { cwd: root, env: { ...env, PATH: `${join(root, 'bin')}:${process.env.PATH}` }, stdout: 'ignore', stderr: 'ignore' });
+ child = Bun.spawn(['bash', 'scripts/run-e2e.sh', 'test/e2e/a.test.ts'], { cwd: root, env: { ...env, COVERAGE_DIR: coverage, PATH: `${join(root, 'bin')}:${process.env.PATH}` }, stdout: 'ignore', stderr: 'ignore' });
const deadline = Date.now() + 5000;
while (!existsSync(join(root, 'child.pid')) && Date.now() < deadline) await Bun.sleep(20);
expect(existsSync(join(root, 'child.pid'))).toBe(true);
pid = Number(readFileSync(join(root, 'child.pid'), 'utf8').trim());
- child.kill('SIGTERM');
- expect(await child.exited).toBe(143);
+ expect(pid).toBeGreaterThan(0);
+ const collision = spawnSync('bash', ['scripts/run-e2e.sh', 'test/e2e/a.test.ts'], {
+ cwd: root, env: { ...env, COVERAGE_DIR: coverage, PATH: `${join(root, 'bin')}:${process.env.PATH}` }, encoding: 'utf8',
+ });
+ expect(collision.status).toBe(1);
+ expect(collision.stderr).toContain('must be a new, unused directory');
+ expect(() => process.kill(pid!, 0)).not.toThrow();
+ child.kill(signal);
+ expect(await child.exited).toBe(signal === 'SIGINT' ? 130 : 143);
expect(() => process.kill(pid!, 0)).toThrow();
+ expect(existsSync(join(coverage, 'lane-manifest.json'))).toBe(false);
+ expect(existsSync(join(coverage, 'executed-files.txt'))).toBe(false);
} finally {
child?.kill();
if (pid) { try { process.kill(pid, 'SIGKILL'); } catch {} }
diff --git a/test/scripts/merge-lcov.test.ts b/test/scripts/merge-lcov.test.ts
index 934ee4a2c2..4df4b3c93d 100644
--- a/test/scripts/merge-lcov.test.ts
+++ b/test/scripts/merge-lcov.test.ts
@@ -288,6 +288,28 @@ describe("merge: lane manifests", () => {
expect(readSummary(out.json).degraded).toBe(true);
});
+ it('requires all four nightly E2E identities with their independent multi-process LCOV counts', () => {
+ const dirs = Array.from({ length: 4 }, (_, i) => {
+ const dir = laneDir(`nightly-e2e-${i}`, LANE_A, { lane: `e2e-${i + 1}`, sha: HEAD_SHA, lcovCount: 2, complete: true });
+ mkdirSync(join(dir, 'second'));
+ writeFileSync(join(dir, 'second/lcov.info'), LANE_B);
+ return dir;
+ });
+ const out = outPaths('nightly-e2e');
+ const args = ['--out-lcov', out.lcov, '--out-json', out.json, '--manifest-expect', 'e2e-1,e2e-2,e2e-3,e2e-4'];
+ runMerge([...args, ...dirs]);
+ expect(readSummary(out.json).degraded).toBe(false);
+ expect(readSummary(out.json).lanes.complete).toEqual(['e2e-1', 'e2e-2', 'e2e-3', 'e2e-4']);
+ for (let absent = 0; absent < 4; absent++) {
+ runMerge([...args, ...dirs.filter((_, index) => index !== absent)]);
+ expect(readSummary(out.json).degraded).toBe(true);
+ }
+ rmSync(join(dirs[3], 'second/lcov.info'));
+ runMerge([...args, ...dirs]);
+ expect(readSummary(out.json).degraded).toBe(true);
+ expect(readSummary(out.json).lanes.complete).not.toContain('e2e-4');
+ });
+
it.each([
['missing count', { lcovCount: undefined }],
['wrong count', { lcovCount: 2 }],
diff --git a/test/scripts/mine-shard-weights.test.ts b/test/scripts/mine-shard-weights.test.ts
index 5f31547286..2e7cec213f 100644
--- a/test/scripts/mine-shard-weights.test.ts
+++ b/test/scripts/mine-shard-weights.test.ts
@@ -12,6 +12,7 @@ import {
mineWeights,
parseLog,
serializeWeights,
+ sourceE2ECorpus,
} from "../../scripts/mine-shard-weights.ts";
const SAMPLE = `test (1)\tUNKNOWN STEP\t2026-05-25T11:26:40.000000Z ##[group]test/alpha.test.ts:
@@ -75,6 +76,46 @@ describe("parseLog", () => {
});
});
+describe('full E2E timing extraction', () => {
+ const expectedFiles = ['test/e2e/alpha.test.ts', 'test/phantom-redirect-engine-parity.test.ts'];
+ const line = (job: string, text: string) => `${job}\tstep\t2026-09-24T06:00:00.000Z ${text}\n`;
+ const file = (job: string, name: string) => line(job, `=== ${name} ===`) + line(job, ' 0 fail') + line(job, 'Ran 1 test across 1 file. [2.50s]');
+ const complete = (job: string, names: string[]) => names.map(name => file(job, name)).join('') + line(job, `Files: ${names.length} total, ${names.length} passed, 0 failed`);
+ const raw = complete('coverage-full-e2e', ['alpha.test.ts', 'phantom-redirect-engine-parity.test.ts']);
+ const opts = { e2eProfile: 'full' as const, expectedFiles, expectedJobs: ['coverage-full-e2e'] };
+ it('resolves the outside-directory parity file without including selected-job timings', () => {
+ const noise = complete('Selected E2E (diff-relevant) 1', ['unrelated.test.ts']);
+ expect(Object.fromEntries(mineWeights(raw + noise, 'e2e', opts))).toEqual(Object.fromEntries(expectedFiles.map(file => [file, 2500])));
+ expect(Object.fromEntries(mineWeights(raw + noise, 'e2e'))).toEqual({ 'test/e2e/unrelated.test.ts': 2500 });
+ });
+ it('uses the final parent summary rather than a nested child summary', () => {
+ for (const [job, options] of [['coverage-full-e2e', opts], ['Selected E2E (diff-relevant) 1', {}]] as const) {
+ const nested = line(job, '=== alpha.test.ts ===') + line(job, ' 0 fail') + line(job, 'Ran 1 test across 1 file. [1.00ms]')
+ + line(job, ' 0 fail') + line(job, 'Ran 1 test across 1 file. [80.00ms]')
+ + file(job, 'phantom-redirect-engine-parity.test.ts') + line(job, 'Files: 2 total, 2 passed, 0 failed');
+ expect(mineWeights(nested, 'e2e', options).get(expectedFiles[0])).toBe(80);
+ expect(() => mineWeights(nested.replace(' 0 fail\n' + line(job, 'Ran 1 test across 1 file. [80.00ms]'), ' 1 fail\n' + line(job, 'Ran 1 test across 1 file. [80.00ms]')), 'e2e', options)).toThrow();
+ }
+ });
+ it('requires complete, disjoint matrix jobs and rejects missing, ambiguous and extra files', () => {
+ const jobs = ['coverage-full-e2e (1)', 'coverage-full-e2e (2)'];
+ const matrix = complete(jobs[0], ['alpha.test.ts']) + complete(jobs[1], ['phantom-redirect-engine-parity.test.ts']);
+ expect(mineWeights(matrix, 'e2e', { ...opts, expectedJobs: jobs }).size).toBe(2);
+ for (const bad of [
+ complete(jobs[0], ['alpha.test.ts']),
+ complete(jobs[0], ['alpha.test.ts']) + complete(jobs[1], ['alpha.test.ts']),
+ matrix.replace(' 0 fail', ' 1 fail'),
+ matrix.replace('1 passed, 0 failed', '0 passed, 1 failed'),
+ matrix.replace('1 passed, 0 failed', '0 passed, 0 failed'),
+ matrix.replace('phantom-redirect-engine-parity.test.ts', 'unknown.test.ts'),
+ matrix.replace('Ran 1 test across 1 file. [2.50s]', ''),
+ ]) expect(() => mineWeights(bad, 'e2e', { ...opts, expectedJobs: jobs })).toThrow();
+ expect(() => mineWeights(raw, 'e2e', { ...opts, expectedFiles: [...expectedFiles, 'test/alpha.test.ts'] })).toThrow('ambiguous');
+ expect(() => mineWeights(raw, 'e2e', { ...opts, expectedFiles: [...expectedFiles, 'test/e2e/missing.test.ts'] })).toThrow('missing source files');
+ expect(() => mineWeights(raw, 'e2e', { e2eProfile: 'full' })).toThrow('source corpus');
+ });
+});
+
describe("computeWeights", () => {
it("computes delta between consecutive file headers within a job", () => {
const events = parseLog(SAMPLE);
@@ -297,3 +338,62 @@ it('GitHub refresh verifies every eligible job before replacing the complete lan
expect(JSON.parse(readFileSync(meta, 'utf8'))).toMatchObject({ commit: 'fixture-commit', measuredFiles: 2, totalFiles: 2, mergeExisting: false });
} finally { rmSync(dir, { recursive: true, force: true }); }
});
+
+it('full-profile CLI pins source, attempt and job provenance and preserves both outputs on refused evidence', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-mine-full-'));
+ try {
+ const repo = join(import.meta.dir, '../..');
+ const sha = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: repo, encoding: 'utf8' }).stdout.trim();
+ const corpus = sourceE2ECorpus(sha);
+ expect(corpus).toContain('test/phantom-redirect-engine-parity.test.ts');
+ expect(() => sourceE2ECorpus('wrong-commit')).toThrow('source SHA');
+ const bin = join(dir, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'gh'), `#!/bin/sh
+case "$*" in
+ "run view 123 --json attempt,conclusion,headSha,jobs") cat "$FIXTURE_GH_INFO" ;;
+ "run view 123 --attempt 2 --job 456 --log") cat "$FIXTURE_GH_LOG" ;;
+ *) exit 2 ;;
+esac
+`, { mode: 0o755 });
+ const infoPath = join(dir, 'run.json');
+ const logPath = join(dir, 'full.log');
+ const out = join(dir, 'weights.json');
+ const meta = join(dir, 'weights.metadata.json');
+ const info = { attempt: 2, conclusion: 'success', headSha: sha, jobs: [{ name: 'coverage-full-e2e', databaseId: 456, conclusion: 'success' }] };
+ const line = (text: string) => `coverage-full-e2e\tstep\t2026-09-24T06:00:00.000Z ${text}\n`;
+ const files = corpus.map(path => line(`=== ${path.split('/').at(-1)} ===`) + line(' 0 fail') + line('Ran 1 test across 1 file. [1.00ms]'));
+ const complete = files.join('') + line(`Files: ${files.length} total, ${files.length} passed, 0 failed`);
+ const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: infoPath, FIXTURE_GH_LOG: logPath };
+ const base = [join(repo, 'scripts/mine-shard-weights.ts'), '--lane', 'e2e', '--e2e-profile', 'full', '--out', out];
+ const run = (args = ['--run', '123']) => spawnSync(process.execPath, [...base, ...args], { env, encoding: 'utf8' });
+ writeFileSync(out, '{"keep":123}\n');
+ writeFileSync(meta, '{"prior":true}\n');
+ for (const [metadata, log] of [
+ [{ ...info, conclusion: 'failure' }, complete],
+ [{ ...info, headSha: 'other-commit' }, complete],
+ [{ ...info, attempt: undefined }, complete],
+ [{ ...info, jobs: [{ ...info.jobs[0], conclusion: 'cancelled' }] }, complete],
+ [{ ...info, jobs: [{ ...info.jobs[0], databaseId: undefined }] }, complete],
+ [info, files.slice(1).join('') + line(`Files: ${files.length - 1} total, ${files.length - 1} passed, 0 failed`)],
+ [info, complete.replace(' 0 fail', ' 1 fail')],
+ ] as const) {
+ writeFileSync(infoPath, JSON.stringify(metadata));
+ writeFileSync(logPath, log);
+ expect(run().status).not.toBe(0);
+ expect(readFileSync(out, 'utf8')).toBe('{"keep":123}\n');
+ expect(readFileSync(meta, 'utf8')).toBe('{"prior":true}\n');
+ }
+ expect(run(['--from-file', logPath]).status).not.toBe(0);
+ writeFileSync(infoPath, JSON.stringify(info));
+ writeFileSync(logPath, complete);
+ const result = run();
+ expect(result.status, result.stderr).toBe(0);
+ expect(Object.keys(JSON.parse(readFileSync(out, 'utf8'))).sort()).toEqual([...corpus].sort());
+ expect(JSON.parse(readFileSync(meta, 'utf8'))).toMatchObject({
+ lane: 'e2e', e2eProfile: 'full', run: '123', commit: sha, attempt: 2, source: 'github',
+ jobs: [{ name: 'coverage-full-e2e', databaseId: 456 }], measuredFiles: corpus.length, totalFiles: corpus.length, mergeExisting: false,
+ logSha256: expect.stringMatching(/^[0-9a-f]{64}$/), corpusSha256: expect.stringMatching(/^[0-9a-f]{64}$/),
+ });
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+}, 30000);
diff --git a/test/scripts/nightly-e2e.test.ts b/test/scripts/nightly-e2e.test.ts
new file mode 100644
index 0000000000..1126e413f1
--- /dev/null
+++ b/test/scripts/nightly-e2e.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { safeLoad } from 'js-yaml';
+import { verifyNightlyE2E } from '../../scripts/verify-nightly-e2e.ts';
+
+const repo = join(import.meta.dir, '../..');
+const fullProfile = "github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)";
+const expected = Array.from({ length: 4 }, (_, i) => [`test/e2e/fixture-${i}-a.test.ts`, `test/e2e/fixture-${i}-b.test.ts`]);
+function fixture(fn: (root: string) => void, partitions = expected) {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-nightly-e2e-'));
+ try {
+ for (let index = 0; index < partitions.length; index++) {
+ const dir = join(root, `coverage-full-e2e-${index + 1}`);
+ mkdirSync(dir);
+ writeFileSync(join(dir, 'lane-manifest.json'), JSON.stringify({ lane: `e2e-${index + 1}`, sha: 'fixture-sha', lcovCount: 2, complete: true }));
+ writeFileSync(join(dir, 'executed-files.txt'), partitions[index].join('\n') + '\n');
+ }
+ fn(root);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+}
+
+describe('nightly E2E execution receipts', () => {
+ test('accepts exactly four complete disjoint partitions of the same commit', () => fixture(root => {
+ expect(() => verifyNightlyE2E(root, expected, 'fixture-sha')).not.toThrow();
+ }));
+ test.each(['missing artifact', 'missing manifest', 'missing receipt', 'wrong SHA', 'incomplete', 'duplicate lane', 'wrong lane', 'missing file', 'duplicate file', 'extra file', 'overlapping partitions', 'malformed manifest'])('%s fails closed', kind => fixture(root => {
+ const dir = join(root, 'coverage-full-e2e-4');
+ const manifest = join(dir, 'lane-manifest.json');
+ const receipt = join(dir, 'executed-files.txt');
+ const data = JSON.parse(readFileSync(manifest, 'utf8'));
+ if (kind === 'missing artifact') rmSync(dir, { recursive: true });
+ if (kind === 'missing manifest') rmSync(manifest);
+ if (kind === 'missing receipt') rmSync(receipt);
+ if (kind === 'wrong SHA') writeFileSync(manifest, JSON.stringify({ ...data, sha: 'stale-commit' }));
+ if (kind === 'incomplete') writeFileSync(manifest, JSON.stringify({ ...data, complete: false }));
+ if (kind === 'duplicate lane') writeFileSync(manifest, JSON.stringify({ ...data, lane: 'e2e-1' }));
+ if (kind === 'wrong lane') writeFileSync(manifest, JSON.stringify({ ...data, lane: 'e2e-5' }));
+ if (kind === 'missing file') writeFileSync(receipt, expected[3][0] + '\n');
+ if (kind === 'duplicate file') writeFileSync(receipt, [expected[3][0], expected[3][0]].join('\n'));
+ if (kind === 'extra file') writeFileSync(receipt, [...expected[3], 'test/e2e/extra.test.ts'].join('\n'));
+ if (kind === 'overlapping partitions') writeFileSync(receipt, expected[0].join('\n'));
+ if (kind === 'malformed manifest') writeFileSync(manifest, '{');
+ expect(() => verifyNightlyE2E(root, expected, 'fixture-sha')).toThrow();
+ }));
+ test('an absent artifact directory cannot claim complete execution', () => fixture(root => {
+ expect(() => verifyNightlyE2E(join(root, 'absent'), expected, 'fixture-sha')).toThrow();
+ }));
+});
+
+describe('nightly E2E scheduling', () => {
+ test('full-profile shell flags use environment data instead of expression interpolation', () => {
+ const workflow = safeLoad(readFileSync(join(repo, '.github/workflows/e2e.yml'), 'utf8')) as any;
+ const steps = [
+ workflow.jobs['prepare-e2e'].steps.find((step: any) => step.id === 'select'),
+ workflow.jobs['e2e-status'].steps.find((step: any) => step.name === 'Aggregate result'),
+ ];
+ for (const step of steps) {
+ expect(step.env?.FULL_CORPUS).toBe('${{ ' + fullProfile + ' }}');
+ expect(step.run).toContain('if [ "$FULL_CORPUS" = "true" ]; then');
+ expect(step.run).not.toContain('${{ ' + fullProfile + ' }}');
+ }
+ });
+ test('the four actual runner partitions cover the complete default discovery exactly once', () => {
+ const discover = (shard: string) => {
+ const result = spawnSync('bash', ['scripts/run-e2e.sh', '--dry-run-list'], {
+ cwd: repo, encoding: 'utf8', env: { ...process.env, SHARD: shard, COVERAGE_DIR: '' },
+ });
+ expect(result.status, result.stderr).toBe(0);
+ return result.stdout.trim().split('\n').filter(Boolean);
+ };
+ const corpus = [...readdirSync(join(repo, 'test/e2e')).filter(file => file.endsWith('.test.ts')).map(file => `test/e2e/${file}`), 'test/phantom-redirect-engine-parity.test.ts'].sort();
+ expect(discover('').sort()).toEqual(corpus);
+ const partitions = [1, 2, 3, 4].map(n => discover(`${n}/4`));
+ expect(partitions.every(files => files.length > 0)).toBe(true);
+ expect(partitions.flat().sort()).toEqual(corpus);
+ expect(new Set(partitions.flat()).size).toBe(corpus.length);
+ fixture(root => {
+ const verify = () => spawnSync(process.execPath, ['scripts/verify-nightly-e2e.ts', root, '4', 'fixture-sha'], {
+ cwd: repo, encoding: 'utf8', env: { ...process.env, SHARD: '3/4', COVERAGE_DIR: join(root, 'unused') },
+ });
+ const complete = verify();
+ expect(complete.status, complete.stderr).toBe(0);
+ expect(complete.stdout).toContain(`all ${corpus.length} files accounted for across 4 isolated workers`);
+ rmSync(join(root, 'coverage-full-e2e-4/executed-files.txt'));
+ expect(verify().status).toBe(1);
+ }, partitions);
+ });
+ test('nightly jobs preserve job-local Postgres, independent artifacts, always-reporting and required execution evidence', () => {
+ const workflow = safeLoad(readFileSync(join(repo, '.github/workflows/e2e.yml'), 'utf8')) as any;
+ const job = workflow.jobs['coverage-full-e2e'];
+ expect(job.if).toBe(fullProfile);
+ expect(job.strategy).toEqual({ 'fail-fast': false, matrix: { shard: [1, 2, 3, 4] } });
+ expect(job.services.postgres.image).toBe('pgvector/pgvector:pg16');
+ const run = job.steps.find((step: any) => step.run === 'bash scripts/run-e2e.sh');
+ expect(run.env.SHARD).toBe('${{ matrix.shard }}/4');
+ expect(run.env.DATABASE_URL).toContain('/gbrain_test');
+ expect(run.env.COVERAGE_DIR).toBe('${{ runner.temp }}/coverage');
+ const bootstrap = job.steps.find((step: any) => step.name === 'Bootstrap isolated E2E schema');
+ expect(job.steps.indexOf(bootstrap)).toBeLessThan(job.steps.indexOf(run));
+ expect(bootstrap.env).toEqual({ DATABASE_URL: run.env.DATABASE_URL, GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1', GBRAIN_MODEL_DISCOVERY: 'off' });
+ fixture(root => {
+ const home = join(root, 'home');
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ const sentinel = join(home, '.gbrain/config.json');
+ writeFileSync(sentinel, '{"doNotTouch":true}\n');
+ const result = spawnSync('bash', ['-e', '-c', bootstrap.run], {
+ cwd: repo, encoding: 'utf8', timeout: 10000,
+ env: { ...process.env, ...bootstrap.env, RUNNER_TEMP: root, HOME: home, GBRAIN_HOME: home,
+ DATABASE_URL: 'postgresql://localhost:1/production', GBRAIN_DATABASE_URL: 'postgresql://localhost:1/also_production',
+ GBRAIN_E2E_ALLOW_DB: 'production', OPENAI_API_KEY: 'synthetic-bootstrap-canary' },
+ });
+ expect(result.status).not.toBe(0);
+ expect(result.stderr).toContain('does not look like a test database');
+ expect(result.stderr).not.toContain('synthetic-bootstrap-canary');
+ expect(readFileSync(sentinel, 'utf8')).toBe('{"doNotTouch":true}\n');
+ expect(readdirSync(root).some(name => name.startsWith('e2e-bootstrap.'))).toBe(false);
+ });
+ for (const [stepName, artifact] of [['Upload coverage', 'coverage-full-e2e-'], ['Upload execution receipt', 'e2e-full-execution-']]) {
+ const step = job.steps.find((step: any) => step.name === stepName);
+ expect(step.if).toBe('always()');
+ expect(step.with.name).toBe(artifact + '${{ matrix.shard }}');
+ }
+ const report = workflow.jobs['coverage-full-report'];
+ expect(report.needs).toContain('coverage-full-e2e');
+ expect(report.if).toBe(`always() && (${fullProfile})`);
+ const merge = report.steps.find((step: any) => step.name === 'Merge full corpus').run;
+ expect(merge).toContain('scripts/verify-nightly-e2e.ts "$RUNNER_TEMP/coverage-artifacts" 4 "$GITHUB_SHA"');
+ expect(merge).toContain(',e2e-1,e2e-2,e2e-3,e2e-4');
+ fixture(root => {
+ const bin = join(root, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'bun'), '#!/bin/sh\necho COVERAGE_CALLED\n', { mode: 0o755 });
+ for (const result of ['success', 'failure', 'cancelled', 'skipped', '']) {
+ const script = merge.replace('${{ needs.coverage-full-e2e.result }}', result);
+ const run = spawnSync('bash', ['-e', '-c', script], {
+ encoding: 'utf8', env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, RUNNER_TEMP: root, GITHUB_SHA: 'fixture-sha' },
+ });
+ expect(run.status, run.stderr).toBe(result === 'success' ? 0 : 1);
+ expect(run.stdout.includes('COVERAGE_CALLED')).toBe(result === 'success');
+ }
+ });
+ const status = workflow.jobs['e2e-status'];
+ expect(status.if).toBe('always()');
+ expect(status.needs).toContain('coverage-full-e2e');
+ expect(status.needs).not.toContain('coverage-full-report');
+ const validate = status.steps.find((step: any) => step.name === 'Verify complete nightly execution');
+ expect(validate.if).toBe(fullProfile);
+ expect(validate.run).toBe('bun scripts/verify-nightly-e2e.ts "$RUNNER_TEMP/e2e-execution" 4 "$GITHUB_SHA"');
+ });
+ test('manual full corpus is opt-in and uses the complete scheduled profile without cancelling ordinary runs', () => {
+ const workflow = safeLoad(readFileSync(join(repo, '.github/workflows/e2e.yml'), 'utf8')) as any;
+ expect(workflow.on.workflow_dispatch.inputs.full_corpus).toMatchObject({ type: 'boolean', default: false });
+ for (const name of ['coverage-full-unit', 'coverage-full-serial', 'coverage-full-slow', 'coverage-full-e2e']) expect(workflow.jobs[name].if).toBe(fullProfile);
+ for (const step of workflow.jobs['e2e-status'].steps.slice(1)) expect(step.if).toBe(fullProfile);
+ const selection = workflow.jobs['prepare-e2e'].steps.find((step: any) => step.id === 'select');
+ const select = selection.run;
+ expect(selection.env.FULL_CORPUS).toBe('${{ ' + fullProfile + ' }}');
+ const group = workflow.concurrency.group;
+ expect(group).toBe("${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event_name == 'workflow_dispatch' && inputs.full_corpus && '-full-corpus' || '' }}");
+ for (const [event, enabled, expected] of [
+ ['pull_request', false, false], ['pull_request', true, false], ['push', true, false],
+ ['workflow_dispatch', false, false], ['workflow_dispatch', true, true], ['schedule', false, true],
+ ] as const) {
+ const condition = fullProfile.replaceAll('github.event_name', JSON.stringify(event)).replaceAll('inputs.full_corpus', String(enabled));
+ expect(new Function(`return (${condition})`)()).toBe(expected);
+ fixture(root => {
+ const bin = join(root, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'git'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ writeFileSync(join(bin, 'bun'), `#!/bin/sh
+case "$*" in
+ "scripts/select-e2e.ts") echo test/e2e/selected.test.ts ;;
+ "scripts/e2e-matrix.ts prepare") cat > "$RUNNER_TEMP/received-selection"; echo '{}' ;;
+ *) exit 2 ;;
+esac
+`, { mode: 0o755 });
+ const run = spawnSync('bash', ['-e', '-c', select], {
+ encoding: 'utf8', env: { ...process.env, FULL_CORPUS: String(expected), PATH: `${bin}:${process.env.PATH}`, RUNNER_TEMP: root, GITHUB_OUTPUT: join(root, 'outputs') },
+ });
+ expect(run.status, run.stderr).toBe(0);
+ expect(readFileSync(join(root, 'received-selection'), 'utf8')).toBe(expected ? '' : 'test/e2e/selected.test.ts\n');
+ });
+ }
+ });
+});
diff --git a/test/symbol-resolver-projection-race.test.ts b/test/symbol-resolver-projection-race.test.ts
index 4cb8f1aa87..3950745e3d 100644
--- a/test/symbol-resolver-projection-race.test.ts
+++ b/test/symbol-resolver-projection-race.test.ts
@@ -7,6 +7,9 @@ import { installPageProjection, preparePageProjection, readProjectionSnapshot }
import { resolveSymbolEdgesIncremental } from '../src/core/chunkers/symbol-resolver.ts';
import { resolveCodeReadiness } from '../src/core/code-graph-readiness.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
function deferred() {
let resolve!: () => void;
@@ -36,10 +39,12 @@ describe('symbol resolver and projection replacement serialization', () => {
let pg: Awaited<ReturnType<typeof isolatedPersistencePostgres>> | undefined;
beforeAll(async () => {
- lite = new PGLiteEngine();
- await lite.connect({});
- await lite.initSchema();
- if (process.env.DATABASE_URL) pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ if (backends.includes('pglite')) {
+ lite = new PGLiteEngine();
+ await lite.connect({});
+ await lite.initSchema();
+ }
+ if (backends.includes('postgres')) pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
}, 120_000);
afterAll(async () => {
@@ -178,16 +183,16 @@ describe('symbol resolver and projection replacement serialization', () => {
}
}
- test('PGlite queues actual projection replacement behind the paused resolver transaction', async () => {
+ test.skipIf(!backends.includes('pglite'))('PGlite queues actual projection replacement behind the paused resolver transaction', async () => {
await replacementRace(lite);
}, 60_000);
- test.skipIf(!process.env.DATABASE_URL)('Postgres reports the actual publisher waiting on the resolver page guard', async () => {
+ test.skipIf(!backends.includes('postgres'))('Postgres reports the actual publisher waiting on the resolver page guard', async () => {
await replacementRace(pg!.engine);
}, 60_000);
test('a failure after edge updates rolls metadata and watermarks back together', async () => {
- for (const engine of [lite, ...(pg ? [pg.engine] : [])]) {
+ for (const engine of [...(lite ? [lite] : []), ...(pg ? [pg.engine] : [])]) {
const sourceId = `resolver-rollback-${engine.kind}`;
await seed(engine, sourceId);
const beforeEdges = await edges(engine, sourceId);
@@ -216,7 +221,7 @@ describe('symbol resolver and projection replacement serialization', () => {
}, 60_000);
test('candidates are revalidated under the page guard before any metadata or watermark update', async () => {
- for (const engine of [lite, ...(pg ? [pg.engine] : [])]) {
+ for (const engine of [...(lite ? [lite] : []), ...(pg ? [pg.engine] : [])]) {
for (const change of ['watermark', 'projection', 'archive', 'slug'] as const) {
const sourceId = `resolver-stale-${engine.kind}-${change}`;
const { snapshot } = await seed(engine, sourceId);
diff --git a/test/test-backends.test.ts b/test/test-backends.test.ts
new file mode 100644
index 0000000000..6fec79a41e
--- /dev/null
+++ b/test/test-backends.test.ts
@@ -0,0 +1,39 @@
+import { expect, test } from 'bun:test';
+import { registerPostgresTests, requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const databaseUrl = 'postgresql://localhost/gbrain_test';
+
+test('direct invocation keeps local-only and opt-in dual-engine execution', () => {
+ expect(testBackends({})).toEqual(['pglite']);
+ expect(testBackends({ DATABASE_URL: databaseUrl })).toEqual(['pglite', 'postgres']);
+});
+
+test('explicit PostgreSQL selection cannot silently fall back, skip, or use an unsafe database', () => {
+ expect(testBackends({ GBRAIN_TEST_BACKEND: 'postgres', DATABASE_URL: databaseUrl })).toEqual(['postgres']);
+ expect(() => testBackends({ GBRAIN_TEST_BACKEND: 'postgres' })).toThrow('requires DATABASE_URL');
+ expect(() => testBackends({ GBRAIN_TEST_BACKEND: 'postgres', DATABASE_URL: 'postgresql://localhost/operator' })).toThrow('does not look like a test database');
+ expect(() => testBackends({ GBRAIN_TEST_BACKEND: 'unknown' })).toThrow('Unknown GBRAIN_TEST_BACKEND');
+ expect(() => requirePostgresTestDatabase({})).toThrow('refusing to skip');
+});
+
+test('E2E registration captures PostgreSQL only and restores the caller after all loaders', async () => {
+ await withEnv({ DATABASE_URL: databaseUrl, GBRAIN_TEST_BACKEND: undefined }, async () => {
+ const captured: string[][] = [];
+ await registerPostgresTests(async () => { captured.push(testBackends()); }, async () => { captured.push(testBackends()); });
+ expect(captured).toEqual([['postgres'], ['postgres']]);
+ expect(testBackends()).toEqual(['pglite', 'postgres']);
+ });
+});
+
+test('failed and unavailable E2E registration cannot leak a backend override or import a fallback', async () => {
+ await withEnv({ DATABASE_URL: databaseUrl, GBRAIN_TEST_BACKEND: undefined }, async () => {
+ await expect(registerPostgresTests(async () => { throw new Error('loader fixture failure'); })).rejects.toThrow('loader fixture failure');
+ expect(process.env.GBRAIN_TEST_BACKEND).toBeUndefined();
+ });
+ await withEnv({ DATABASE_URL: undefined, GBRAIN_TEST_BACKEND: undefined }, async () => {
+ let imported = false;
+ await expect(registerPostgresTests(async () => { imported = true; })).rejects.toThrow('requires DATABASE_URL');
+ expect(imported).toBe(false);
+ });
+});