The pyramid (4 layers + evals)
1. Unit — packages/schema, packages/core pure logic
Pure functions only: schema validation, supersession resolution, commitment FSM transitions, retrieval fusion scoring. No DB, no mocks of the DB — if a test wants to mock packages/db, it’s an integration test in disguise; move it down a layer.
2. Integration — the workhorse layer
- Runs against real Postgres + pgvector — never a mock, never SQLite. Locally: the same
docker-compose.ymlPostgres as self-host (test database). CI: each selectedintegration (...)shard gets its own disposablepgvector/pgvector:pg18service container, aggregated bytest, with the heavy DB package split intodb-structure,db-search,db-auth, anddb-memoryslices. This path requires no hosted-database credentials and works for fork PRs. - Two isolation strategies, used deliberately (
packages/db/test/integration/helpers.ts):- Savepoint pattern —
withTestTransaction()for tests that own their SQL: rolled back, fast, parallel-safe. - Truncate-based cleanup —
resetDomainTables()for suites exercising the realwithTenant()path:withTenantcommits on its own pool, so cross-connection visibility makes savepoints inapplicable there. Honest trade: those suites serialize on cleanup. Because these global TRUNCATEs are not isolated across packages on a shared database (--fileParallelism=falseonly serializes within a package), the roottest:integrationscript pins turbo--concurrency=1for local/single-database runs. CI keeps package-internal serialization and gives each selected shard its own Postgres service container. DB sub-shards therefore cannot collide with one another.
- Savepoint pattern —
- RLS tests run as the runtime role, not the owner role (owner bypasses RLS — a green isolation test as superuser proves nothing). The test harness provisions roles via the same
scripts/provision-roles.sqlas production. - Real concurrency is constructed, never timed (
packages/db/test/integration/concurrency.ts): a test transaction takes the conflicting lock and parks before commit (holdOpen), the production call starts on its own pooled runtime-role connection and provably blocks on that lock (waitForLockWaitpollspg_locks, scoped to the test database and to the holder’s pid, with a bounded timeout), and only then is the holder released and committed state asserted. No sleep picks a winner.session-contention.int.test.tspins the session-locking claims (one epoch bump per resurrection, attach vs close, the single-open count at commit, attach vs erasure lock order, heartbeat vs erasure) this way. - Mandatory suites that exist from the start (
packages/db/test/integration/):- Tenant isolation: user A writes, user B queries — across every query path including edges, facts, commitments, proposals. Mirrors the eval slice but as fast deterministic tests.
withTenantdiscipline: concurrent pooled connections cannot leakapp.user_id.- Append-only enforcement: UPDATE/DELETE on
memory_events/audit_logfails at the grant level; no DELETE anywhere in the memory domain. - Migration round-trip: fresh DB → all migrations → structure parity (tables, policies+NULLIF, FSM trigger, HNSW index, SECURITY DEFINER resolvers).
- HNSW parity: pgvector vs the eval gate’s exact cosine on the real golden-set embeddings — the bridge between the eval gate’s upper bound and what production serves. Two-regime (see Data model & RLS): natural plan asserted index-driven (selective tenants get btree+exact — correct), plus a forced-HNSW arm (
enable_sort=off,hnsw.iterative_scan) with EXPLAIN-asserted index use; both ≥ 0.95 overlap.
packages/core/test/integration/provenance-chain.int.test.ts)
uses eval/fixtures/provenance-synthetic.json to mirror product writes across two tenants.
It requires exact chain recall and precision (1.0), zero foreign ids, and truncation for
a 28-version chain. Expected labels map to stored identities without reading producer
links or provenance output. An explicit caller-predicate probe works independently of
RLS. Mutation checks remove that predicate or a producer link and must fail. This slice
runs in integration (core), including fixture-only changes, and blocks through test;
it does not add a database dependency to eval-gate.
3. Contract — MCP and REST surfaces
- Spin up the Express app in-process through the SDK v2 dual-era handler; drive both legacy and
2026-07-28clients through the official MCP client SDK (not hand-rolled JSON-RPC) so version negotiation, transport, auth bridging, and structured-output semantics are actually exercised. - Every tool: happy path + auth-missing + cross-tenant + output-schema validation (the response must parse against the tool’s declared
outputSchema— enforced as plain tests, not a bespoke CI job). - REST mirrors: generated OpenAPI is diffed in CI; a contract change shows up in the PR.
4. E2E — minimal by design
The managed dashboard lives in3ngram-platform. Browser QA drives the changed
surface and records its evidence in the PR. Neither repository currently has a
Playwright workflow; do not treat a staging merge as proof of a browser pass.
Consequence-loop coverage (#322)
These synthetic scenarios run in the existing suites and CI shards. They need no paid model calls or separate end-to-end framework. Paths below are relative to each package’stest/ directory; integration files end in .int.test.ts.
Integration shards are path-gated by
.github/workflows/ci.yml. The closer’s
deterministic tests prove ID containment and write guards. Whether a model falsely
classifies a briefed commitment as completed remains model-quality work under
#166/#224; these tests do not claim to prove that judgment correct.
LLM policy in tests
- Automated layers 1–3 never call a real model.
packages/llmships aFakeGateway(deterministic embeddings via seeded hash → vector; canned completions per operation key; canneddecide()answers per operation, with a fixed low default probability so a test that forgets one fails closed). Tests assert on our logic, not model behavior. Browser QA against a shared deployment uses that environment’s configured gateway; isolated QA can inject the fake. - Model behavior is the eval harness’s job — that’s the separation: tests prove the machine is wired right; evals prove the memory is good. A PR can’t compensate for a golden-set regression with passing unit tests, and vice versa.
- Recorded-fixture mode (capture a real gateway response once, replay) is allowed for extraction-shaped logic, stored under
__fixtures__/, refreshed deliberately — never auto-recorded in CI.
Test health policy
- No skipped tests on
main.it.skip/todofails the lint step. A test that can’t pass is either fixed in the PR or deleted with a linked issue — a pile of dormant markers is how a suite rots. - No flake tolerance: a test that fails intermittently is quarantined by deletion + issue, not retry-until-green. CI has no retry-on-failure config.
- Coverage is observed, not gated. Vitest coverage reported on PRs for review judgment; no threshold ratchet (thresholds breed assertion-free tests). The mandatory-suite list above is the real floor.
- Speed budgets are enforced: unit
<30s, integration<3min, contract<2min, totalci.yml<10minwall. A PR that blows the budget fixes it or splits the suite — slow CI is how the job sprawl started. - Tests-with-the-change: every behavior PR carries its tests; there is no “test backfill” epic, ever.