Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.51.4.0 perf: speed up persistence and test verification (#5174)

Garry Tan3e92670ddf46
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 9aa4897a01..f4b1d6fa25 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.51.3.0",
+ "version": "0.51.4.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 bfb1599b46..65cda24a45 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.51.3.0",
+ "version": "0.51.4.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/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index df782cb08d..972b90579a 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.51.3.0 -->
+<!-- gbrain-runbook-stamp: 0.51.4.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 10059efecd..916cb64a84 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,74 @@
All notable changes to GBrain will be documented in this file.
+## [0.51.4.0] - 2026-09-21
+
+**Queued writes move sooner, and contributor checks spend less time repeating work.**
+
+When several agents are waiting to save, finishing one write now wakes the next
+instead of waiting for an idle timer. Busy folders and retryable failures still
+back off normally. Shutdown still waits for active work, and every accepted write
+keeps the same durable receipt and recovery checks.
+
+Unchanged managed folders also stop replacing the same ownership-refusal record
+with two different descriptions on every refresh. Their files remain protected,
+including old paths after a move and sources without a worktree binding.
+
+Upgrade with `gbrain upgrade`; no configuration change or data migration is needed.
+These changes do not relax filesystem synchronization, lower stress-test counts,
+or move required checks out of pull-request CI.
+
+### The measured numbers
+
+| Workload | Before | After |
+| --- | ---: | ---: |
+| 256 disk-backed writes, same Linux machine and Bun 1.3.14 | 89.0s | 42.4s |
+| Privacy guard, same four-worker verify setup | 25.45s | 0.47–0.63s |
+| Full verify CPU time | 112.40s | 84.84–85.63s |
+| Repeated typecheck with native compiler state | 33.26s cold | 7.37–7.46s warm |
+| Full verify with warm compiler state | 36.19s cold | 18.12–18.40s warm |
+| 100 full PGLite fixture resets, median of three | 8.244s | 3.897s |
+| 12 reset-heavy files, four processes, median of two | 44.256s | 35.484s |
+
+The 256-write measurement is an iteration benchmark, not the full persistence
+gate. Full verification still requires 1,000 schedules, eight process-kill
+boundaries and 10,000 writes per engine. Cold type checking still takes about
+33 seconds on the measured machine; native incremental analysis speeds repeated
+local checks without caching test outcomes or restoring prior CI results.
+
+### Itemized changes
+
+- Canonical-write completion wakes the consumer promptly, including when the
+ wake-up arrives during another tick. Blocked attempts retain polling backoff.
+- Managed-root refresh chooses a stable bound record for each path while retaining
+ distinct fallback and moved paths. Unchanged registrations avoid redundant
+ durable replacements.
+
+### For contributors
+
+- Privacy and test-isolation guards batch fresh candidate scans before running
+ their existing detailed rules. Scanner errors fail closed; diagnostics,
+ allowlists and rule boundaries are unchanged.
+- Scheduler, root-registration and guard regressions cover the performance paths
+ alongside shutdown, retry, path confinement and scanner failure behavior.
+- Full PGLite fixture resets retain table/index storage rather than recreating it
+ for every test. Owned sequences, default-source reseeding, trigger behavior,
+ infrastructure state and fresh logical brain identities remain covered; unusual
+ schemas use the original truncation path. Exact aggregate storage accounting
+ also triggers truncation above 8 MiB, bounding retained fixture data.
+- `bun run typecheck` keeps native compiler analysis in ignored
+ `node_modules/.cache/gbrain-typecheck.tsbuildinfo`. Source/configuration/dependency
+ invalidation and repeated error reporting are regression-tested.
+- Every code-running local CI mode runs the authoritative `bun run verify` gate
+ once before tests, plus the existing test-timeout guard. It no longer maintains a smaller
+ parallel list of checks that can drift from hosted CI. The doc-only diff fast
+ path remains secrets-scan-only.
+- The Docker admin build has its own dependency and output volumes, keeping Linux
+ packages and root-owned generated files out of the host checkout.
+- A rename-recovery fixture now asserts that Git actually classified its change
+ as a rename. Terminated fixture lines keep it above Git's similarity threshold;
+ all original rejection, retry and recovery assertions remain in place.
+
## [0.51.3.0] - 2026-09-20
**Use your brain from every device, app and cloud agent you have, without moving it off your own computer.** `gbrain mcp expose` publishes `gbrain serve --http` on your Tailscale tailnet with HTTPS, keeps it running as a user service, and hands you the grant command for each client. Tailnet-only by default; `--funnel` is the explicit opt-in for agents that run in a vendor's cloud (Grok Bot, Muse, ChatGPT, Claude.ai / Cowork, Perplexity). ngrok and cloud hosts stay documented as alternatives, and Grok Bot and Muse now recommend this shape first.
diff --git a/TODOS.md b/TODOS.md
index 5a741085e3..ac9a80a5fe 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -4712,7 +4712,6 @@ PR bisectable.
- [ ] **v0.42+: refactor `runRoutingEval` to take `ResolverEntry[]` directly** instead of `resolverContent: string`. Cleaner shape than synthesizing markdown then re-parsing it. Cascades through 9+ test files that depend on the string-content API. Defer until the next big refactor of the routing-eval module so the test-file churn lands with that wave.
- [ ] **v0.42+: replace regex-based `parseSkillFrontmatter` with a real YAML parser** (js-yaml is already a transitive dep via gray-matter). Codex finding #4 from /plan-eng-review: the regex in `src/core/skill-frontmatter.ts` assumes YAML semantics it can't enforce (e.g. multi-line scalars, escaped quotes). For our current uniform-shape skills (all use `- "quoted"` block form), it works. Swap when a skill ships a YAML construct the regex misparses, or proactively for defense-in-depth.
- [ ] **v0.42+: unify `parseSkillFrontmatter` (skill-frontmatter.ts) and MECE's `extractTriggers` (check-resolvable.ts:216)** into a single parser. Codex finding #5: two parsers, drift surface. Both extract `triggers:` arrays the same way today, so the drift is bounded — but every future change to one needs to be mirrored in the other. Consolidate when either needs to diverge.
-- [ ] **v0.42+: `bun run ci:local` should run `bun run verify`** (codex finding #10 from /plan-eng-review). Today ci:local runs guards + typecheck + unit + E2E but NOT verify, so the new `check:resolver` gate (and others added to verify) don't fire in local pre-push. Bigger conversation about local vs CI scope — defer as a separate UX decision after measuring how often verify-only failures land in CI.
- [ ] **v0.42+: remove the deprecated `install/` skill directory entirely.** It has no SKILL.md (just a deprecation note pointing at setup/) and is correctly skipped by `loadSkillTriggerIndex`. Removing the directory cleans up the bundled skill tree. Orthogonal to #1451; small follow-up.
- [ ] **v0.42+: extend `entriesToResolverContent` to escape backticks in trigger strings.** Today only pipes are escaped, because no real bundled trigger contains a backtick. If a future skill ships a trigger like ``` `code` ``` the markdown-table row would mangle. Add a single regex replace if a real case appears.
@@ -7252,6 +7251,10 @@ keeping both skills' triggers intact for chaining.
## Completed
+- [x] **v0.42+: `bun run ci:local` should run `bun run verify`** (codex finding #10 from /plan-eng-review).
+ **Original task:** ci:local ran guards + typecheck + unit + E2E but NOT verify, so the new `check:resolver` gate (and others added to verify) did not fire in local pre-push. Deferred as a separate UX decision after measuring how often verify-only failures landed in CI.
+ **Completed:** v0.51.4.0 (2026-09-21). Every code-running local CI mode now runs the authoritative `bun run verify` once before tests, plus the test-timeout guard. The doc-only `--diff` fast path remains secrets-scan-only; `test/scripts/ci-local-rendering.test.ts` checks phase order in all four mode combinations and rejects failed stages.
+
### ~~Report returned import failures accurately in the human summary~~
**Completed:** v0.50.0.0 (2026-09-10)
diff --git a/VERSION b/VERSION
index 73951c63bd..467f040540 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.51.3.0
+0.51.4.0
diff --git a/docker-compose.ci.yml b/docker-compose.ci.yml
index ccac7c3a9e..cb1f257a84 100644
--- a/docker-compose.ci.yml
+++ b/docker-compose.ci.yml
@@ -154,6 +154,8 @@ services:
# Without this, container `bun install` stomps host node_modules and
# subsequent `bun test` on host fails with binary-incompat errors.
- gbrain-ci-node-modules:/app/node_modules
+ - gbrain-ci-admin-node-modules:/app/admin/node_modules
+ - gbrain-ci-admin-dist:/app/admin/dist
# Warm install cache across runs.
- gbrain-ci-bun-cache:/root/.bun/install/cache
@@ -163,4 +165,6 @@ volumes:
gbrain-ci-pg-data-3:
gbrain-ci-pg-data-4:
gbrain-ci-node-modules:
+ gbrain-ci-admin-node-modules:
+ gbrain-ci-admin-dist:
gbrain-ci-bun-cache:
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index e1872fe8c4..1efba324b8 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -41,7 +41,10 @@ Three ways to actually gate on types:
1. `bun run verify` — runs the shell guard checks (privacy, jsonb, source-id,
progress-to-stdout, …) plus `bun run typecheck` in parallel
(`scripts/run-verify-parallel.sh`). Use this mid-branch.
-2. `bun run typecheck` — `tsc --noEmit` standalone. Fast (~5s on this repo).
+2. `bun run typecheck` — standalone TypeScript checking with native incremental
+ analysis in ignored `node_modules/.cache/gbrain-typecheck.tsbuildinfo`. Cold
+ checks still analyze the whole project; repeated checks reuse compiler state
+ while retaining input invalidation and diagnostics. See [Testing](TESTING.md).
3. `bun run ci:local` — the full local CI gate from Path A.
The trap is: writing a new test, running `bun test test/foo.test.ts`,
diff --git a/docs/TESTING.md b/docs/TESTING.md
index ee179b372c..1653212468 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -46,6 +46,18 @@ array in `scripts/run-verify-parallel.sh` is the single execution list
`check:no-legacy-getconnection`). The guard REGISTRY is `scripts/guards-manifest.tsv` (see "Guard registry and
self-test" below).
+`bun run typecheck` uses TypeScript's native incremental analysis in
+`node_modules/.cache/gbrain-typecheck.tsbuildinfo`. Every invocation still runs
+the compiler; source, root-file, configuration and dependency changes invalidate
+the affected analysis, and cached diagnostics remain failures. The cache is local
+and ignored by Git; CI does not restore prior typecheck results.
+
+The local Docker runner isolates root and admin `node_modules`, plus the generated
+admin bundle, in named volumes. Admin build dependencies, Vite's generated cache
+and build output stay inside container volumes instead of replacing host files
+or leaving root-owned directories behind. `ci:local --clean` removes these volumes
+too; build the admin app on the host when updating its committed bundle.
+
### Native writer locks
`bun test test/native-lock.test.ts test/scripts/native-lock-prebuilds.test.ts`
@@ -87,6 +99,15 @@ nested transaction confinement and the Postgres resident-stop barrier.
### Durable persistence schedules and process crashes
+`test/persistence-consumer-scheduling.test.ts` pins completion wake-ups,
+including a wake-up arriving during an active tick, without lowering the idle
+poll interval. Per-root deadlines preserve blocked/retryable backoff even while
+another root keeps committing; expired deadlines permit retries. Shutdown drains
+active preparation without starting another request.
+`test/persistence-root-refresh.test.ts` checks that unchanged root registrations
+do not replace their durable files while unbound, moved and original bound paths
+all remain fenced.
+
`test/persistence-chaos.slow.test.ts` and `test/e2e/persistence-chaos.test.ts`
execute real journal/coordinator schedules and eight SIGKILL publication
boundaries, followed by a small multi-process soak. The Postgres test creates
@@ -215,6 +236,11 @@ successful test results are never cached.
### Guard registry and self-test
+The privacy and test-isolation guards use `scripts/lib/guard-candidates.sh` to
+scan fresh file contents in bounded batches before applying their detailed
+per-file rules. They do not cache passing results. Candidate scanner failures
+fail the guard, and matching files retain the same allowlists and diagnostics.
+
`scripts/guards-manifest.tsv` is THE single registry of `scripts/check-*`
guards (currently 48), each classified `scanner` (greps/parses repo sources —
must eventually carry fixtures), `buildfresh`, or `repostate` (build/freshness
@@ -516,7 +542,13 @@ beforeEach(async () => {
});
```
-Why this exact shape: `beforeAll` creates a single engine per file (PGLite WASM cold-start + initSchema is ~20s); `beforeEach` truncates user data via `resetPgliteState` ("two orders of magnitude faster" than fresh-engine-per-test); `afterAll` disconnects so the engine doesn't leak across file boundaries within a shard process.
+Why this exact shape: `beforeAll` creates a single engine per file (PGLite WASM cold-start + initSchema is ~20s); `beforeEach` clears user data via `resetPgliteState`; `afterAll` disconnects so the engine doesn't leak across file boundaries within a shard process. Ordinary resets atomically delete rows with cleanup-only trigger suppression and restart owned sequences, retaining table/index storage. The helper restores trigger behavior before reseeding and falls back to `TRUNCATE CASCADE` for schemas whose triggers, rules, inheritance, external foreign keys or privileges require its original semantics. Schema/generation infrastructure survives, and each reset rotates the logical brain identity.
+
+Every full reset measures aggregate target-table storage, including indexes and
+TOAST, with `pg_total_relation_size`. Above 8 MiB it uses the same atomic TRUNCATE
+path to reclaim storage; no reset counter or stale size estimate is retained.
+The helper regression suite checks repeated TOAST-heavy resets, cleanup and
+sequence parity, restored triggers and foreign-key enforcement.
#### `withEnv` pattern (R1 fix)
@@ -564,7 +596,7 @@ consumer suites:
not replay migrations on a later `initSchema()` after a version rewind —
rewind-arc tests need the cold path (see `test/bootstrap.test.ts`).
- `reset-pglite.ts#resetPgliteStateNarrow(engine, tables)` — explicit-table
- truncate for hot loops (the full reset truncates the whole catalog). The
+ truncate for hot loops (the full reset clears the whole catalog). The
table list is REQUIRED — a default would silently under-truncate.
- `git-fixture.ts` — `makeGitFixture(dir)`: build-once git repo +
`reset()`/`commitAll()` between tests, replacing per-test `git init` chains.
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index b00bf096b8..20024ac7fe 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -8,6 +8,8 @@ lives in `CHANGELOG.md` + `git log` / `git blame`, NOT here. Do not append
per-release `**vX.Y.Z:**` narration — CI enforces this
(`scripts/check-key-files-current-state.sh`).
+- `src/core/persistence/consumer.ts` — bounded resident canonical-write consumer. Terminal completion preempts a pending idle poll; wake-ups requested during an active tick are retained until it finishes. Blocked/retryable attempts retain normal polling, and stop drains active work without scheduling its successor. `test/persistence-consumer-scheduling.test.ts` pins these scheduling boundaries. Managed-root refresh selects one stable record per path, preferring a bound worktree over a fallback source path, so repeated refreshes do not replace the same durable record twice; distinct unbound and moved paths remain fenced (`test/persistence-root-refresh.test.ts`).
+
- `scripts/persistence/{performance,read-workload,read-metrics,read-admission}.ts` — required median-of-three read latency gate around the existing heavy query corpus. Both engines use public page mutation handlers; every read/write error invalidates the sample, the union of actual in-flight mutation intervals must cover at least 90% of reads, and loaded p99 may exceed idle p99 by at most 50%. Isolated child homes/databases, runtime/source manifests and queue/admission/commit/RSS/recovery/pool metrics keep evidence reproducible. The original `tests/heavy/read_latency_under_sync.sh` invokes this runner. The stable engine proxy observes resolved top-level admission transactions during warmup and measurement, excludes nested savepoints, and requires one prior admission per committed UUID. `test/persistence-performance.test.ts` guards idle-gap detection and invalid-sample/median gate semantics; `test/persistence-admission-observer.test.ts` proves actual rollback and publication boundaries on both engines.
- `scripts/persistence/{matrix,matrix-cases}.ts` — required real Postgres/PgBouncer deployment matrix: 24 combinations of RLS policy enforcement, ordinary pool sizes 1/2/3 and shared/separate direct capacity. Production bulk reservations must leave short claims, renewals and reads usable; size-one publication stays queued. Fresh fixtures also verify successor manifests, stale owners, retained native lock exclusion during root replacement and source deletion/recreation. `test/e2e/persistence-runtime-matrix.test.ts` runs it when configured and refuses missing required pooler fixtures. Supplied URLs pass the test-database guard before its CREATE/DROP control connection uses the maintenance database; fresh case databases isolate it from other E2E shards.
@@ -529,7 +531,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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/build-pglite-snapshot.ts` — `bun run build:pglite-snapshot [--profile legacy|default]` bakes post-schema PGLite snapshots. Legacy (the default) matches the unit preload; default follows canonical CLI embedding defaults. Profiles have disjoint tar/version/lock paths and CI cache keys. Version sidecars retain schema-byte hash, dims and model. The builder requires PID/token lock ownership, only reclaims confirmed dead owners using its retirement protocol, times out on live/unknown locks, and publishes temporary files via atomic rename with the version last. Normal release and crash recovery retain the same nonempty owner tombstone so a delayed observer cannot move a replacement lock. `scripts/lib/test-env.sh` exposes `ensure_pglite_snapshot` (legacy primary env) and `ensure_default_pglite_snapshot` (absolute auxiliary `GBRAIN_TEST_DEFAULT_SNAPSHOT`); failure visibly falls back to cold init. `GBRAIN_NO_SNAPSHOT=1` clears both and survives preloads. BrainBench overrides only CLI children, including run-all, to the default path. The production loader's per-process memoization, schema/shape refusal and in-memory-only gate remain authoritative and unchanged. Keep `computeSnapshotSchemaHash` and every CI profile cache key aligned with imported SQL helpers, including grants, withdrawals, page state and persistence schemas. Tests: `test/scripts/build-pglite-snapshot.test.ts`, `test/snapshot-shape-guard.test.ts`, BrainBench CLI E2E and operator preload tests.
-- `docker-compose.ci.yml` + `scripts/ci-local.sh` — Local CI gate. `bun run ci:local` spins up four `pgvector/pgvector:pg16` services (postgres-1..4) + `oven/bun:${GBRAIN_CI_BUN_TAG:-1.3.13}` with named volumes (`gbrain-ci-pg-data-{1..4}`, `gbrain-ci-node-modules`, `gbrain-ci-bun-cache`), runs gitleaks on host, smoke-tests `scripts/run-e2e.sh` argv handling, runs guards (including explicit Bun test timeout coverage) + typecheck, then the Tier 1 default: 4-shard parallel unit + E2E (`xargs -P4`, one Postgres per shard; unit phase keeps `DATABASE_URL` unset). `--no-shard` falls back to the legacy unsharded sequential flow (debug aid); `--diff` runs the diff-aware selector unsharded. Also runs a `pgbouncer` service (`edoburu/pgbouncer`, `POOL_MODE: transaction`, `AUTH_TYPE: plain` — pg16 stores SCRAM verifiers, so the userlist must hold the plaintext password; `IGNORE_STARTUP_PARAMETERS` whitelists gbrain's `statement_timeout`/`idle_in_transaction_session_timeout` startup params the way the Supabase pooler does) fronting postgres-1 on host port `GBRAIN_CI_PGBOUNCER_PORT` (default 6543); every E2E invocation exports `GBRAIN_PGBOUNCER_URL` (pooled; dedicated `gbrain_pgbouncer_test` database so it never races the `gbrain_test` TRUNCATE fixtures) + `GBRAIN_PGBOUNCER_DIRECT_URL`, consumed by `test/e2e/pgbouncer-teardown.test.ts` — which reproduces the transaction-mode teardown failure in the local gate. `--no-pull` skips upstream pulls; `--clean` nukes named volumes. Postgres host port defaults to 5434; override with `GBRAIN_CI_PG_PORT=NNNN`. Stronger gate than PR CI's 2-file Tier 1 set.
+- `docker-compose.ci.yml` + `scripts/ci-local.sh` — Local CI gate. `bun run ci:local` spins up four `pgvector/pgvector:pg16` services (postgres-1..4) + `oven/bun:${GBRAIN_CI_BUN_TAG:-1.3.13}` with named volumes (`gbrain-ci-pg-data-{1..4}`, `gbrain-ci-node-modules`, `gbrain-ci-admin-node-modules`, `gbrain-ci-admin-dist`, `gbrain-ci-bun-cache`), runs gitleaks on host, smoke-tests `scripts/run-e2e.sh` argv handling, runs the authoritative `bun run verify` once plus the explicit Bun test-timeout guard, then the complete serial and slow lanes before 4-shard parallel unit + E2E (`xargs -P4`, one Postgres per shard; unit phase keeps `DATABASE_URL` unset). `--no-shard` runs unit/E2E sequentially (debug aid); `--diff` narrows E2E selection without changing the chosen shard mode. The doc-only `--diff` fast path runs only the host secrets scans. Also runs a `pgbouncer` service (`edoburu/pgbouncer`, `POOL_MODE: transaction`, `AUTH_TYPE: plain` — pg16 stores SCRAM verifiers, so the userlist must hold the plaintext password; `IGNORE_STARTUP_PARAMETERS` whitelists gbrain's `statement_timeout`/`idle_in_transaction_session_timeout` startup params the way the Supabase pooler does) fronting postgres-1 on host port `GBRAIN_CI_PGBOUNCER_PORT` (default 6543); every E2E invocation exports `GBRAIN_PGBOUNCER_URL` (pooled; dedicated `gbrain_pgbouncer_test` database so it never races the `gbrain_test` TRUNCATE fixtures) + `GBRAIN_PGBOUNCER_DIRECT_URL`, consumed by `test/e2e/pgbouncer-teardown.test.ts` — which reproduces the transaction-mode teardown failure in the local gate. `--no-pull` skips upstream pulls; `--clean` nukes named volumes. Postgres host port defaults to 5434; override with `GBRAIN_CI_PG_PORT=NNNN`. Full persistence and native runtime matrices run separately; see `docs/TESTING.md`.
- `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/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.
- `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.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 563e99afc9..b3bda8f3e1 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.51.3.0",
+ "version": "0.51.4.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index c7ce27973c..9b1930897c 100644
--- a/package.json
+++ b/package.json
@@ -76,7 +76,7 @@
"ci:local": "bash scripts/ci-local.sh",
"ci:local:diff": "bash scripts/ci-local.sh --diff",
"ci:select-e2e": "bun run scripts/select-e2e.ts",
- "typecheck": "tsc --noEmit",
+ "typecheck": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/gbrain-typecheck.tsbuildinfo",
"check:jsonb": "bash scripts/check-jsonb-pattern.sh",
"check:search-path": "bash scripts/check-search-path.sh",
"check:no-double-retry": "bash scripts/check-no-double-retry.sh",
@@ -177,7 +177,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.51.3.0",
+ "version": "0.51.4.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 2c017f0799..0860a73ee6 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.51.3.0",
+ "version": "0.51.4.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 — 20 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 dc25ca4027..3d370aed69 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.51.3.0",
+ "version": "0.51.4.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 — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 3a926982ae..33a85ef39f 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.51.3.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.51.4.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 ee7a3eee87..894a223811 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.51.3.0",
+ "version": "0.51.4.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 — 19 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 aaa3585783..6b21642886 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.51.3.0",
+ "version": "0.51.4.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 — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index dd4d4c013c..b8aac9a775 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.51.3.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.51.4.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 e391c5d39e..78290ae214 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.51.3.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.51.4.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/check-privacy.sh b/scripts/check-privacy.sh
index 4adcd5d55f..17b85687e4 100755
--- a/scripts/check-privacy.sh
+++ b/scripts/check-privacy.sh
@@ -25,6 +25,8 @@
set -euo pipefail
+. "$(dirname "$0")/lib/guard-candidates.sh"
+
BANNED_NAME='wintermute'
# v0.25.1 (codex T7): additional patterns from wintermute-specific filesystem
# layouts that would leak private fork context if they slipped through a port.
@@ -90,6 +92,12 @@ if [ -z "$FILES" ]; then
exit 0
fi
+SCAN_PATTERNS=(-iF -e "$BANNED_NAME")
+for path in "${BANNED_PATHS[@]}"; do
+ SCAN_PATTERNS+=(-e "$path")
+done
+FILES="$(guard_candidates "${SCAN_PATTERNS[@]}" <<< "$FILES")"
+
# Allow-list: files in which the banned name is legitimate.
# Meta-rule docs (define the rule itself), auto-generated LLM indexes,
# historical upgrade guides, and the test that enforces the rule
diff --git a/scripts/check-test-isolation.sh b/scripts/check-test-isolation.sh
index c016fecbe7..694e30fe35 100755
--- a/scripts/check-test-isolation.sh
+++ b/scripts/check-test-isolation.sh
@@ -37,6 +37,8 @@
set -euo pipefail
+. "$(dirname "$0")/lib/guard-candidates.sh"
+
ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
cd "$ROOT"
@@ -85,6 +87,11 @@ FILE_LIST="$(find "$TARGET_DIR" $EXTRA_DIRS -name '*.test.ts' \
-not -path "*/e2e/*" \
-type f 2>/dev/null | sort)"
+ENV_MUTATION_PATTERN='process\.env\.[A-Za-z_][A-Za-z_0-9]*[[:space:]]*=[^=]|process\.env\[[^]]+\][[:space:]]*=[^=]|delete[[:space:]]+process\.env\.|delete[[:space:]]+process\.env\[|Object\.assign[[:space:]]*\([[:space:]]*process\.env|Reflect\.set[[:space:]]*\([[:space:]]*process\.env'
+MODULE_MOCK_PATTERN='mock\.module[[:space:]]*\('
+ENGINE_PATTERN='new PGLiteEngine[[:space:]]*\('
+CANDIDATES="$(guard_candidates -E -e "$ENV_MUTATION_PATTERN" -e "$MODULE_MOCK_PATTERN" -e "$ENGINE_PATTERN" <<< "$FILE_LIST")"
+
violations=0
file_count=0
@@ -105,20 +112,27 @@ emit_violation() {
while IFS= read -r f; do
[ -z "$f" ] && continue
file_count=$((file_count + 1))
+ case $'\n'"$CANDIDATES"$'\n' in
+ *$'\n'"$f"$'\n'*) ;;
+ *) continue ;;
+ esac
+ if is_allowlisted "$f"; then
+ continue
+ fi
# R1: env mutations.
- env_lines=$(grep -nE 'process\.env\.[A-Za-z_][A-Za-z_0-9]*[[:space:]]*=[^=]|process\.env\[[^]]+\][[:space:]]*=[^=]|delete[[:space:]]+process\.env\.|delete[[:space:]]+process\.env\[|Object\.assign[[:space:]]*\([[:space:]]*process\.env|Reflect\.set[[:space:]]*\([[:space:]]*process\.env' "$f" 2>/dev/null || true)
+ env_lines=$(grep -nE "$ENV_MUTATION_PATTERN" "$f" 2>/dev/null || true)
if [ -n "$env_lines" ]; then
emit_violation "$f" "R1" "process.env mutation; use withEnv() or rename to *.serial.test.ts" "$env_lines"
fi
# R2: mock.module() anywhere.
- mock_lines=$(grep -nE 'mock\.module[[:space:]]*\(' "$f" 2>/dev/null || true)
+ mock_lines=$(grep -nE "$MODULE_MOCK_PATTERN" "$f" 2>/dev/null || true)
if [ -n "$mock_lines" ]; then
emit_violation "$f" "R2" "mock.module() leaks across files in the shard process; rename to *.serial.test.ts" "$mock_lines"
fi
# R3: PGLiteEngine outside ~50 lines after a beforeAll(.
- if grep -qE 'new PGLiteEngine[[:space:]]*\(' "$f" 2>/dev/null; then
+ if grep -qE "$ENGINE_PATTERN" "$f" 2>/dev/null; then
bad=$(awk '
BEGIN { last_before_all = -1000 }
/beforeAll[[:space:]]*\(/ { last_before_all = NR }
@@ -134,7 +148,7 @@ while IFS= read -r f; do
fi
# R4: PGLiteEngine creation requires afterAll{disconnect}.
- if grep -qE 'new PGLiteEngine[[:space:]]*\(' "$f" 2>/dev/null; then
+ if grep -qE "$ENGINE_PATTERN" "$f" 2>/dev/null; then
if ! grep -qE 'afterAll[[:space:]]*\(' "$f" 2>/dev/null \
|| ! grep -qE '\.disconnect[[:space:]]*\(' "$f" 2>/dev/null; then
emit_violation "$f" "R4" "creates PGLiteEngine but missing afterAll(() => engine.disconnect()); engine leaks across files in the shard process" ""
diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh
index 3419e4cafe..33496fc867 100755
--- a/scripts/ci-local.sh
+++ b/scripts/ci-local.sh
@@ -191,12 +191,8 @@ echo "[ci-local] Smoke OK ($SMOKE_NO_ARGS files no-arg, 1 single-arg, ${SHARD_TO
if [ "$NO_SHARD" = "1" ]; then
if [ "$DIFF" = "1" ]; then
RUN_PHASES_CMD='echo "[runner] guards + typecheck"
-bash scripts/check-jsonb-pattern.sh
bash scripts/check-bun-test-timeout.sh
-bash scripts/check-progress-to-stdout.sh
-bash scripts/check-trailing-newline.sh
-bash scripts/check-wasm-embedded.sh
-bun run typecheck
+bun run verify
echo "[runner] serial tests (DATABASE_URL unset)"
env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun run test:serial
echo "[runner] slow tests (DATABASE_URL unset)"
@@ -218,12 +214,8 @@ else
fi'
else
RUN_PHASES_CMD='echo "[runner] guards + typecheck"
-bash scripts/check-jsonb-pattern.sh
bash scripts/check-bun-test-timeout.sh
-bash scripts/check-progress-to-stdout.sh
-bash scripts/check-trailing-newline.sh
-bash scripts/check-wasm-embedded.sh
-bun run typecheck
+bun run verify
echo "[runner] serial tests (DATABASE_URL unset)"
env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun run test:serial
echo "[runner] slow tests (DATABASE_URL unset)"
@@ -253,12 +245,8 @@ fi'
DIFF_E2E_PREP='> /tmp/e2e-selected.txt'
fi
RUN_PHASES_CMD="echo \"[runner] guards + typecheck (run once before sharding)\"
-bash scripts/check-jsonb-pattern.sh
bash scripts/check-bun-test-timeout.sh
-bash scripts/check-progress-to-stdout.sh
-bash scripts/check-trailing-newline.sh
-bash scripts/check-wasm-embedded.sh
-bun run typecheck
+bun run verify
echo \"[runner] serial tests (DATABASE_URL unset)\"
env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun run test:serial
echo \"[runner] slow tests (DATABASE_URL unset)\"
diff --git a/scripts/lib/guard-candidates.sh b/scripts/lib/guard-candidates.sh
new file mode 100644
index 0000000000..116cc717e7
--- /dev/null
+++ b/scripts/lib/guard-candidates.sh
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+
+guard_candidates() {
+ local file rc batch_count=0
+ local -a batch=()
+ while IFS= read -r file; do
+ [ -n "$file" ] && [ -f "$file" ] || continue
+ batch+=("$file")
+ batch_count=$((batch_count + 1))
+ if [ "$batch_count" -ge 128 ]; then
+ if grep -l "$@" -- "${batch[@]}"; then
+ :
+ else
+ rc=$?
+ [ "$rc" -eq 1 ] || return "$rc"
+ fi
+ batch=()
+ batch_count=0
+ fi
+ done
+ if [ "$batch_count" -gt 0 ]; then
+ if grep -l "$@" -- "${batch[@]}"; then
+ :
+ else
+ rc=$?
+ [ "$rc" -eq 1 ] || return "$rc"
+ fi
+ fi
+}
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index ef18c0d0bf..1d47957a25 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -14,10 +14,11 @@ export class PersistenceConsumer {
private stopping = false;
private timer: ReturnType<typeof setTimeout> | undefined;
private tickPromise: Promise<void> | undefined;
+ private wakeRequested = false;
private active = new Set<Promise<void>>();
private activeRoots = new Set<string>();
private foregroundCounts = new Map<string, number>();
- private recoveryRetryAfter = new Map<string, number>();
+ private rootRetryAfter = new Map<string, number>();
private projectionWorker: Promise<unknown> | undefined;
private effectsWorker: Promise<void> | undefined;
private topologyWorker: Promise<unknown> | undefined;
@@ -32,13 +33,19 @@ export class PersistenceConsumer {
}
start(): void { this.stopping = false; this.abort = new AbortController(); this.schedule(0); }
private schedule(ms: number): void {
- if (this.stopping || this.timer) return;
+ if (this.stopping) return;
+ if (ms === 0 && this.tickPromise) { this.wakeRequested = true; return; }
+ if (this.timer && ms !== 0) return;
+ if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(() => { this.timer = undefined; void this.tick().finally(() => this.schedule(this.opts.pollMs ?? 250)); }, ms);
this.timer.unref?.();
}
async tick(): Promise<void> {
if (this.tickPromise) return this.tickPromise;
- this.tickPromise = this.doTick().catch(error => { this.report(error); }).finally(() => { this.tickPromise = undefined; });
+ this.tickPromise = this.doTick().catch(error => { this.report(error); }).finally(() => {
+ this.tickPromise = undefined;
+ if (this.wakeRequested) { this.wakeRequested = false; this.schedule(0); }
+ });
return this.tickPromise;
}
private async doTick(): Promise<void> {
@@ -60,8 +67,8 @@ export class PersistenceConsumer {
// Recover only our owner roots. Kernel exclusion, not elapsed heartbeat,
// proves that a previous process can no longer be publishing this root.
const now = Date.now();
- for (const [root, retryAt] of this.recoveryRetryAfter) if (retryAt <= now) this.recoveryRetryAfter.delete(root);
- const excluded = [...this.activeRoots, ...this.recoveryRetryAfter.keys()];
+ for (const [root, retryAt] of this.rootRetryAfter) if (retryAt <= now) this.rootRetryAfter.delete(root);
+ const excluded = [...this.activeRoots, ...this.rootRetryAfter.keys()];
const recovery = await this.engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
JOIN persistence_worktrees w ON w.id=r.worktree_id
WHERE w.owner_host_id=$1::uuid AND r.recovery IS NOT NULL AND NOT(r.worktree_id::text=ANY($2::text[]))
@@ -73,13 +80,13 @@ export class PersistenceConsumer {
// Always skip at least the next scheduled poll for an unresolved root.
// This preserves its FIFO head while allowing the next root into LIMIT 16.
const delay = Math.max(1000, (this.opts.pollMs ?? 250) * 2);
- this.recoveryRetryAfter.set(root, Date.now() + delay);
+ this.rootRetryAfter.set(root, Date.now() + delay);
try {
const recovered = await recoverPublication(this.engine, row.id, this.hostId);
- if (!recovered.recovery) this.recoveryRetryAfter.delete(root);
- else if (recovered.blocked_reason === 'unexpected_file_bytes') this.recoveryRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));
+ if (!recovered.recovery) this.rootRetryAfter.delete(root);
+ else if (recovered.blocked_reason === 'unexpected_file_bytes') this.rootRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));
} catch (error) {
- this.recoveryRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));
+ this.rootRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));
this.report(error);
}
}
@@ -92,7 +99,7 @@ export class PersistenceConsumer {
return;
}
const concurrency = this.opts.concurrency ?? 2;
- const attemptedRoots = new Set(this.activeRoots);
+ const attemptedRoots = new Set([...this.activeRoots, ...this.rootRetryAfter.keys()]);
while (!this.stopping && this.active.size < concurrency) {
const row = await claimNextWrite(this.engine, this.hostId, 30_000, [...attemptedRoots]);
if (!row) break;
@@ -100,8 +107,10 @@ export class PersistenceConsumer {
attemptedRoots.add(key);
if (this.activeRoots.has(key)) { await releaseUnpublishedClaim(this.engine, row, 'writer_busy'); break; }
this.activeRoots.add(key);
- const task = this.execute(row).catch(error => this.report(error)).finally(() => {
- this.active.delete(task); this.activeRoots.delete(key); this.schedule(0);
+ let progressed = false;
+ const task = this.execute(row).then(result => { progressed = result; }).catch(error => this.report(error)).finally(() => {
+ if (!progressed) this.rootRetryAfter.set(key, Date.now() + (this.opts.pollMs ?? 250));
+ this.active.delete(task); this.activeRoots.delete(key); this.schedule(progressed ? 0 : this.opts.pollMs ?? 250);
});
this.active.add(task);
}
@@ -117,7 +126,7 @@ export class PersistenceConsumer {
if (this.opts.onError) this.opts.onError(error);
else process.stderr.write('[persistence] Consumer paused after a storage error; inspect writer status.\n');
}
- private async execute(row: WriteRequest): Promise<void> {
+ private async execute(row: WriteRequest): Promise<boolean> {
let renewing: Promise<unknown> | undefined;
let claimLive = true;
let closed = false;
@@ -129,15 +138,18 @@ export class PersistenceConsumer {
interval.unref?.();
try {
const prepared = await this.prepare(this.engine, row, this.config);
- if (!claimLive || this.stopping) { await releaseUnpublishedClaim(this.engine, row, 'consumer_stopping'); return; }
+ if (!claimLive || this.stopping) { await releaseUnpublishedClaim(this.engine, row, 'consumer_stopping'); return false; }
const done = await publishMutation(this.engine, row, prepared, this.hostId);
if (done.state === 'committed' && row.worktree_id && !String(row.intent?.kind).startsWith('managed_sync_')) {
this.foregroundCounts.set(row.worktree_id, this.foregroundCompletions(row.worktree_id) + 1);
}
+ return isTerminal(done);
} catch (error) {
const current = await getWriteRequestById(this.engine, row.id);
- if (current && !isTerminal(current) && current.execution_token === row.execution_token && !current.recovery) await finishUnpublishedFailure(this.engine, current, error);
- else throw error;
+ if (current && !isTerminal(current) && current.execution_token === row.execution_token && !current.recovery) {
+ return isTerminal(await finishUnpublishedFailure(this.engine, current, error));
+ }
+ throw error;
} finally { closed = true; clearInterval(interval); await renewing; }
}
/** Mandatory barrier: engine.close must be sequenced AFTER this promise. */
diff --git a/src/core/persistence/filesystem-guard.ts b/src/core/persistence/filesystem-guard.ts
index 331fce4c54..0ded6a9aaa 100644
--- a/src/core/persistence/filesystem-guard.ts
+++ b/src/core/persistence/filesystem-guard.ts
@@ -24,9 +24,11 @@ function encloses(root: string, path: string): boolean {
export async function refreshManagedFilesystemRoots(engine: SqlEngine, databasePath = datastorePaths.get(engine)): Promise<void> {
const [brain] = await engine.executeRaw<{ brain_id: string; enabled: boolean }>('SELECT brain_id,enabled FROM persistence_brain WHERE singleton=1');
if (!brain) return;
- const roots = brain.enabled ? await engine.executeRaw<ManagedRootRecord>(`SELECT h.local_path,s.source_id,s.source_incarnation,s.worktree_id,s.topology_generation
+ const roots = brain.enabled ? await engine.executeRaw<ManagedRootRecord>(`SELECT DISTINCT ON (local_path) * FROM (
+ SELECT h.local_path,s.source_id,s.source_incarnation,s.worktree_id,s.topology_generation
FROM persistence_host_bindings h JOIN persistence_source_bindings s ON s.worktree_id=h.worktree_id WHERE h.host_id=$1::uuid
- UNION SELECT local_path,id,incarnation,NULL,NULL FROM sources WHERE local_path IS NOT NULL`, [localHostId()]) : [];
+ UNION SELECT local_path,id,incarnation,NULL,NULL FROM sources WHERE local_path IS NOT NULL
+ ) roots ORDER BY local_path,worktree_id NULLS LAST,source_id,source_incarnation,topology_generation`, [localHostId()]) : [];
if (brain.enabled && databasePath) roots.push({ local_path: databasePath });
if (brain.enabled) recordManagedRoots(brain.brain_id, roots);
managedRoots.set(brain.brain_id, new Set(roots.map(row => resolve(row.local_path))));
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 16adc1a16c..7dcd541966 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.51.3.0 -->
+<!-- gbrain-template-stamp: 0.51.4.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/helpers/reset-pglite.test.ts b/test/helpers/reset-pglite.test.ts
new file mode 100644
index 0000000000..4a748ea485
--- /dev/null
+++ b/test/helpers/reset-pglite.test.ts
@@ -0,0 +1,215 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { resetPgliteState } from './reset-pglite.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw('CREATE TABLE schema_version (version int)');
+ await engine.executeRaw('INSERT INTO schema_version VALUES (1)');
+ await engine.executeRaw('CREATE TABLE reset_fixture_parent (id serial PRIMARY KEY, value text)');
+ await engine.executeRaw('CREATE TABLE reset_fixture_child (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, parent_id int REFERENCES reset_fixture_parent)');
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+afterEach(async () => {
+ await engine.executeRaw('DROP EVENT TRIGGER IF EXISTS reset_fixture_event');
+ await engine.executeRaw('DROP RULE IF EXISTS reset_fixture_rule ON reset_fixture_parent');
+ await engine.executeRaw('DROP SCHEMA IF EXISTS reset_fixture_external CASCADE');
+ await engine.executeRaw('DROP TABLE IF EXISTS reset_fixture_added, "reset_fixture_quoted""name", reset_fixture_truncate_events CASCADE');
+ await engine.executeRaw('DROP SEQUENCE IF EXISTS reset_fixture_unowned');
+ await engine.executeRaw('DROP FUNCTION IF EXISTS reset_fixture_guard(), reset_fixture_event_guard() CASCADE');
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('resetPgliteState', () => {
+ test('reuses table and index storage during ordinary fixture cleanup', async () => {
+ await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('before')");
+ const sql = "SELECT oid, relfilenode FROM pg_class WHERE oid IN ('reset_fixture_parent'::regclass, 'reset_fixture_parent_pkey'::regclass) ORDER BY oid";
+ const storage = await engine.executeRaw(sql);
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw(sql)).toEqual(storage);
+ expect(await engine.executeRaw('SELECT * FROM reset_fixture_parent')).toEqual([]);
+ });
+
+ test('reclaims aggregate TOAST-heavy storage across repeated full resets', async () => {
+ await engine.executeRaw('CREATE TABLE reset_fixture_added (id serial PRIMARY KEY, value text)');
+ const [{ payload }] = await engine.executeRaw<{ payload: string }>(
+ "SELECT string_agg(md5(i::text), '') AS payload FROM generate_series(1, 4096) i",
+ );
+ expect(payload.length).toBe(128 * 1024);
+ let previous = 0;
+ let reclaimed = 0;
+ let peak = 0;
+ for (let i = 0; i < 100; i++) {
+ expect(await engine.executeRaw('INSERT INTO reset_fixture_parent (value) VALUES ($1) RETURNING id', [payload]))
+ .toEqual([{ id: 1 }]);
+ expect(await engine.executeRaw('INSERT INTO reset_fixture_added (value) VALUES ($1) RETURNING id', [payload]))
+ .toEqual([{ id: 1 }]);
+ await resetPgliteState(engine);
+ const [{ bytes }] = await engine.executeRaw<{ bytes: number }>(
+ "SELECT (pg_total_relation_size('reset_fixture_parent') + pg_total_relation_size('reset_fixture_added'))::bigint AS bytes",
+ );
+ const size = Number(bytes);
+ if (size < previous) reclaimed++;
+ peak = Math.max(peak, size);
+ previous = size;
+ expect(size).toBeLessThan(8 * 1024 * 1024);
+ expect(await engine.executeRaw('SELECT count(*)::int AS n FROM reset_fixture_parent UNION ALL SELECT count(*)::int AS n FROM reset_fixture_added'))
+ .toEqual([{ n: 0 }, { n: 0 }]);
+ }
+ expect(peak).toBeGreaterThan(1024 * 1024);
+ expect(reclaimed).toBeGreaterThanOrEqual(3);
+ expect(await engine.executeRaw("SELECT current_setting('session_replication_role') AS role")).toEqual([{ role: 'origin' }]);
+ await expect(engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (999)')).rejects.toThrow('foreign key');
+ }, 60_000);
+
+ test('clears every public table, including foreign-key cycles, and restores the default source', async () => {
+ await engine.executeRaw('ALTER TABLE reset_fixture_parent ADD COLUMN child_id int REFERENCES reset_fixture_child');
+ try {
+ await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('parent')");
+ await engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (1)');
+ await engine.executeRaw('UPDATE reset_fixture_parent SET child_id = 1');
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('extra', 'Extra')");
+ await engine.putPage('reset-fixture/page', { type: 'note', title: 'Fixture', compiled_truth: 'body', timeline: '' });
+ await engine.setConfig('reset-fixture', 'present');
+ await resetPgliteState(engine);
+ const tables = await engine.executeRaw<{ tablename: string }>("SELECT tablename FROM pg_tables WHERE schemaname='public'");
+ for (const { tablename } of tables) {
+ if (['schema_version', 'page_generation_clock', 'persistence_brain', 'sources'].includes(tablename)) continue;
+ const rows = await engine.executeRaw(`SELECT count(*)::int AS n FROM public."${tablename.replaceAll('"', '""')}"`);
+ expect(rows).toEqual([{ n: 0 }]);
+ }
+ expect(await engine.executeRaw('SELECT id, name, config, local_path FROM sources')).toEqual([
+ { id: 'default', name: 'default', config: { federated: true }, local_path: null },
+ ]);
+ } finally {
+ await engine.executeRaw('ALTER TABLE reset_fixture_parent DROP COLUMN child_id');
+ }
+ });
+
+ test('preserves schema and generation infrastructure but rotates the logical brain identity', async () => {
+ await engine.putPage('reset-fixture/generation', { type: 'note', title: 'Fixture', compiled_truth: 'body', timeline: '' });
+ const version = await engine.executeRaw('SELECT * FROM schema_version');
+ const clock = await engine.executeRaw('SELECT * FROM page_generation_clock');
+ const generation = await engine.executeRaw('SELECT last_value, is_called FROM page_generation_clock_seq');
+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled = true, activated_at = now() WHERE singleton = 1');
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw('SELECT * FROM schema_version')).toEqual(version);
+ expect(await engine.executeRaw('SELECT * FROM page_generation_clock')).toEqual(clock);
+ expect(await engine.executeRaw('SELECT last_value, is_called FROM page_generation_clock_seq')).toEqual(generation);
+ const [fresh] = await engine.executeRaw<{ brain_id: string; enabled: boolean; activated_at: string | null }>('SELECT brain_id, enabled, activated_at FROM persistence_brain');
+ expect(fresh.brain_id).not.toBe(brain.brain_id);
+ expect(fresh.enabled).toBe(false);
+ expect(fresh.activated_at).toBeNull();
+ });
+
+ test('restarts serial and identity sequences even when their tables are already empty', async () => {
+ await engine.executeRaw("SELECT nextval('reset_fixture_parent_id_seq') FROM generate_series(1, 3)");
+ await engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (NULL)');
+ await engine.executeRaw('DELETE FROM reset_fixture_child');
+ await engine.executeRaw('CREATE SEQUENCE reset_fixture_unowned START 7');
+ await engine.executeRaw("SELECT nextval('reset_fixture_unowned')");
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('fresh') RETURNING id")).toEqual([{ id: 1 }]);
+ expect(await engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (1) RETURNING id')).toEqual([{ id: 1 }]);
+ expect(await engine.executeRaw("SELECT nextval('reset_fixture_unowned') AS id")).toEqual([{ id: 8 }]);
+ });
+
+ test('discovers new tables and quoted identifiers on every reset and respects sequence starts', async () => {
+ await resetPgliteState(engine);
+ await engine.executeRaw('CREATE TABLE "reset_fixture_quoted""name" (id int GENERATED ALWAYS AS IDENTITY (START WITH 23), value text)');
+ await engine.executeRaw('CREATE TABLE reset_fixture_added (id serial PRIMARY KEY)');
+ await engine.executeRaw('INSERT INTO "reset_fixture_quoted""name" (value) VALUES (\'quoted\')');
+ await engine.executeRaw('INSERT INTO reset_fixture_added DEFAULT VALUES');
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw('SELECT * FROM "reset_fixture_quoted""name"')).toEqual([]);
+ expect(await engine.executeRaw('SELECT * FROM reset_fixture_added')).toEqual([]);
+ expect(await engine.executeRaw('INSERT INTO "reset_fixture_quoted""name" (value) VALUES (\'fresh\') RETURNING id')).toEqual([{ id: 23 }]);
+ expect(await engine.executeRaw('INSERT INTO reset_fixture_added DEFAULT VALUES RETURNING id')).toEqual([{ id: 1 }]);
+ });
+
+ test('bypasses ordinary DELETE triggers only during cleanup and restores FK enforcement', async () => {
+ await engine.executeRaw("CREATE FUNCTION reset_fixture_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'delete trigger is active'; END $$");
+ await engine.executeRaw('CREATE TRIGGER reset_fixture_delete BEFORE DELETE ON reset_fixture_parent FOR EACH ROW EXECUTE FUNCTION reset_fixture_guard()');
+ await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('before')");
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw("SELECT current_setting('session_replication_role') AS role")).toEqual([{ role: 'origin' }]);
+ await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('after')");
+ await expect(engine.executeRaw('DELETE FROM reset_fixture_parent')).rejects.toThrow('delete trigger is active');
+ await expect(engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (999)')).rejects.toThrow('foreign key');
+ });
+
+ test.each(['ALWAYS', 'REPLICA'])('retains TRUNCATE semantics with an ENABLE %s row trigger', async mode => {
+ await engine.executeRaw("CREATE FUNCTION reset_fixture_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'replica delete trigger'; END $$");
+ await engine.executeRaw('CREATE TRIGGER reset_fixture_delete BEFORE DELETE ON reset_fixture_parent FOR EACH ROW EXECUTE FUNCTION reset_fixture_guard()');
+ await engine.executeRaw(`ALTER TABLE reset_fixture_parent ENABLE ${mode} TRIGGER reset_fixture_delete`);
+ await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('before')");
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw('SELECT * FROM reset_fixture_parent')).toEqual([]);
+ });
+
+ test('fires custom TRUNCATE triggers instead of silently bypassing their contract', async () => {
+ await engine.executeRaw('CREATE TEMP TABLE reset_fixture_truncate_events (value text)');
+ await engine.executeRaw("CREATE FUNCTION reset_fixture_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN INSERT INTO reset_fixture_truncate_events VALUES ('truncated'); RETURN NULL; END $$");
+ await engine.executeRaw('CREATE TRIGGER reset_fixture_truncate AFTER TRUNCATE ON reset_fixture_parent EXECUTE FUNCTION reset_fixture_guard()');
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw('SELECT * FROM reset_fixture_truncate_events')).toEqual([{ value: 'truncated' }]);
+ });
+
+ test('cannot be bypassed by an ALWAYS-enabled DELETE rewrite rule', async () => {
+ await engine.executeRaw('CREATE RULE reset_fixture_rule AS ON DELETE TO reset_fixture_parent DO INSTEAD NOTHING');
+ await engine.executeRaw('ALTER TABLE reset_fixture_parent ENABLE ALWAYS RULE reset_fixture_rule');
+ await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('before')");
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw('SELECT * FROM reset_fixture_parent')).toEqual([]);
+ });
+
+ test('still cascades into a referencing table outside the public schema', async () => {
+ await engine.executeRaw('CREATE SCHEMA reset_fixture_external');
+ await engine.executeRaw('CREATE TABLE reset_fixture_external.child (id serial PRIMARY KEY, parent_id int REFERENCES reset_fixture_parent)');
+ await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('parent')");
+ await engine.executeRaw('INSERT INTO reset_fixture_external.child (parent_id) VALUES (1)');
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw('SELECT * FROM reset_fixture_external.child')).toEqual([]);
+ await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('fresh')");
+ expect(await engine.executeRaw('INSERT INTO reset_fixture_external.child (parent_id) VALUES (1) RETURNING id')).toEqual([{ id: 1 }]);
+ });
+
+ test('retains inherited-table truncation across schemas', async () => {
+ await engine.executeRaw('CREATE SCHEMA reset_fixture_external');
+ await engine.executeRaw('CREATE TABLE reset_fixture_external.child () INHERITS (reset_fixture_parent)');
+ await engine.executeRaw("INSERT INTO reset_fixture_external.child (value) VALUES ('inherited')");
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw('SELECT * FROM reset_fixture_external.child')).toEqual([]);
+ });
+
+ test('does not introduce ALTER SEQUENCE event-trigger effects', async () => {
+ await engine.executeRaw("CREATE FUNCTION reset_fixture_event_guard() RETURNS event_trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'sequence DDL observed'; END $$");
+ await engine.executeRaw("CREATE EVENT TRIGGER reset_fixture_event ON ddl_command_start WHEN TAG IN ('ALTER SEQUENCE') EXECUTE FUNCTION reset_fixture_event_guard()");
+ await resetPgliteState(engine);
+ expect(await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('fresh') RETURNING id")).toEqual([{ id: 1 }]);
+ });
+
+ test('rolls back failed reseeding and never leaves triggers disabled', async () => {
+ await engine.executeRaw("CREATE FUNCTION reset_fixture_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'reseed failed'; END $$");
+ await engine.executeRaw('CREATE TRIGGER reset_fixture_insert BEFORE INSERT ON sources FOR EACH ROW EXECUTE FUNCTION reset_fixture_guard()');
+ await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('survives')");
+ const brain = await engine.executeRaw('SELECT * FROM persistence_brain');
+ await expect(resetPgliteState(engine)).rejects.toThrow('reseed failed');
+ expect(await engine.executeRaw('SELECT value FROM reset_fixture_parent')).toEqual([{ value: 'survives' }]);
+ expect(await engine.executeRaw('SELECT * FROM persistence_brain')).toEqual(brain);
+ expect(await engine.executeRaw("SELECT current_setting('session_replication_role') AS role")).toEqual([{ role: 'origin' }]);
+ await expect(engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (999)')).rejects.toThrow('foreign key');
+ });
+});
diff --git a/test/helpers/reset-pglite.ts b/test/helpers/reset-pglite.ts
index 36a8b3a491..12cb859bc1 100644
--- a/test/helpers/reset-pglite.ts
+++ b/test/helpers/reset-pglite.ts
@@ -38,7 +38,7 @@
* engines leak across file boundaries within a shard process.
*
* Implementation:
- * 1. TRUNCATE every public table CASCADE, including `sources` (so tests
+ * 1. Empty every public table, including `sources` (so tests
* that register their own sources don't leak rows into the next test).
* 2. Re-seed the default source row that pages.source_id's DEFAULT FKs
* against. Without this, the next page insert would fail FK validation.
@@ -46,7 +46,14 @@
* initSchema() populates; wiping it would make migration helpers think
* the brain is on v0.
*
- * Identifier-quoted defensively against pathological table names.
+ * Cleanup bypasses row triggers, like TRUNCATE, and resets owned sequences.
+ * DELETE avoids recreating every empty table/index's storage on each test.
+ * Schemas with truncate/replica triggers or rules, inheritance, or external foreign
+ * keys retain TRUNCATE CASCADE semantics. Cleanup is one atomic statement;
+ * normal trigger behavior is restored before re-seeding or running tests.
+ * Aggregate table/index/TOAST storage over 8 MiB also uses TRUNCATE so deleted
+ * rows cannot accumulate unbounded storage across repeated fixture resets.
+ * Identifiers are quoted defensively against pathological table names.
*/
import type { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
@@ -60,26 +67,60 @@ const PRESERVE_TABLES = new Set(['schema_version', 'page_generation_clock', 'per
export async function resetPgliteState(engine: PGLiteEngine): Promise<void> {
await disposePersistenceConsumer(engine);
- const rows = await engine.executeRaw<{ tablename: string }>(
- `SELECT tablename FROM pg_tables WHERE schemaname='public'`,
- );
- const targets = rows
- .map(r => r.tablename)
- .filter(name => !PRESERVE_TABLES.has(name));
- if (targets.length === 0) return;
- const quoted = targets.map(t => `"${t.replace(/"/g, '""')}"`).join(', ');
- await engine.executeRaw(`TRUNCATE ${quoted} RESTART IDENTITY CASCADE`);
- // This fixture deleted every registration and permanent receipt. Give its new
- // logical brain a new identity so private credentials from the previous test
- // cannot masquerade as a revoked registration on restart.
- await engine.executeRaw('UPDATE persistence_brain SET brain_id=gen_random_uuid(),enabled=false,activated_at=NULL WHERE singleton=1');
- // Re-seed the default source row that initSchema() inserts. Mirrors the
- // INSERT in src/core/pglite-schema.ts so the FK target survives reset.
- await engine.executeRaw(
- `INSERT INTO sources (id, name, config)
- VALUES ('default', 'default', '{"federated": true}'::jsonb)
- ON CONFLICT (id) DO NOTHING`,
- );
+ await engine.executeRaw(`DO $reset$
+ DECLARE
+ tables regclass[];
+ targets text;
+ storage_bytes bigint;
+ target regclass;
+ sequence record;
+ original_role text := current_setting('session_replication_role');
+ BEGIN
+ SELECT array_agg(c.oid::regclass), string_agg(format('%I.%I', n.nspname, c.relname), ', '),
+ sum(pg_total_relation_size(c.oid))
+ INTO tables, targets, storage_bytes
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p')
+ AND c.relname NOT IN (${[...PRESERVE_TABLES].map(t => `'${t}'`).join(', ')});
+ IF targets IS NULL THEN RETURN; END IF;
+ IF storage_bytes > 8 * 1024 * 1024 OR EXISTS (
+ SELECT 1 FROM pg_trigger WHERE tgrelid = ANY(tables)
+ AND ((tgtype::int & 32) <> 0 OR tgenabled IN ('A', 'R'))
+ ) OR EXISTS (
+ SELECT 1 FROM pg_rewrite WHERE ev_class = ANY(tables) AND ev_enabled IN ('A', 'R')
+ ) OR EXISTS (
+ SELECT 1 FROM pg_constraint WHERE contype = 'f'
+ AND confrelid = ANY(tables) AND NOT conrelid = ANY(tables)
+ ) OR EXISTS (
+ SELECT 1 FROM pg_inherits WHERE inhrelid = ANY(tables) OR inhparent = ANY(tables)
+ ) OR EXISTS (
+ SELECT 1 FROM pg_event_trigger WHERE evtenabled <> 'D'
+ ) OR NOT EXISTS (
+ SELECT 1 FROM pg_roles WHERE rolname = current_user AND rolsuper
+ ) THEN
+ EXECUTE 'TRUNCATE ' || targets || ' RESTART IDENTITY CASCADE';
+ ELSE
+ PERFORM set_config('session_replication_role', 'replica', true);
+ FOREACH target IN ARRAY tables LOOP
+ EXECUTE format('DELETE FROM %s', target);
+ END LOOP;
+ FOR sequence IN
+ SELECT n.nspname, c.relname FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ JOIN pg_depend d ON d.objid = c.oid
+ WHERE c.relkind = 'S' AND d.refobjid = ANY(tables)
+ AND d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_class'::regclass
+ AND d.deptype IN ('a', 'i')
+ LOOP
+ EXECUTE format('ALTER SEQUENCE %I.%I RESTART', sequence.nspname, sequence.relname);
+ END LOOP;
+ PERFORM set_config('session_replication_role', original_role, true);
+ END IF;
+ UPDATE persistence_brain SET brain_id = gen_random_uuid(), enabled = false, activated_at = NULL WHERE singleton = 1;
+ INSERT INTO sources (id, name, config)
+ VALUES ('default', 'default', '{"federated": true}'::jsonb)
+ ON CONFLICT (id) DO NOTHING;
+ END $reset$`);
}
/** Structural engine slice so the narrow reset works on either engine. */
diff --git a/test/persistence-consumer-scheduling.test.ts b/test/persistence-consumer-scheduling.test.ts
new file mode 100644
index 0000000000..a2cd87c94d
--- /dev/null
+++ b/test/persistence-consumer-scheduling.test.ts
@@ -0,0 +1,212 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';
+import { admitWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
+import { cancelWriteRequest } from '../src/core/persistence/control.ts';
+import { acquireWorktree } from '../src/core/persistence/ownership.ts';
+import { admission, assertCommittedSnapshot, assertConservation, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-consumer-scheduling-'));
+const config: HarnessConfig = {
+ kind: 'pglite', root: home, dataDir: join(home, 'data'), hostId: randomUUID(),
+ seed: 5105, schedules: 0, operations: 0,
+ sourceIds: ['consumer-scheduling', 'consumer-scheduling-other'], principalIds: [randomUUID()],
+};
+const env = { GBRAIN_HOME: home, GBRAIN_PERSISTENCE_FIXTURE_HOME: home };
+let engine: PGLiteEngine;
+
+beforeAll(async () => withEnv(env, async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(engine, config);
+}), 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+
+test('an immediate wake-up during an active tick is retained until that tick finishes', async () => {
+ const release = Promise.withResolvers<void>();
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async () => { throw new Error('No writes in scheduler probe'); },
+ { hostId: config.hostId, pollMs: 60_000 });
+ const scheduler = consumer as unknown as { doTick(): Promise<void>; schedule(ms: number): void };
+ let ticks = 0;
+ scheduler.doTick = async () => { if (++ticks === 1) await release.promise; };
+ try {
+ const active = consumer.tick();
+ scheduler.schedule(0);
+ await Bun.sleep(25);
+ expect(ticks).toBe(1);
+ release.resolve();
+ await active;
+ await waitFor(() => ticks === 2, { timeoutMs: 5_000 });
+ } finally {
+ release.resolve();
+ await consumer.stop();
+ }
+});
+
+for (const outcome of ['committed', 'failed'] as const) test(`a ${outcome} write preempts idle polling and drains the next FIFO request`, async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const first = await admitWrite(engine, admission(config, sources[0], `first-${outcome}`, 'first body'));
+ const second = await admitWrite(engine, admission(config, sources[0], `second-${outcome}`, 'second body'));
+ const release = Promise.withResolvers<void>();
+ const started: string[] = [];
+ const errors: unknown[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_engine, row) => {
+ started.push(row.id);
+ if (row.id === first.id) {
+ await release.promise;
+ if (outcome === 'failed') throw new Error('Permanent fixture failure');
+ }
+ return prepared(row, sources);
+ }, { hostId: config.hostId, concurrency: 1, pollMs: 60_000, onError: error => errors.push(error) });
+ try {
+ consumer.start();
+ await waitFor(() => started.length === 1);
+ await consumer.tick();
+ expect(started).toEqual([first.id]);
+ release.resolve();
+ await waitFor(async () => (await getWriteRequestById(engine, second.id))?.state === 'committed',
+ { timeoutMs: 5_000, label: 'completion wake-up must not wait for the idle poll' });
+ expect(started).toEqual([first.id, second.id]);
+ const terminal = (await getWriteRequestById(engine, first.id))!;
+ expect(terminal.state).toBe(outcome);
+ if (outcome === 'committed') await assertCommittedSnapshot(engine, terminal);
+ else expect(await engine.readPageSnapshot(first.slug, { sourceId: config.sourceIds[0] })).toBeNull();
+ await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, second.id))!);
+ await assertConservation(engine);
+ expect(errors).toEqual([]);
+ } finally {
+ release.resolve();
+ await consumer.stop();
+ for (const row of [first, second]) await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);
+ }
+}), 15_000);
+
+test('stopping while preparation is active does not schedule another queued write', async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const first = await admitWrite(engine, admission(config, sources[0], 'stop-first', 'first body'));
+ const second = await admitWrite(engine, admission(config, sources[0], 'stop-second', 'second body'));
+ const release = Promise.withResolvers<void>();
+ const started: string[] = [];
+ const errors: unknown[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_engine, row) => {
+ started.push(row.id);
+ await release.promise;
+ return prepared(row, sources);
+ }, { hostId: config.hostId, concurrency: 1, pollMs: 60_000, onError: error => errors.push(error) });
+ try {
+ consumer.start();
+ await waitFor(() => started.length === 1);
+ await consumer.tick();
+ const stopped = consumer.stop();
+ release.resolve();
+ await stopped;
+ await consumer.tick();
+ expect(started).toEqual([first.id]);
+ expect((await getWriteRequestById(engine, first.id))?.state).toBe('queued');
+ expect((await getWriteRequestById(engine, second.id))?.state).toBe('queued');
+ expect(consumer.status()).toMatchObject({ accepting: false, active_preparations: 0 });
+ expect(errors).toEqual([]);
+ await assertConservation(engine);
+ } finally {
+ release.resolve();
+ await consumer.stop();
+ for (const row of [first, second]) await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);
+ }
+}), 15_000);
+
+for (const reason of ['locked root', 'retryable preparation'] as const) test(`${reason} keeps idle backoff instead of spinning on immediate wake-ups`, async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], 'blocked', 'blocked body'));
+ const lock = reason === 'locked root' ? await acquireWorktree(sources[0].binding) : undefined;
+ if (reason === 'locked root') expect(lock).not.toBeNull();
+ let attempts = 0;
+ const errors: unknown[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_engine, current) => {
+ attempts++;
+ if (reason === 'retryable preparation') throw Object.assign(new Error('Retryable fixture failure'), { code: '40001' });
+ return prepared(current, sources);
+ }, { hostId: config.hostId, concurrency: 1, pollMs: 60_000, onError: error => errors.push(error) });
+ try {
+ consumer.start();
+ await waitFor(() => attempts > 0 && consumer.status().active_preparations === 0);
+ await Bun.sleep(100);
+ expect(attempts).toBe(1);
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ expect(errors).toEqual([]);
+ } finally {
+ await consumer.stop();
+ await lock?.release();
+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);
+ }
+}), 15_000);
+
+for (const reason of ['locked root', 'retryable preparation'] as const) test(`healthy completions preserve ${reason} backoff on another root`, async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const suffix = reason.replaceAll(' ', '-');
+ const blocked = await admitWrite(engine, admission(config, sources[0], `mixed-blocked-${suffix}`, 'blocked body'));
+ const healthy = await Promise.all(Array.from({ length: 3 }, (_, i) =>
+ admitWrite(engine, admission(config, sources[1], `mixed-healthy-${suffix}-${i}`, `healthy body ${i}`))));
+ const lock = reason === 'locked root' ? await acquireWorktree(sources[0].binding) : undefined;
+ if (reason === 'locked root') expect(lock).not.toBeNull();
+ let attempts = 0;
+ const errors: unknown[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_engine, row) => {
+ if (row.id === blocked.id) {
+ attempts++;
+ if (reason === 'retryable preparation') throw Object.assign(new Error('Retryable fixture failure'), { code: '40001' });
+ }
+ return prepared(row, sources);
+ }, { hostId: config.hostId, concurrency: 2, pollMs: 60_000, onError: error => errors.push(error) });
+ try {
+ consumer.start();
+ await waitFor(async () => (await Promise.all(healthy.map(row => getWriteRequestById(engine, row.id))))
+ .every(row => row?.state === 'committed'), { timeoutMs: 5_000 });
+ await waitFor(() => consumer.status().active_preparations === 0);
+ expect(attempts).toBe(1);
+ expect((await getWriteRequestById(engine, blocked.id))?.state).toBe('queued');
+ for (const row of healthy) await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, row.id))!);
+ await assertConservation(engine);
+ expect(errors).toEqual([]);
+ } finally {
+ await consumer.stop();
+ await lock?.release();
+ for (const row of [blocked, ...healthy]) await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);
+ }
+}), 15_000);
+
+test('a retryable root becomes eligible again after its backoff expires', async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], 'retry-expiry', 'retry body'));
+ const attempts: number[] = [];
+ const errors: unknown[] = [];
+ const pollMs = 200;
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_engine, current) => {
+ attempts.push(Date.now());
+ if (attempts.length === 1) throw Object.assign(new Error('Retryable fixture failure'), { code: '40001' });
+ return prepared(current, sources);
+ }, { hostId: config.hostId, pollMs, onError: error => errors.push(error) });
+ try {
+ consumer.start();
+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 5_000 });
+ expect(attempts).toHaveLength(2);
+ expect(attempts[1] - attempts[0]).toBeGreaterThanOrEqual(pollMs);
+ await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, row.id))!);
+ await assertConservation(engine);
+ expect(errors).toEqual([]);
+ } finally {
+ await consumer.stop();
+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);
+ }
+}), 15_000);
diff --git a/test/persistence-root-refresh.test.ts b/test/persistence-root-refresh.test.ts
new file mode 100644
index 0000000000..0a734458a9
--- /dev/null
+++ b/test/persistence-root-refresh.test.ts
@@ -0,0 +1,64 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { refreshManagedFilesystemRoots, assertManagedFilesystemWrite } from '../src/core/persistence/filesystem-guard.ts';
+import { fixtures, initializeFixtures, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-root-refresh-'));
+const config: HarnessConfig = {
+ kind: 'pglite', root: home, dataDir: join(home, 'data'), hostId: randomUUID(),
+ seed: 5105, schedules: 0, operations: 0,
+ sourceIds: ['root-refresh'], principalIds: [randomUUID()],
+};
+let engine: PGLiteEngine;
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home, GBRAIN_PERSISTENCE_FIXTURE_HOME: home }, async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(engine, config);
+}), 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+
+test('unchanged bound roots retain their durable records without replacement', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const [source] = await fixtures(engine, config);
+ await refreshManagedFilesystemRoots(engine);
+ const directory = join(home, '.gbrain', 'persistence', 'managed-roots');
+ const records = () => readdirSync(directory).filter(file => file.endsWith('.json')).map(file => {
+ const path = join(directory, file);
+ const stat = statSync(path, { bigint: true });
+ return { file, inode: stat.ino, modified: stat.mtimeNs, bytes: readFileSync(path, 'utf8') };
+ });
+ const before = records();
+ expect(before).toHaveLength(1);
+ await refreshManagedFilesystemRoots(engine);
+ expect(records()).toEqual(before);
+ expect(JSON.parse(before[0].bytes)).toMatchObject({ source_id: source.id, worktree_id: source.binding.worktree_id });
+ expect(() => assertManagedFilesystemWrite(join(source.root, 'note.md'))).toThrow('managed canonical worktree');
+}));
+
+test('unbound and moved source paths remain fenced alongside the original bound root', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const [source] = await fixtures(engine, config);
+ const unbound = join(home, 'unbound'); mkdirSync(unbound);
+ const moved = join(home, 'moved'); mkdirSync(moved);
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['unbound-refresh', unbound]);
+ await tx.executeRaw('UPDATE sources SET local_path=$1 WHERE id=$2', [moved, source.id]);
+ });
+ await refreshManagedFilesystemRoots(engine);
+ for (const root of [source.root, unbound, moved]) {
+ expect(() => assertManagedFilesystemWrite(join(root, 'note.md'))).toThrow('managed canonical worktree');
+ }
+ const records = readdirSync(join(home, '.gbrain', 'persistence', 'managed-roots'));
+ expect(records.filter(file => file.endsWith('.json'))).toHaveLength(3);
+}));
diff --git a/test/privacy-script-wired.test.ts b/test/privacy-script-wired.test.ts
index f2fdb9547f..313fd237ce 100644
--- a/test/privacy-script-wired.test.ts
+++ b/test/privacy-script-wired.test.ts
@@ -20,8 +20,9 @@
*/
import { describe, it, expect } from 'bun:test';
-import { readFileSync, existsSync } from 'fs';
-import { resolve } from 'path';
+import { readFileSync, existsSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
+import { join, resolve } from 'path';
+import { tmpdir } from 'os';
import { spawnSync } from 'child_process';
const REPO_ROOT = resolve(import.meta.dir, '..');
@@ -29,6 +30,27 @@ const PACKAGE_JSON = resolve(REPO_ROOT, 'package.json');
const PRIVACY_SCRIPT = resolve(REPO_ROOT, 'scripts/check-privacy.sh');
const VERIFY_DISPATCHER = resolve(REPO_ROOT, 'scripts/run-verify-parallel.sh');
const TEST_WORKFLOW = resolve(REPO_ROOT, '.github/workflows/test.yml');
+const guardSource = readFileSync(PRIVACY_SCRIPT, 'utf8');
+const bannedName = guardSource.match(/^BANNED_NAME='([^']+)'/m)![1]!;
+const bannedPath = guardSource.match(/BANNED_PATHS=\(\s*'([^']+)'/)![1]!;
+
+function privacyFixture(files: Record<string, string>) {
+ const root = mkdtempSync(join(tmpdir(), 'privacy-guard-'));
+ for (const [file, contents] of Object.entries(files)) {
+ const target = join(root, file);
+ mkdirSync(resolve(target, '..'), { recursive: true });
+ writeFileSync(target, contents);
+ }
+ const init = spawnSync('git', ['init', '-q', root]);
+ expect(init.status).toBe(0);
+ const add = spawnSync('git', ['add', '.'], { cwd: root });
+ expect(add.status).toBe(0);
+ return root;
+}
+
+function runPrivacy(root: string, args: string[] = [], env: Record<string, string> = {}) {
+ return spawnSync('bash', [PRIVACY_SCRIPT, ...args], { cwd: root, encoding: 'utf8', env: { ...process.env, ...env } });
+}
describe('check-privacy.sh CI wiring', () => {
it('scripts/check-privacy.sh exists and is executable', () => {
@@ -71,4 +93,92 @@ describe('check-privacy.sh CI wiring', () => {
const yml = readFileSync(TEST_WORKFLOW, 'utf-8');
expect(yml).toContain('bun run verify');
});
+
+ it('reports every name and path violation with its original line number', () => {
+ const root = privacyFixture({
+ 'docs/a file.md': `safe\n${bannedName.toUpperCase()}\n${bannedPath}\n`,
+ 'src/b.ts': `${bannedName}\n`,
+ 'ignored.bin': bannedName,
+ });
+ try {
+ const r = runPrivacy(root);
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('BANNED NAME in docs/a file.md');
+ expect(r.stderr).toContain(`2:${bannedName.toUpperCase()}`);
+ expect(r.stderr).toContain(`BANNED PATH '${bannedPath}' in docs/a file.md`);
+ expect(r.stderr).toContain('BANNED NAME in src/b.ts');
+ expect(r.stderr).not.toContain('ignored.bin');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it('preserves exact allowlist paths, case-sensitive path rules, and the changelog name check', () => {
+ const root = privacyFixture({
+ 'CLAUDE.md': `${bannedName}\n${bannedPath}\n`,
+ 'CHANGELOG.md': `${bannedPath}\n`,
+ 'docs/case.md': `${bannedPath.toUpperCase()}\n`,
+ });
+ try {
+ expect(runPrivacy(root).status).toBe(0);
+ writeFileSync(join(root, 'CHANGELOG.md'), `${bannedName}\n`);
+ const r = runPrivacy(root);
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('BANNED NAME in CHANGELOG.md');
+ expect(r.stderr).not.toContain('BANNED PATH');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it('staged mode keeps its selected-file scope and scans their current working contents', () => {
+ const root = privacyFixture({ 'selected.md': 'safe\n' });
+ try {
+ writeFileSync(join(root, 'intent.md'), `${bannedName}\n`);
+ expect(spawnSync('git', ['add', '-N', 'intent.md'], { cwd: root }).status).toBe(0);
+ expect(runPrivacy(root, ['--staged']).status).toBe(0);
+ expect(runPrivacy(root).status).toBe(1);
+ writeFileSync(join(root, 'selected.md'), `${bannedName}\n`);
+ const r = runPrivacy(root, ['--staged']);
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('BANNED NAME in selected.md');
+ expect(r.stderr).not.toContain('intent.md');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it('batches clean files while still checking matches beyond the first batch', () => {
+ const root = privacyFixture(Object.fromEntries(Array.from({ length: 260 }, (_, i) => [`docs/clean ${i}.md`, 'safe\n'])));
+ const bin = join(root, 'bin');
+ mkdirSync(bin);
+ const log = join(root, 'grep-calls');
+ writeFileSync(join(bin, 'grep'), `#!/usr/bin/env bash\nprintf 'grep\\n' >> "$GREP_CALL_LOG"\nexec "$REAL_GREP" "$@"\n`, { mode: 0o755 });
+ const env = { PATH: `${bin}:${process.env.PATH}`, GREP_CALL_LOG: log, REAL_GREP: Bun.which('grep')! };
+ try {
+ expect(runPrivacy(root, [], env).status).toBe(0);
+ expect(readFileSync(log, 'utf8').trim().split('\n').length).toBeLessThan(10);
+ writeFileSync(join(root, 'docs', 'clean 99.md'), `${bannedName}\n`);
+ const r = runPrivacy(root, [], env);
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('BANNED NAME in docs/clean 99.md');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it('fails closed when a later candidate batch cannot be scanned', () => {
+ const root = privacyFixture(Object.fromEntries(Array.from({ length: 260 }, (_, i) => [`docs/file ${i}.md`, `${bannedName}\n`])));
+ const bin = join(root, 'bin');
+ mkdirSync(bin);
+ const marker = join(root, 'first-batch');
+ writeFileSync(join(bin, 'grep'), `#!/usr/bin/env bash\nif [ -f "$BATCH_MARKER" ]; then\n echo 'candidate scan failed' >&2\n exit 2\nfi\nprintf done > "$BATCH_MARKER"\nexec "$REAL_GREP" "$@"\n`, { mode: 0o755 });
+ try {
+ const r = runPrivacy(root, [], { PATH: `${bin}:${process.env.PATH}`, BATCH_MARKER: marker, REAL_GREP: Bun.which('grep')! });
+ expect(r.status).toBe(2);
+ expect(r.stderr).toContain('candidate scan failed');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
});
diff --git a/test/scripts/check-test-isolation.test.ts b/test/scripts/check-test-isolation.test.ts
index b4fa8ba0d8..363aa75e14 100644
--- a/test/scripts/check-test-isolation.test.ts
+++ b/test/scripts/check-test-isolation.test.ts
@@ -10,7 +10,7 @@
import { describe, it, expect } from 'bun:test';
import { spawnSync } from 'child_process';
-import { mkdtempSync, mkdirSync, writeFileSync } from 'fs';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join, resolve } from 'path';
@@ -29,7 +29,7 @@ interface RunResult {
stderr: string;
}
-function runLintIn(files: FakeFile[], allowlist: string[] = []): RunResult {
+function runLintIn(files: FakeFile[], allowlist: string[] = [], env: Record<string, string> = {}): RunResult {
const dir = mkdtempSync(join(tmpdir(), 'lint-isolation-'));
mkdirSync(join(dir, 'test'), { recursive: true });
mkdirSync(join(dir, 'scripts'), { recursive: true });
@@ -49,7 +49,7 @@ function runLintIn(files: FakeFile[], allowlist: string[] = []): RunResult {
const r = spawnSync('bash', [LINT_SH, 'test'], {
cwd: dir,
encoding: 'utf-8',
- env: { ...process.env },
+ env: { ...process.env, ...env },
});
return { status: r.status ?? -1, stdout: r.stdout, stderr: r.stderr };
}
@@ -66,6 +66,30 @@ describe('check-test-isolation.sh', () => {
expect(r.status).toBe(0);
expect(r.stdout).toContain('check-test-isolation: OK');
});
+
+ it('batches candidate scans instead of starting grep for every clean file', () => {
+ const bin = mkdtempSync(join(tmpdir(), 'lint-grep-count-'));
+ const log = join(bin, 'calls');
+ writeFileSync(join(bin, 'grep'), `#!/usr/bin/env bash\nprintf 'grep\\n' >> "$GREP_CALL_LOG"\nexec "$REAL_GREP" "$@"\n`, { mode: 0o755 });
+ try {
+ const files = Array.from({ length: 260 }, (_, i) => ({ path: `clean ${i}.test.ts`, contents: 'if (process.env.TEST_MODE === "yes") {}\n' }));
+ const env = { PATH: `${bin}:${process.env.PATH}`, GREP_CALL_LOG: log, REAL_GREP: Bun.which('grep')! };
+ const r = runLintIn(
+ files,
+ [],
+ env,
+ );
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain('260 non-serial unit files scanned');
+ expect(readFileSync(log, 'utf8').trim().split('\n').length).toBeLessThan(10);
+ const bad = runLintIn([...files, { path: 'z bad.test.ts', contents: `Reflect.set(process.env, 'OOPS', 'bad');\n` }], [], env);
+ expect(bad.status).toBe(1);
+ expect(bad.stdout).toContain('z bad.test.ts');
+ expect(bad.stdout).toContain('rule R1');
+ } finally {
+ rmSync(bin, { recursive: true, force: true });
+ }
+ });
});
describe('R1 — env mutation', () => {
@@ -179,6 +203,19 @@ describe('check-test-isolation.sh', () => {
]);
expect(r.status).toBe(0);
});
+
+ it('keeps the exact 50-line boundary and reports violations in later candidate files', () => {
+ const r = runLintIn([
+ { path: 'a clean.test.ts', contents: 'export {};\n' },
+ { path: 'b boundary.test.ts', contents: `beforeAll(() => {});\n${'\n'.repeat(49)}new PGLiteEngine();\nafterAll(() => engine.disconnect());\n` },
+ { path: 'c outside.test.ts', contents: `beforeAll(() => {});\n${'\n'.repeat(50)}new PGLiteEngine();\nafterAll(() => engine.disconnect());\n` },
+ ]);
+ expect(r.status).toBe(1);
+ expect(r.stdout).toContain('rule R3');
+ expect(r.stdout).toContain('c outside.test.ts');
+ expect(r.stdout).not.toContain('b boundary.test.ts');
+ expect(r.stdout).toContain('52:new PGLiteEngine();');
+ });
});
describe('R4 — afterAll/disconnect pairing', () => {
diff --git a/test/scripts/ci-local-rendering.test.ts b/test/scripts/ci-local-rendering.test.ts
index 2a319c2c46..0b77fd3faf 100644
--- a/test/scripts/ci-local-rendering.test.ts
+++ b/test/scripts/ci-local-rendering.test.ts
@@ -9,6 +9,17 @@ const source = readFileSync(join(import.meta.dir, '../../scripts/ci-local.sh'),
const templateStart = source.indexOf("INNER_CMD=$(cat <<'EOF'");
const templateEnd = source.indexOf('\n# Conductor / git-worktree support:', templateStart);
+test('the CI admin build keeps container dependencies and Vite cache off the host', () => {
+ const compose = Bun.YAML.parse(readFileSync(join(import.meta.dir, '../../docker-compose.ci.yml'), 'utf8')) as {
+ services: { runner: { volumes: string[] } };
+ volumes: Record<string, unknown>;
+ };
+ expect(compose.services.runner.volumes).toContain('gbrain-ci-admin-node-modules:/app/admin/node_modules');
+ expect(Object.hasOwn(compose.volumes, 'gbrain-ci-admin-node-modules')).toBe(true);
+ expect(compose.services.runner.volumes).toContain('gbrain-ci-admin-dist:/app/admin/dist');
+ expect(Object.hasOwn(compose.volumes, 'gbrain-ci-admin-dist')).toBe(true);
+});
+
describe('ci-local command rendering', () => {
const cases = [
{ phaseExit: 0, missingTool: '' },
@@ -83,7 +94,7 @@ function runPhases(noShard: boolean, diff: boolean, failStage = '') {
put('bin/bun', `
case "$*" in
"run scripts/select-e2e.ts") printf '%s\\n' test/e2e/one.test.ts test/e2e/two.test.ts; exit 0 ;;
- "run typecheck") stage=verify ;;
+ "run verify") stage=verify ;;
"run test:serial") stage=serial ;;
"run test:slow") stage=slow ;;
*) exit 0 ;;
@@ -91,9 +102,6 @@ esac
printf '%s:%s\\n' "$stage" "\${DATABASE_URL-unset}" >> "$TRACE"
[ "$FAIL_STAGE" != "$stage" ] || exit 7
`);
- for (const script of ['check-jsonb-pattern.sh', 'check-progress-to-stdout.sh', 'check-trailing-newline.sh', 'check-wasm-embedded.sh']) {
- put(`scripts/${script}`, 'exit 0');
- }
put('scripts/check-bun-test-timeout.sh', `
printf 'timeout_guard:%s\\n' "\${DATABASE_URL-unset}" >> "$TRACE"
[ "$FAIL_STAGE" != timeout_guard ] || exit 7
diff --git a/test/scripts/typecheck-incremental.test.ts b/test/scripts/typecheck-incremental.test.ts
new file mode 100644
index 0000000000..4ab5276e78
--- /dev/null
+++ b/test/scripts/typecheck-incremental.test.ts
@@ -0,0 +1,128 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import pkg from '../../package.json';
+
+const tsc = resolve(import.meta.dir, '../../node_modules/typescript/bin/tsc');
+const [command, ...args] = pkg.scripts.typecheck.split(/\s+/);
+const roots: string[] = [];
+
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+function write(root: string, file: string, content: string) {
+ const path = join(root, file);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, content);
+}
+
+function fixture(source = 'export const answer: number = 42;\n', strict = true) {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-typecheck-'));
+ roots.push(root);
+ write(root, 'tsconfig.base.json', JSON.stringify({ compilerOptions: {
+ target: 'ESNext', module: 'ESNext', moduleResolution: 'bundler', lib: ['ES5'],
+ types: [], strict, skipLibCheck: true, noEmit: true,
+ } }));
+ write(root, 'tsconfig.json', JSON.stringify({ extends: './tsconfig.base.json', include: ['src'] }));
+ write(root, 'src/main.ts', source);
+ return root;
+}
+
+function check(root: string) {
+ expect(command).toBe('tsc');
+ const result = spawnSync(Bun.which('node') ?? process.execPath, [tsc, ...args], { cwd: root, encoding: 'utf8', timeout: 30_000 });
+ expect(result.error).toBeUndefined();
+ expect(result.signal).toBeNull();
+ expect(existsSync(join(root, 'node_modules/.cache/gbrain-typecheck.tsbuildinfo'))).toBe(true);
+ return { status: result.status ?? -1, output: result.stdout + result.stderr };
+}
+
+function rejects(root: string, code: string) {
+ const result = check(root);
+ expect([1, 2]).toContain(result.status);
+ expect(result.output).toContain(code);
+ return result.output;
+}
+
+describe('native incremental typecheck', () => {
+ test('reuses compiler state without hiding edited-source or newly added-file errors', () => {
+ const root = fixture();
+ expect(check(root).status).toBe(0);
+ expect(check(root).status).toBe(0);
+ expect(readdirSync(join(root, 'src'))).toEqual(['main.ts']);
+
+ write(root, 'src/main.ts', 'export const answer: string = 42;\n');
+ const first = rejects(root, 'TS2322');
+ expect(rejects(root, 'TS2322')).toEqual(first);
+ write(root, 'src/main.ts', 'export const answer: number = 42;\n');
+ expect(check(root).status).toBe(0);
+
+ write(root, 'src/extra.ts', 'export const extra: string = 42;\n');
+ rejects(root, 'TS2322');
+ rmSync(join(root, 'src/extra.ts'));
+ expect(check(root).status).toBe(0);
+ });
+
+ test('invalidates inherited compiler options and the configured root file set', () => {
+ const root = fixture('export function identity(value) { return value; }\n', false);
+ expect(check(root).status).toBe(0);
+ const basePath = join(root, 'tsconfig.base.json');
+ const base = JSON.parse(readFileSync(basePath, 'utf8'));
+ base.compilerOptions.strict = true;
+ writeFileSync(basePath, JSON.stringify(base));
+ const first = rejects(root, 'TS7006');
+ expect(rejects(root, 'TS7006')).toEqual(first);
+ base.compilerOptions.strict = false;
+ writeFileSync(basePath, JSON.stringify(base));
+ expect(check(root).status).toBe(0);
+
+ write(root, 'extra/more.ts', 'export const more: string = 42;\n');
+ expect(check(root).status).toBe(0);
+ write(root, 'tsconfig.json', JSON.stringify({ extends: './tsconfig.base.json', include: ['src', 'extra'] }));
+ rejects(root, 'TS2322');
+ write(root, 'tsconfig.json', JSON.stringify({ extends: './tsconfig.base.json', include: ['src'] }));
+ expect(check(root).status).toBe(0);
+ });
+
+ test('invalidates dependency contents and package type-entry changes', () => {
+ const root = fixture('import type { Value } from "fixture-dep";\nexport const answer: Value = 42;\n');
+ const dependency = 'node_modules/fixture-dep';
+ const manifest = { name: 'fixture-dep', version: '1.0.0', types: 'index.d.ts' };
+ write(root, `${dependency}/package.json`, JSON.stringify(manifest));
+ write(root, `${dependency}/index.d.ts`, 'export type Value = number;\n');
+ expect(check(root).status).toBe(0);
+
+ const declaration = join(root, dependency, 'index.d.ts');
+ const previous = statSync(declaration);
+ writeFileSync(declaration, 'export type Value = string;\n');
+ utimesSync(declaration, previous.atime, previous.mtime);
+ const first = rejects(root, 'TS2322');
+ expect(rejects(root, 'TS2322')).toEqual(first);
+ writeFileSync(declaration, 'export type Value = number;\n');
+ expect(check(root).status).toBe(0);
+
+ write(root, `${dependency}/other.d.ts`, 'export type Value = string;\n');
+ write(root, `${dependency}/package.json`, JSON.stringify({ ...manifest, types: 'other.d.ts' }));
+ rejects(root, 'TS2322');
+ write(root, `${dependency}/package.json`, JSON.stringify(manifest));
+ expect(check(root).status).toBe(0);
+ });
+
+ test('does not turn cached diagnostics, incompatible state, or malformed state into success', () => {
+ const root = fixture('export const answer: string = 42;\n');
+ const first = rejects(root, 'TS2322');
+ expect(rejects(root, 'TS2322')).toEqual(first);
+ const cache = join(root, 'node_modules/.cache/gbrain-typecheck.tsbuildinfo');
+ const info = JSON.parse(readFileSync(cache, 'utf8'));
+ info.version = '0.0.0-incompatible';
+ writeFileSync(cache, JSON.stringify(info));
+ expect(rejects(root, 'TS2322')).toEqual(first);
+ writeFileSync(cache, '{');
+ expect(rejects(root, 'TS2322')).toEqual(first);
+ write(root, 'src/main.ts', 'export const answer: number = 42;\n');
+ expect(check(root).status).toBe(0);
+ });
+});
diff --git a/test/sync-rename-reconcile.serial.test.ts b/test/sync-rename-reconcile.serial.test.ts
index fb37cd7b13..aa79691250 100644
--- a/test/sync-rename-reconcile.serial.test.ts
+++ b/test/sync-rename-reconcile.serial.test.ts
@@ -2502,7 +2502,7 @@ describe('#3583 review: GATE25 — the upgrade path for someone already wedged b
describe('rename destination import: an errored skip must not checkpoint the rename as done', () => {
test('a frontmatter slug-authority rejection at the destination is retried, never falsely checkpointed', async () => {
const { performSync } = await import('../src/commands/sync.ts');
- const repo = mkRepo({ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.') });
+ const repo = mkRepo({ 'people/alpha.md': `${personMd('Alpha', 'Alpha is a person.')}\n` });
await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
expect(await engine.getPage('people/alpha')).not.toBeNull();
@@ -2517,11 +2517,13 @@ describe('rename destination import: an errored skip must not checkpoint the ren
execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });
writeFileSync(join(repo, 'people/beta.md'), [
'---', 'type: person', 'title: Alpha', 'slug: totally-different', '---',
- '', 'Alpha is a person.',
+ '', 'Alpha is a person.', '',
].join('\n'));
execSync('git add -A && git commit -m "rename alpha to beta, corrupted frontmatter"', {
cwd: repo, stdio: 'pipe',
});
+ expect(execSync('git diff --name-status -M HEAD~1 HEAD', { cwd: repo }).toString())
+ .toMatch(/^R\d+\tpeople\/alpha\.md\tpeople\/beta\.md\n$/);
const first = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
expect(first.status).toBe('blocked_by_failures');