Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.60.10.0 perf(persistence): PGLite managed writes 3.7× faster, same durability (#5684)
Garry Tan608a174dcfa1
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 9713ab5623..fab243c1a9 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.8.0",+ "version": "0.60.10.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.jsonindex 339863cdd2..8c2609afbc 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.8.0",+ "version": "0.60.10.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.mdindex 74bb601ba6..d0a828c698 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.8.0 -->+<!-- gbrain-runbook-stamp: 0.60.10.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0113667f8e..40dd21f332 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,35 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.10.0] - 2026-09-29++**Local PGLite brains now commit writes about 3.7× faster, with the same durability.**++A local brain's resident writer spent most of each write on overhead. It parsed and planned every SQL statement from scratch, reopened hundreds of database files per write, blocked on two `git` subprocesses, and ran work that grew with the size of the brain. PGLite never runs autovacuum, so receipt lookups ended up scanning every request a writer had ever made. Every write still takes the same path, with the same staged files, fsyncs, recovery records and crash boundaries.++| On a Ubicloud standard-30, same VM, matched runs | Before | After |+| --- | --- | --- |+| PGLite, 1,000-write soak (median of 3) | 7.20 writes/s | 26.86 writes/s |+| PGLite, time for a caller's write to commit (p50) | 2.14 s | 0.55 s |+| Postgres, 1,000-write soak (median of 3) | 11.22 writes/s | 12.93 writes/s |++The 10,000-write validation soak now takes 335 s on PGLite (29.9 writes/s; master took 1,417 s when last measured) and 692 s on Postgres (14.5 writes/s; master 886 s).++All eight SIGKILL crash boundaries and the full default validation gate pass on both engines.++### To take advantage of v0.60.10.0++Run `gbrain upgrade`. There is no migration. The resident writer picks up the changes when it restarts.++### Itemized changes++- **PGLite reuses prepared statements.** A statement seen twice is prepared once on the server and later runs as a single protocol batch, like postgres.js already does for Postgres. Results are parsed with parsers resolved once per statement. A changed result shape or schema change drops the cached statement.+- **PGLite keeps its planner statistics current.** The resident writer vacuums and analyzes its queue tables, since PGLite has no autovacuum. Projection statistics refresh after 50 rows plus 10% of the page table have changed, not after every write. The projection queue is read job-first, so an empty queue costs the same at any brain size.+- **Git effects no longer block the writer.** The durability-hook check runs its `git` probes asynchronously, once per worktree root per effect batch, and never while holding the worktree lock. When the repository has no durability hook, a git effect only proves the root with the lock and records its outcome without holding it. Effects drain in batches of 20 and keep pace with publication.+- **Fewer statements per write.** Page guards already held in a transaction are not taken again. Counter updates use one statement per step. The publication's final page read is reused when queuing effects and sealing projections. Exact-slug page reads keep alias resolution out of the parameters. Idle-time scans run at most once per poll interval while writes are flowing.+- **One-at-a-time writers no longer wait for the poll.** A caller waiting on its own write wakes the resident writer, which claims the write at once instead of on the next 250 ms poll. With reads running alongside, a single sequential writer on a local brain commits in about 58 ms instead of 270 ms.+- **Research record.** `docs/research/pglite-persistence-throughput-2026-09-29.md` has the owner profile before and after, the matched numbers, and the approaches that were tried and rejected.+## [0.60.8.0] - 2026-09-29**Pull-request CI asks for about a fifth of the machines it used to, so checks start right away instead of waiting half an hour in line.**diff --git a/VERSION b/VERSIONindex 510bfa781f..4d0449862b 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.8.0+0.60.10.0diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 4b1ee6bdd6..4d6523a937 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -18,7 +18,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion uses source-scoped journaled import/deletion and `managed-connector` checkpoint CAS, not Git cursors. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner, then start the existing consumer and wait up to five seconds for retained worktree publications to settle before checking file bytes or deriving new request identity. Blocked recovery returns its retained receipt and `blocked_reason`; startup recovery precedes connector fetching, and operator edits still fail the strict file-drift check. Explicit `--retry-failed` atomically admits a new linked attempt and stores a per-base-request `managed-connector-retry` pointer, without changing the API cursor or reopening terminal receipts. Approval revalidates current and accepted authority, source/configuration/owner and idle state; concurrent approvals and pending/restarted calls reuse the already approved attempt. Receipt compaction retains the digest and authority needed for exact replay and retry. Checkpoint page-receipt lists are server-derived validation dependencies, excluded from caller identity but frozen in the first admitted intent; changed dependency lists on an unchanged sweep cannot bypass a terminal checkpoint. Durable connector cursors and retry pointers survive generic seven-day checkpoint GC, including completed sweeps needed for incremental resume. Source incarnation/configuration changes select separate cursors; obsolete state remains retained rather than automatically retiring by age. Failed pagination/identity reads cannot advance freshness or delete unconfirmed pages. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts` and `test/helpers/connector-restart.ts` cover synthetic public sync entry in fresh processes, actual SIGKILL between file publication and DB commit, blocked recovery, zero-fetch authorization refusal, aged cursor purge/resume, real storage failures, compacted retries, checkpoint dependencies, atomic approval/lost acknowledgement and concurrent paused-owner replay on PGLite and disposable Postgres.-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex 191aff39e4..2261710c53 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -37,4 +37,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/pglite-lock.ts` — persistent datastore ownership uses a canonical sibling `.gbrain-owner.lock` retained inode and the native kernel binding. `.gbrain-lock/lock` retains PID, structured argv, command/subcommand and heartbeat diagnostics for `inspectLockHolder`/`peekLock` and engine-free IPC routing. The exported ps/proc/Windows CIM process probe is diagnostic compatibility only; ownership and takeover never consult it. Metadata age, corruption and PID reuse never override a kernel owner. The initial protocol upgrade refuses live/unknown legacy owners; all older processes must be stopped. Handles remain strongly retained until explicit release, so GC cannot unlock a datastore after a close timeout. Dead legacy migration keeps the one-acquisition WAL-repair quarantine; `msSinceLastReap` reads older persisted quarantine markers. Tests: `test/pglite-lock.test.ts` (real paused/crashed process, replacement/aliases, migration, metadata).+- `src/core/pglite-statements.ts` — `PgliteStatementCache`, the PGLite counterpart of postgres.js prepared statements. `PGLiteEngine._attachDatabase` routes the root handle's `query`/`exec` through it and `transaction()` routes each transaction handle. A statement text seen twice is prepared once as a named server-side statement; later calls send one Bind/Execute/Sync batch and parse rows with parsers resolved at prepare time, instead of PGlite's parse/describe round trips and its per-query copy of `db.parsers`. PostgreSQL's plan cache replans on invalidation; a changed result shape (`0A000`) or missing statement (`26000`) drops the entry and retries outside a transaction. `ALTER`/`CREATE`/`DROP`/`DO`/`DISCARD`/`DEALLOCATE` text and any non-transaction-control `exec` clear the cache, retired names are closed in the next prepare batch, an instance-level `query`/`exec` override (test seams) takes precedence on the root handle, and `_closeInternal` drops the cache with the database so a disconnected engine does not retain its PGLite instance. `dropRowTypeArrayParsers` removes composite-row array parsers after connect, since gbrain never selects those arrays. Pinned by `test/pglite-statements.test.ts`.+- `src/core/pglite-repair.ts` — WAL-repair orchestrator wrapping the resetWal port with the safety layers that make it runnable automatically from `connect()`: `validateWalRepairTarget` (read-only, fail-closed; refuses symlinked dataDir/pg_wal/`global`/pg_control — lstat follows INTERMEDIATE symlinks, so `global/` itself must be checked or surgery would write pg_control through it into a foreign dir; tolerates the in-dir `.gbrain-lock`), rename-based backup (the ENTIRE `pg_wal/` dir + postmaster.pid renamed into a sibling `<dataDir>.wal-repair-backup-<ts>/`, only the 8KB pg_control copied — zero transient disk cost), `restoreWalBackup` (overwrite order: control first via atomic tmp+rename, then a pg_wal dir swap with the reset dir set ASIDE inside the backup — nothing is ever deleted during restore; mtime guard refuses when a foreign segment is newer than the backup; a missing/empty backup NEVER reports `restored:true`), `WalRepairError` (thrown when resetWal fails AFTER the backup — carries the receipt + the best-effort restore's REAL result so the seam's `restored` flag and the `failed-restored`/`failed-not-restored` message arms never lie), a cooldown sidecar `<dataDir>.wal-repair-attempt.json` (skip `'recently-failed'` inside `GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600 — bounds the autopilot/supervisor reconnect loops) with episode-scoped backups (attempts within one corruption episode REUSE the episode's first backup — the pre-damage forensic state, honored only when the sidecar's path is a real non-symlink `<dataDir>.wal-repair-backup-*` sibling since the sidecar is user-writable JSON; retention keeps the newest 3 episodes, never pruning the open episode's), and `attemptWalRepairAndRetry` — the engine seam that NEVER throws (gates: kill-switch → reaped-lock `'possibly-live-writer'` → 10-minute reap-marker quarantine (`msSinceLastReap`, cross-process) → validation → cooldown; then repair → retry create once → restore-and-record on failure; prints a repair-start stderr line so a timeout-killed attempt is self-explaining). `inspectPgliteDataDir` is the read-only diagnosis for `gbrain doctor` + `pglite-repair --dry-run`. Imports runtime values only from `pglite-lock.ts`/`pglite-resetwal.ts`/node:fs — never from `pglite-engine.ts` (no cycle; the engine statically imports THIS file per the engine-live rule). Pinned by `test/pglite-repair.test.ts` + `test/pglite-wal-repair.serial.test.ts`.diff --git a/docs/research/README.md b/docs/research/README.mdindex 9ddf8aa95b..6b99e683a7 100644--- a/docs/research/README.md+++ b/docs/research/README.md@@ -5,4 +5,5 @@ These are historical evidence, not promises about current GBrain behavior.| Date | Research | Decision ||---|---|---|+| 2026-09-29 | [PGLite managed-persistence write throughput](pglite-persistence-throughput-2026-09-29.md) | Shipped. PGLite soak 8.9 → 31.7 writes/s in matched 1,000-write runs on `standard-30`; the 10,000-write gate soak drops from 1,417 s to 277–308 s; Postgres 11.2 → 13.5 writes/s; all crash boundaries and full gates pass. || 2026-09-24 | [T-Mem validation for GBrain](t-mem-2026-09-24/postmortem.md) | Feature [#5374](https://github.com/garrytan/gbrain/pull/5374) is mothballed, not merged. Preserve the research and evaluator separately: no completed custom feature-on score; a released-code pilot found a small descriptive-trigger retrieval signal but no demonstrated answer-quality gain. |diff --git a/docs/research/pglite-persistence-throughput-2026-09-29.md b/docs/research/pglite-persistence-throughput-2026-09-29.mdnew file mode 100644index 0000000000..f28509bfbb--- /dev/null+++ b/docs/research/pglite-persistence-throughput-2026-09-29.md@@ -0,0 +1,201 @@+# PGLite managed-persistence write throughput (2026-09-29)++**Decision:** ship. The PGLite soak goes from 8.9 to 31.7 committed writes/s in+matched 1,000-write runs on the final commit (3.6×). The full 10,000-write gate+soak drops from 1,417 s to 277–308 s across three VMs. Postgres does not+regress (11.2 → 13.5 writes/s). Every durability and crash contract is+unchanged, and the full default gate reports `full_gate: true` on both engines.++## Method++All numbers come from one Ubicloud `standard-30` VM (30 vCPU, Ubuntu 24.04,+Bun 1.3.13, `pgvector/pgvector:pg16` with default settings), running master+`6bb88d1` and the candidate side by side, alternating runs:++```bash+bun --no-env-file scripts/persistence/validate.ts --engine=<engine> \+ --schedules=0 --no-crashes --operations=1000 --manifest=<file>+```++The owner profile adds a scratch preload to the owner process that is not+shipped: an `AsyncLocalStorage` label per consumer phase, the SQL text and+PGLite WASM time of every protocol message, Node `fs` and child-process+counters, and `bun --cpu-prof-md` for the JavaScript side.++## Owner profile, 1,000 writes, per committed write++| | master | candidate |+|---|---:|---:|+| Owner wall time per write (the owner is saturated) | 113 ms | 30 ms |+| PGLite WASM time | 60.7 ms | 13.3 ms |+| SQL statements executed | 217 | 176 |+| Relation-file `open()` / `fstat()` from PGLite NODEFS | 473 / 1,690 | 4.4 / 113 |+| Synchronous `git` spawns on the event loop | 2.0 (6.3 ms blocked) | 0 (0.87 async probe pairs) |+| Projection rebuild WASM time (55 → 38 statements) | 20.5 ms | 3.3 ms |+| Publish transaction WASM time | 9.0 ms | 1.9 ms |++Where master's time went, in order:++1. **Per-statement overhead in PGlite.** `query()` parses, plans, and describes+ every call as an unnamed statement over five protocol round trips, and its+ result parser copies `db.parsers` (412 entries, most of them composite+ row-type arrays) for every result. That copy alone was 20% of owner CPU.+ Planning each statement calls `lseek(SEEK_END)` on every relation and index+ it touches. PGLite's file-descriptor cache is pinned at about 48 files, so the+ write path reopened ~470 relation segments per write. That cache limit is+ inherent to PGLite 0.4.3: `max_files_per_process` does not change it.+2. **Synchronous git probes.** The git effect's durability check ran+ `git config --get core.hooksPath` and `git rev-parse --git-path hooks` through+ `execFileSync`, blocking the owner for about 6 ms per write. It did not sit on+ the commit's ordering path, but the owner is one event loop, so it serialized+ with everything.+3. **Work that grows with the brain.** `ANALYZE pages(...)` ran after every+ drained projection rebuild, taking 10 ms at 10,000 pages. The projection-job+ selection scanned every page to probe an almost empty queue. PGLite has no+ autovacuum, so the queue tables were never analyzed: receipt and admission+ lookups picked the `(principal_kind, principal_id, sequence)` index over the+ unique request-id index and scanned every request of that principal. Their+ cost grew linearly across the 10,000-write soak.++Durable file work (fsync of the staged file and its directory) is about 4.7 ms+per write on this VM. It is required and unchanged.++## Changes++- `src/core/pglite-statements.ts`: named server-side statements for PGLite, the+ plan cache postgres.js already gives the Postgres engine. A statement seen+ twice is prepared once; later calls send one Bind/Execute/Sync batch and parse+ rows with parsers resolved at prepare time. A changed result shape or missing+ statement drops the entry. Shape-changing SQL clears the cache. The engine also+ drops composite row-type array parsers after connect.+- Git effects start their durability probe asynchronously, once per worktree+ root per effect batch, and wait for it after the rest of the batch without+ holding a worktree lock. A single-file git effect in a repository without the+ durability hook runs no git command; it acquires the worktree lock only to+ prove the root and records its outcome after releasing it. Effects drain in batches of 20 without waiting for+ the next consumer tick, so they keep pace with publication: at the end of+ every soak, all effects are committed and none are queued.+- The projection-job queue is read job-first. Planner statistics refresh on an+ autovacuum-style threshold (50 + 10% of pages) instead of after every drained+ rebuild.+- The resident owner runs `VACUUM (ANALYZE)` on the queue tables every minute+ or after 50 + 20% of the request table's rows in publications. PGLite only.+- Statement trims: reentrant page guards within one PGLite transaction and its+ open savepoints; one-statement counter updates; the publication's final+ snapshot reused when queuing effects; the projection's guarded snapshot reused+ when sealing; exact-slug snapshot reads keep alias resolution in the SQL text,+ so a cached plan uses the slug index; completion wake-ups skip the root+ refresh and recovery/expiry/topology scans when they ran less than one poll+ interval ago; the managed-root registry skips its directory fsync when no+ record changed.++## Matched throughput, `standard-30`, 3 × 1,000 writes, final commit++| Engine | master (median, range) | candidate (median, range) | Caller p50 |+|---|---|---|---|+| PGLite | 8.92 (8.92–8.98) | 31.68 (31.55–31.72) | 1,731 → 436 ms |+| Postgres | 11.18 (11.17–11.31) | 13.48 (13.27–13.90) | 1,317 → 1,134 ms |++VM placement moves absolute numbers. On a second VM, one commit earlier,+PGLite measured 8.97 → 33.14 and Postgres 11.35 → 13.86. On a noisier third VM+PGLite measured 8.35 → 25.34, where master was slower too. The ratio stayed+between 3.0× and 3.7×.++## Full default gate (1,000 schedules, 8 SIGKILL boundaries, 10,000-write soak)++| Engine | master soak | candidate soak | `full_gate` |+|---|---|---|---|+| PGLite | 7.06 writes/s, 1,417 s | 32.48 writes/s, 308 s (final commit); 36.11 / 277 s and 33.77 / 296 s on earlier commits and other VMs | true / true |+| Postgres | 11.28 writes/s, 886 s | 13.76–17.22 writes/s, 581–727 s | true / true |++The whole default PGLite gate (crash cases, schedules and soak) takes+337–373 s.++After the sequential-writer wake (below), the full default gate passed again on+both engines with `full_gate: true` and all 8 crash cases: PGLite soak 28.52+writes/s (351 s), Postgres soak 11.93 writes/s (838 s), on a VM with no master+control. A same-VM 10,000-write Postgres soak then measured master 12.50,+the pre-wake candidate 14.16 and the final candidate 14.00 writes/s, so the+wake costs Postgres nothing measurable and the soak stays about 12% above+master. Matched 3 × 1,000 on the wake commit: PGLite 8.88 → 31.27, Postgres+11.90 → 14.86 (medians).++## After merging master v0.60.5.0 (#5689)++#5689 added a WAL checkpoint guard that probes `pg_control_checkpoint()` before+every outermost PGLite transaction (about 12 probes per write, ~4% of+throughput when disabled locally), an idle-probe consumer backoff, and effect+parking. Master and this change both lost throughput; the ratio held. Matched+3 × 1,000 on one `standard-30`: PGLite 7.20 (7.16–7.26) → 26.86 (26.69–28.70)+writes/s, caller p50 2,144 → 548 ms; Postgres 11.22 (11.19–11.25) → 12.93+(12.77–13.10). Full default gate on the merged head: `full_gate: true` on both+engines with all 8 crash cases; PGLite soak 29.87 writes/s (335 s), Postgres+14.46 writes/s (692 s).++## Read latency (`scripts/persistence/performance.ts`, median of 3 runs)++The statement cache is engine-wide, so read paths were checked against master+on the same VM: 500 pages, 200 search queries, alone and under 4 concurrent+writers.++| Engine | master idle p50 / p95 | candidate idle p50 / p95 | master loaded p50 / p95 | candidate loaded p50 / p95 |+|---|---|---|---|---|+| PGLite | 11.6 / 19.3 ms | 8.2 / 16.6 ms | 12.5 / 17.3 ms | 8.9 / 16.0 ms |+| Postgres | 21.1 / 30.2 ms | 23.0 / 32.1 ms | 18.1 / 30.1 ms | 18.4 / 32.0 ms |++Both engines pass the workload's loaded-versus-idle gate. The Postgres+differences are within run-to-run noise; the Postgres engine's reads are not+changed by this work.++## One sequential writer under read load (local 4-core machine, 2 runs)++`test/persistence-performance.test.ts` runs 200 searches beside one writer that+submits its next write only after the previous one commits. After the throughput+changes, the reads finished in under a second while that writer committed only+1–5 writes, each taking about 270 ms. The consumer's post-publication tick now+claimed immediately, before the caller had admitted its next write, so every+sequential write waited for the 250 ms poll. On master the extra work between+publication and the next claim hid this gap.++`waitForWrite` now wakes the local owner for a claim-only tick, with scans still+bounded by the poll interval. `runReadLatencyWorkload` with 1,000 searches and+one sequential writer, on PGLite, same machine:++| | master | candidate |+|---|---|---|+| Read window for 1,000 searches | 97.5–106.6 s | 6.8–8.4 s |+| Search p50, idle / loaded | 7.0 / 9.5–9.9 ms | 1.3–1.4 / 2.4–2.6 ms |+| Sequential writes committed per second | 9.3–10.0 | 17.0–17.3 |+| Commit p50 / p95 | 96–104 / 132–142 ms | 56–57 / 70 ms |++Before the wake, the candidate measured 4.5 writes/s with a 268 ms commit p50 in+the same workload (4,000 searches).++## Tried and rejected++- `plan_cache_mode = force_custom_plan`: this keeps parse savings but replans+ every call. PGLite fell from 30.6 to 20.1 writes/s. Generic plans are safe+ once PGLite's statistics exist; the one generic-plan trap on the hot path, the+ snapshot read's `$2::boolean` alias toggle, is now statement text.+- Collapsing `lockCounters` into two array statements, and merging+ `indexingContext`'s two page reads: tests inject faults on those exact SQL+ strings, and the gain was small, so both are unchanged.+- A consumer concurrency above 1 on PGLite: `tryAcquirePublicationCapacity`+ admits one embedded publication at a time by design, and the owner is+ CPU-bound on one event loop, so extra claims would only be released as+ `writer_pool_capacity`.+- PGLite start parameters: `-F` (fsync off inside WASM Postgres) is PGLite's+ default and unchanged. Neither `max_files_per_process` nor any other GUC+ raises the ~48-file descriptor cache.++## Follow-up: where the 10,000-write soak should run++[#5667](https://github.com/garrytan/gbrain/pull/5667) cut pull-request soaks to+2,500 writes while the PGLite soak ran about 11 writes/s. The full 10,000-write+soak now takes 277–351 s on PGLite and 581–838 s on Postgres on `standard-30`.+Recommendation: keep 2,500 writes on pull requests, and run the full default+gate (10,000 writes, both engines) nightly and before each release. Two of the+regressions fixed here grew with queue size (receipt lookups scanning every+request without vacuum, and `ANALYZE` after every drained rebuild); 10,000+writes shows that kind of growth much more clearly than 2,500, but it does not+need to gate every pull request.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex fde6897598..816af9a0f3 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.8.0",+ "version": "0.60.10.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex 2080fea097..55332bf4f9 100644--- a/package.json+++ b/package.json@@ -191,7 +191,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.60.8.0",+ "version": "0.60.10.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.jsonindex adadace5ef..d8908b3d6c 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.60.8.0",+ "version": "0.60.10.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 6761dfc495..5eeccc79b5 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.60.8.0",+ "version": "0.60.10.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 035bb72cf0..038045eafa 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.8.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.10.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.jsonindex 20fa5a13e3..28cea1795a 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.60.8.0",+ "version": "0.60.10.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex ac2b6e989e..5257a7debf 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.60.8.0",+ "version": "0.60.10.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 77ad56727a..79de8b31f2 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.8.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.10.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.mdindex 3d80823fdf..21d29a2fbd 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.8.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.10.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 030ba452a1..a00298ebae 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -20,7 +20,7 @@ src/core/engine.ts 2667 ratchet grown v0.46.26.0 megawave: relational/visibilitysrc/core/import-file.ts 2283 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the mergesrc/core/migrate.ts 722 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: projection migration helper; #5105: lease schema helper; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +1 import for focused topology migration module; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: static projection statistics import; DDL remains region-exempt; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestionsrc/core/operations.ts 329 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base-src/core/pglite-engine.ts 6175 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations; +6 write-path wave: updateSlug records its rename alias in one transaction; +11 read-path wave: searchKeyword type/exclude_slugs Postgres parity + getTags private/deleted filters; +5: updateSlug carries entity-scoped fact withdrawals; +12 wave-2 W4: upsertChunks writes content_chunks.embedding_input_hash with the vector (#5553, parity twin); +6 #5449 outermost-transaction WAL checkpoint guard admitted into the shutdown drain, reset per attached database (logic in pglite-engine/checkpoint-guard.ts); +10 fw3-search: traversal walk row cap + (page, depth) dedupe (parity twin), source_boosts opt; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +8 at the merge+src/core/pglite-engine.ts 6184 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations; +6 write-path wave: updateSlug records its rename alias in one transaction; +11 read-path wave: searchKeyword type/exclude_slugs Postgres parity + getTags private/deleted filters; +5: updateSlug carries entity-scoped fact withdrawals; +12 wave-2 W4: upsertChunks writes content_chunks.embedding_input_hash with the vector (#5553, parity twin); +6 #5449 outermost-transaction WAL checkpoint guard admitted into the shutdown drain, reset per attached database (logic in pglite-engine/checkpoint-guard.ts); +10 fw3-search: traversal walk row cap + (page, depth) dedupe (parity twin), source_boosts opt; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +8 at the merge; +9: PGLite statement-cache attach and release, savepoint-aware page guards (helpers live in pglite-statements.ts and page-state/guards.ts)src/core/postgres-engine.ts 5590 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +3 wave-2 W4: upsertChunks writes content_chunks.embedding_input_hash with the vector (#5553, parity twin); +2 fix wave 2 (v0.60.5.0) integration: master grew 2 lines under the old ceiling while W4 raised it from its older base; +5 v0.60.5.0 master-merge true-up: W4 +12 re-summed over master v0.59.18.0 at 5575 lines; +8 fw3-search: traversal walk row cap + (page, depth) dedupe (parity twin), source_boosts opt; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the mergesrc/core/search/hybrid.ts 3125 ratchet +2: preserve local query-deadline classification through gateway error wrapping; grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes; retired provider integration removed; lowered fw3-search: alias hop peeled to search/alias-hop.ts; +5 fw3-search: general title-mention boost skips concept intent and relational questions; fix wave 3 x fix wave 2 (v0.60.5.0) composition: -90 at the merge (hybrid.ts: alias hop lives in search/alias-hop.ts)src/core/types.ts 2086 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the mergediff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.tsindex e5dc16dc55..0770e4ec1e 100644--- a/src/core/brain-repo-durability.ts+++ b/src/core/brain-repo-durability.ts@@ -33,7 +33,7 @@ import {existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync, statSync, renameSync,} from 'fs';import { join, dirname, relative, isAbsolute } from 'path';-import { execFileSync, execSync } from 'child_process';+import { execFile, execFileSync, execSync } from 'child_process';import {GIT_ENV, GIT_ENV_AUTH, divergenceSafePull, detectDefaultBranch, pushProbe,type PullOutcome, type PushProbeResult,@@ -445,6 +445,33 @@ export function isDurabilityHardened(repoPath: string): boolean {}}+/** A git probe that does not block the event loop; a failed probe reads as ''. */+function gitOutput(repoPath: string, args: string[]): Promise<string> {+ return new Promise(resolve => {+ execFile('git', ['-C', repoPath, ...args], { encoding: 'utf8', timeout: 10_000, env: { ...process.env, ...GIT_ENV } },+ (error, stdout) => resolve(error ? '' : stdout.trim()));+ });+}++/**+ * {@link isDurabilityHardened} for long-running owners: the same two git+ * probes, run concurrently as child processes the event loop does not wait on.+ */+export async function isDurabilityHardenedAsync(repoPath: string): Promise<boolean> {+ try {+ const [hooksPath, gitHooks] = await Promise.all([gitOutput(repoPath, ['config', '--get', 'core.hooksPath']),+ gitOutput(repoPath, ['rev-parse', '--git-path', 'hooks'])]);+ const reported = hooksPath || gitHooks;+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- repoPath is a registered local worktree root and the hooks path comes from git itself, resolved exactly as resolveHooksDir/gitDirPath do+ const dir = !reported ? join(repoPath, '.git', 'hooks') : isAbsolute(reported) ? reported : join(repoPath, reported);+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- fixed hook filename inside the git-reported hooks directory, as in isDurabilityHardened+ const hookPath = join(dir, 'post-commit');+ return existsSync(hookPath) && readFileSync(hookPath, 'utf-8').includes(HOOK_BANNER);+ } catch {+ return false;+ }+}+/*** #2426: best-effort commit of a single write-through artifact so DB writes* reach git (the post-commit hook then background-pushes). Pre-fix,diff --git a/src/core/page-state/guards.ts b/src/core/page-state/guards.tsindex 5aadfba8b4..6ecab2b528 100644--- a/src/core/page-state/guards.ts+++ b/src/core/page-state/guards.ts@@ -26,3 +26,32 @@ export async function lockPageKeys(engine: Pick<BrainEngine, 'executeRaw'>, keysawait engine.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE', [key.sourceId, key.slug]);}}++/**+ * Guards a PGLite transaction already holds, chained through its open+ * savepoints. The single PGLite session owns them until the transaction or+ * savepoint ends, so they are not re-acquired.+ */+export interface HeldPageKeys { keys: Set<string>; parent: HeldPageKeys | null }+function pageGuardKey(key: PageKey): string | null {+ if (!key.sourceId) return null;+ try { return JSON.stringify([key.sourceId, validateSlug(key.slug)]); } catch { return null; }+}+function holds(held: HeldPageKeys | null, id: string): boolean {+ for (; held; held = held.parent) if (held.keys.has(id)) return true;+ return false;+}+/** lockPageKeys for keys this transaction does not hold yet; invalid keys still reach its checks. */+export async function lockUnheldPageKeys(engine: Pick<BrainEngine, 'executeRaw'>, held: HeldPageKeys, keys: readonly PageKey[]): Promise<void> {+ const pending = keys.filter(key => { const id = pageGuardKey(key); return id === null || !holds(held, id); });+ if (!pending.length) return;+ await lockPageKeys(engine, pending);+ for (const key of pending) held.keys.add(pageGuardKey(key)!);+}+/** Runs a transaction or savepoint; a released savepoint's guards stay held by its parent, a rolled-back one's do not. */+export async function withHeldPageKeys<T>(parent: HeldPageKeys | null, run: (held: HeldPageKeys) => Promise<T>): Promise<T> {+ const held: HeldPageKeys = { keys: new Set(), parent };+ const result = await run(held);+ for (const key of held.keys) parent?.keys.add(key);+ return result;+}diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 47ad4d00e2..35baa868cd 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -16,9 +16,13 @@ import { belowSafeChunkFence } from '../search/safe-chunks.ts';import { acceptedEmbeddingInputHashes, embeddingInputHash, isContextualMode, plainEmbeddingTier, synopsisBodyHash,type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';-/** Complete the searchable snapshot only after its sanitized chunks are installed. */-export async function sealPageTextProjection(engine: BrainEngine, slug: string, sourceId: string): Promise<void> {- const current = await engine.readPageSnapshot(slug, { sourceId });+/**+ * Complete the searchable snapshot only after its sanitized chunks are installed.+ * `guarded` is this transaction's own read of the page under its guard, when+ * the caller has one and has not changed the page's revision or timeline since.+ */+export async function sealPageTextProjection(engine: BrainEngine, slug: string, sourceId: string, guarded?: PageSnapshot): Promise<void> {+ const current = guarded ?? await engine.readPageSnapshot(slug, { sourceId });if (!current) return;await engine.executeRaw(`UPDATE pages SET text_projection_revision=knowledge_revision,search_vector=setweight(to_tsvector('${getFtsLanguage()}',COALESCE(title,'')),'A') ||@@ -103,14 +107,20 @@ export async function readProjectionSnapshot(engine: BrainEngine, slug: string,opts: { allowUnsealed?: boolean; maxChunkTokens?: number; requireLiveSource?: boolean } = {}): Promise<ProjectionSnapshot | null> {return engine.transaction(async tx => {await tx.lockPageKeys([{ sourceId, slug }]);- const snapshot = await tx.readPageSnapshot(slug, { sourceId, ...(opts.requireLiveSource && { requireLiveSource: true }) });- if (!snapshot || (!opts.allowUnsealed && snapshot.page.text_projection_revision !== snapshot.revision)) return null;- const context = await indexingContext(tx, snapshot, opts.maxChunkTokens);- return { snapshot, chunks: await tx.getChunks(slug, { sourceId, includeUnsealed: true }), indexingContext: context.key,- embeddingModel: context.model, embeddingColumn: context.column, maxChunkTokens: context.maxChunkTokens, maxChunkTokensOverride: opts.maxChunkTokens, pageKind: context.pageKind };+ return readGuardedProjectionSnapshot(tx, slug, sourceId, opts);});}+/** readProjectionSnapshot for a caller whose transaction already holds the page guard. */+async function readGuardedProjectionSnapshot(tx: BrainEngine, slug: string, sourceId: string,+ opts: { allowUnsealed?: boolean; maxChunkTokens?: number; requireLiveSource?: boolean }): Promise<ProjectionSnapshot | null> {+ const snapshot = await tx.readPageSnapshot(slug, { sourceId, ...(opts.requireLiveSource && { requireLiveSource: true }) });+ if (!snapshot || (!opts.allowUnsealed && snapshot.page.text_projection_revision !== snapshot.revision)) return null;+ const context = await indexingContext(tx, snapshot, opts.maxChunkTokens);+ return { snapshot, chunks: await tx.getChunks(slug, { sourceId, includeUnsealed: true }), indexingContext: context.key,+ embeddingModel: context.model, embeddingColumn: context.column, maxChunkTokens: context.maxChunkTokens, maxChunkTokensOverride: opts.maxChunkTokens, pageKind: context.pageKind };+}+/** No provider work under the guard. Delayed derived results lose to newer content. */export async function installPageProjection(engine: BrainEngine, prepared: ProjectionSnapshot, chunks: ChunkInput[], opts: { seal?: boolean; signature?: string; preserveEmbeddings?: boolean; code?: Awaited<ReturnType<typeof prepareCodeChunks>> } = {}): Promise<void> {const { snapshot } = prepared;@@ -166,7 +176,7 @@ export async function installPageProjection(engine: BrainEngine, prepared: Projeif (opts.seal) {await tx.executeRaw(`UPDATE pages SET chunker_version=$3WHERE source_id=$1 AND slug=$2`, [sourceId, slug, MARKDOWN_CHUNKER_VERSION]);- await sealPageTextProjection(tx, slug, sourceId);+ await sealPageTextProjection(tx, slug, sourceId, current!);await tx.executeRaw('DELETE FROM page_projection_jobs WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', [snapshot.sourceIncarnation, slug, snapshot.revision]);}if (opts.signature) await tx.setPageEmbeddingSignature(slug, { sourceId, signature: opts.signature });@@ -276,12 +286,28 @@ export async function preparePageProjection(prepared: ProjectionSnapshot) {return { chunks: await prepareMarkdownChunks(page, prepared.maxChunkTokens), code: undefined };}+// The job queue is usually empty or small while pages grows without bound, so+// these reads walk jobs and probe sources/pages per job. The OFFSET 0 fences+// keep the planner from turning the probes back into a scan of pages; PGLite+// has no autovacuum to give it accurate queue statistics.+const PROJECTION_JOB_PROBES = `CROSS JOIN LATERAL (SELECT s.id FROM sources s+ WHERE s.incarnation=j.source_incarnation AND NOT s.archived OFFSET 0) s+ CROSS JOIN LATERAL (SELECT p.page_kind FROM pages p WHERE p.source_id=s.id AND p.slug=j.slug+ AND p.deleted_at IS NULL AND p.page_kind IN ('markdown','code') OFFSET 0) p`;++/**+ * Rebuilds between statistics refreshes, per engine. Like autovacuum's analyze+ * threshold, a refresh is due once 50 rows plus 10% of the table changed; a+ * process's first drained rebuild always refreshes.+ */+const statisticsDebt = new WeakMap<BrainEngine, { rebuilt: number; rows: number | null }>();+/** Bounded and keyless. Unsupported media remains queued for its source importer. */export async function rebuildPendingPageProjections(engine: BrainEngine, limit = 20): Promise<{ rebuilt: number; superseded: number }> {const jobs = await engine.executeRaw<{ source_id: string; source_incarnation: string; slug: string; revision: string; page_kind: string }>(`SELECT s.id AS source_id,j.source_incarnation,j.slug,j.revision,p.page_kind- FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation- JOIN pages p ON p.source_id=s.id AND p.slug=j.slug- WHERE p.deleted_at IS NULL AND NOT s.archived AND p.page_kind IN ('markdown','code')+ FROM (SELECT source_incarnation,slug,revision,updated_at FROM page_projection_jobs+ ORDER BY updated_at,source_incarnation,slug OFFSET 0) j+ ${PROJECTION_JOB_PROBES}ORDER BY j.updated_at,j.source_incarnation,j.slug LIMIT $1`, [Math.max(1, Math.min(limit, 100))]);let rebuilt = 0;let superseded = 0;@@ -291,7 +317,7 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =const pending = await tx.executeRaw(`SELECT 1 FROM page_projection_jobsWHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, [job.source_incarnation, job.slug, job.revision]);if (!pending.length) return null;- return readProjectionSnapshot(tx, job.slug, job.source_id, { allowUnsealed: true });+ return readGuardedProjectionSnapshot(tx, job.slug, job.source_id, { allowUnsealed: true });});if (!prepared || prepared.snapshot.sourceIncarnation !== job.source_incarnation || prepared.snapshot.revision !== job.revision) { superseded++; continue; }try {@@ -309,11 +335,18 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =}}if (rebuilt > 0) {+ const debt = statisticsDebt.get(engine);+ const owed = { rebuilt: (debt?.rebuilt ?? 0) + rebuilt, rows: debt?.rows ?? null };+ statisticsDebt.set(engine, owed);+ if (owed.rows !== null && owed.rebuilt < 50 + owed.rows * 0.1) return { rebuilt, superseded };const remaining = await engine.executeRaw(`SELECT 1 FROM page_projection_jobs j- JOIN sources s ON s.incarnation=j.source_incarnation JOIN pages p ON p.source_id=s.id AND p.slug=j.slug- WHERE p.deleted_at IS NULL AND NOT s.archived AND p.page_kind IN ('markdown','code')- AND j.reason<>'rebuild_failed' LIMIT 1`);- if (!remaining.length) await refreshProjectionStatistics(engine);+ ${PROJECTION_JOB_PROBES}+ WHERE j.reason<>'rebuild_failed' LIMIT 1`);+ if (!remaining.length) {+ await refreshProjectionStatistics(engine);+ const [pages] = await engine.executeRaw<{ rows: number }>("SELECT GREATEST(reltuples,0)::float8 AS rows FROM pg_class WHERE oid='pages'::regclass");+ statisticsDebt.set(engine, { rebuilt: 0, rows: Number(pages?.rows ?? 0) });+ }}return { rebuilt, superseded };}diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.tsindex 8b612e4c75..2949e96bb3 100644--- a/src/core/page-state/snapshot.ts+++ b/src/core/page-state/snapshot.ts@@ -19,12 +19,14 @@ export async function overlayCanonicalBodies(query: ReadQuery, body: string, tim/** One MVCC statement binds content, tags, identity and withdrawals to one revision. */export async function readPageSnapshot(query: ReadQuery, slug: string, opts?: PageSnapshotOptions): Promise<PageSnapshot | null> {- const params: unknown[] = [slug, opts?.resolveAlias === true];- const where = [`(p.slug=$1 OR ($2::boolean- ${opts?.preserveExactIdentity ? 'AND NOT EXISTS (SELECT 1 FROM pages exact_page WHERE exact_page.source_id=p.source_id AND exact_page.slug=$1)' : ''}- AND EXISTS (SELECT 1 FROM slug_aliases a+ const params: unknown[] = [slug];+ // Alias resolution is part of the statement text, not a parameter, so a+ // cached plan for an exact-slug read keeps using the slug index.+ const where = [opts?.resolveAlias === true ? `(p.slug=$1 OR (+ ${opts?.preserveExactIdentity ? 'NOT EXISTS (SELECT 1 FROM pages exact_page WHERE exact_page.source_id=p.source_id AND exact_page.slug=$1) AND' : ''}+ EXISTS (SELECT 1 FROM slug_aliases aWHERE a.alias_slug=$1 AND a.source_id=p.source_id AND a.canonical_slug=p.slug- AND EXISTS (SELECT 1 FROM sources alias_source WHERE alias_source.id=a.source_id ${opts?.includeDeleted ? '' : 'AND NOT alias_source.archived'}))))`];+ AND EXISTS (SELECT 1 FROM sources alias_source WHERE alias_source.id=a.source_id ${opts?.includeDeleted ? '' : 'AND NOT alias_source.archived'}))))` : 'p.slug=$1'];if (opts?.sourceIds?.length) {params.push(opts.sourceIds);where.push(`p.source_id=ANY($${params.length}::text[])`);diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 6e78ce1951..6a6de27bcd 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -1,6 +1,6 @@import type { BrainEngine, ReservedConnection } from '../engine.ts';import type { GBrainConfig } from '../config.ts';-import { claimNextWrite, compactWriteReceipts, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim } from './journal.ts';+import { claimNextWrite, compactWriteReceipts, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';import { finishUnpublishedFailure, publishMutation, recoverPublication, type PreparedMutation } from './coordinator.ts';import { localHostId } from './identity.ts';import { isTerminal, type WriteRequest } from './model.ts';@@ -33,6 +33,10 @@ export class PersistenceConsumer {private topologyWorker: Promise<unknown> | undefined;private maintenanceWorker: Promise<unknown> | undefined;private nextMaintenance = 0;+ private publishedSinceMaintenance = 0;+ private maintenanceVolume = 50;+ private lastScan = 0;+ private progressWake = false;private lastError: { code: string; at: string; phase?: string } | undefined;private abort = new AbortController();private phaseObservation: { name: string; started_at: string; deadline_exceeded: boolean; attempt: number } | undefined;@@ -47,8 +51,12 @@ export class PersistenceConsumer {this.hostId = opts.hostId ?? localHostId();}start(): void { this.stopping = false; this.abort = new AbortController(); this.fullTickRequested = true; this.idleDelayMs = this.pollMs; this.schedule(0); }- /** Work admitted by this process: run a full tick now instead of waiting out the idle backoff. */- wake(): void { this.idleDelayMs = this.pollMs; this.schedule(0); }+ /**+ * Work admitted by this process: tick now instead of waiting out the idle+ * backoff. Like a completed publication, it claims at once and leaves scans+ * to at most one pass per poll interval.+ */+ wake(): void { this.progressWake = true; this.idleDelayMs = this.pollMs; this.schedule(0); }private get pollMs(): number { return this.opts.pollMs ?? 250; }private get idleMaxMs(): number { return Math.max(this.pollMs, this.opts.idleMaxMs ?? 5000); }private schedule(ms: number): void {@@ -60,7 +68,9 @@ export class PersistenceConsumer {this.timerDueAt = Date.now() + ms;this.timer = setTimeout(() => {this.timer = undefined;- void this.tick().finally(() => { const next = this.nextDelayMs ?? this.pollMs; this.nextDelayMs = undefined; this.schedule(next); });+ const afterProgress = this.progressWake;+ this.progressWake = false;+ void this.tick(afterProgress).finally(() => { const next = this.nextDelayMs ?? this.pollMs; this.nextDelayMs = undefined; this.schedule(next); });}, ms);this.timer.unref?.();}@@ -169,15 +179,21 @@ export class PersistenceConsumer {throw error;} finally { signal.removeEventListener('abort', onAbort); }}- async tick(): Promise<void> {+ /**+ * `afterProgress` marks the wake-up that follows a completed publication+ * or a local admission. Those ticks claim the next write at once and leave+ * root refresh and recovery/expiry/topology scans to at most one pass per+ * poll interval, the same bound an idle owner has.+ */+ async tick(afterProgress = false): Promise<void> {if (this.tickPromise) return this.tickPromise;- this.tickPromise = this.doTick().catch(error => { this.report(error); }).finally(() => {+ this.tickPromise = this.doTick(afterProgress).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> {+ private async doTick(afterProgress: boolean): Promise<void> {if (this.stopping) return;const requested = this.fullTickRequested || this.active.size > 0;this.fullTickRequested = false;@@ -208,19 +224,26 @@ export class PersistenceConsumer {await this.releaseIdleLane();this.idleDelayMs = this.pollMs;this.nextDelayMs = this.pollMs;- await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,- this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));+ const scan = !afterProgress || Date.now() - this.lastScan >= this.pollMs;+ if (scan) {+ this.lastScan = Date.now();+ await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,+ this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));+ }if (this.stopping) return;- if (!this.topologyWorker) this.topologyWorker = import('./topology-recovery.ts')+ if (scan && !this.topologyWorker) this.topologyWorker = import('./topology-recovery.ts').then(({ recoverSourceTopologies }) => recoverSourceTopologies(this.engine, { hostId: this.hostId, limit: 2,onAttempt: (id, recovered) => { if (recovered) this.topologyRetryAfter.delete(id); else this.topologyRetryAfter.set(id, Date.now() + 30_000); } })).catch(error => this.report(error)).finally(() => { this.topologyWorker = undefined; });- if (!this.effectsWorker) this.effectsWorker = runPersistenceEffects(this.engine, this.config,- { hostId: this.hostId, limit: 2, signal: this.abort.signal }).catch(error => this.report(error))+ if (!this.effectsWorker) this.effectsWorker = this.drainEffects().catch(error => this.report(error)).finally(() => { this.effectsWorker = undefined; });- if (!this.maintenanceWorker && Date.now() >= this.nextMaintenance) {+ // Queue upkeep also follows publication volume, like autovacuum's scale+ // factor, so a busy owner never plans against a much smaller queue.+ if (!this.maintenanceWorker && (Date.now() >= this.nextMaintenance || this.publishedSinceMaintenance >= this.maintenanceVolume)) {this.nextMaintenance = Date.now() + 60_000;- this.maintenanceWorker = compactWriteReceipts(this.engine).catch(error => this.report(error))+ this.publishedSinceMaintenance = 0;+ this.maintenanceWorker = compactWriteReceipts(this.engine).then(() => vacuumPersistenceQueues(this.engine))+ .then(rows => { this.maintenanceVolume = 50 + Math.ceil(rows * 0.2); }).catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });}if (!this.projectionWorker) this.projectionWorker = rebuildPendingPageProjections(this.engine, 2)@@ -229,35 +252,37 @@ export class PersistenceConsumer {// proves that a previous process can no longer be publishing this root.const now = Date.now();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.phase('recovery_scan', signal => 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[]))- AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier WHERE earlier.worktree_id=r.worktree_id- AND earlier.recovery IS NOT NULL AND earlier.sequence<r.sequence)- ORDER BY r.updated_at,r.sequence LIMIT 16`, [this.hostId, excluded], { signal }));- for (const row of recovery) {- const root = row.worktree_id!;- // 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.rootRetryAfter.set(root, Date.now() + delay);- try {- const recovered = await this.phase('recovery', () => recoverPublication(this.engine, row.id, this.hostId));- 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.rootRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));- this.report(error);+ if (scan) {+ const excluded = [...this.activeRoots, ...this.rootRetryAfter.keys()];+ const recovery = await this.phase('recovery_scan', signal => 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[]))+ AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier WHERE earlier.worktree_id=r.worktree_id+ AND earlier.recovery IS NOT NULL AND earlier.sequence<r.sequence)+ ORDER BY r.updated_at,r.sequence LIMIT 16`, [this.hostId, excluded], { signal }));+ for (const row of recovery) {+ const root = row.worktree_id!;+ // 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.rootRetryAfter.set(root, Date.now() + delay);+ try {+ const recovered = await this.phase('recovery', () => recoverPublication(this.engine, row.id, this.hostId));+ 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.rootRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));+ this.report(error);+ }}+ await this.phase('expired_claims', signal => this.engine.executeRaw(`WITH expired AS (+ SELECT r.id FROM persistence_requests r WHERE r.state='running' AND r.recovery IS NULL+ AND r.publication_started=false AND r.claim_expires_at<now() AND ${PERSISTENCE_PROTOCOL_PREDICATE}+ AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))+ ORDER BY r.sequence LIMIT 100 FOR UPDATE OF r SKIP LOCKED)+ UPDATE persistence_requests r SET state='queued',execution_token=NULL,claim_expires_at=NULL+ FROM expired WHERE r.id=expired.id`, [this.hostId], { signal }));}- await this.phase('expired_claims', signal => this.engine.executeRaw(`WITH expired AS (- SELECT r.id FROM persistence_requests r WHERE r.state='running' AND r.recovery IS NULL- AND r.publication_started=false AND r.claim_expires_at<now() AND ${PERSISTENCE_PROTOCOL_PREDICATE}- AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))- ORDER BY r.sequence LIMIT 100 FOR UPDATE OF r SKIP LOCKED)- UPDATE persistence_requests r SET state='queued',execution_token=NULL,claim_expires_at=NULL- FROM expired WHERE r.id=expired.id`, [this.hostId], { signal }));if (publicationConcurrency(this.engine) === 0) {await this.phase('capacity', signal => this.engine.executeRaw(`UPDATE persistence_requests SET blocked_reason='writer_pool_capacity'WHERE state='queued' AND blocked_reason IS DISTINCT FROM 'writer_pool_capacity' AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, undefined, { signal }));@@ -276,11 +301,18 @@ export class PersistenceConsumer {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));+ else { this.progressWake = true; this.publishedSinceMaintenance++; }this.active.delete(task); this.activeRoots.delete(key); this.schedule(progressed ? 0 : this.opts.pollMs ?? 250);});this.active.add(task);}}+ /** Effects keep pace with publication: full batches continue without waiting for the next tick. */+ private async drainEffects(): Promise<void> {+ const limit = 20;+ while (!this.stopping && await runPersistenceEffects(this.engine, this.config,+ { hostId: this.hostId, limit, signal: this.abort.signal }) >= limit);+ }foregroundCompletions(worktreeId: string): number { return this.foregroundCounts.get(worktreeId) ?? 0; }status() {return { accepting: !this.stopping, active_preparations: this.active.size, active_worktrees: this.activeRoots.size,diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 2c3ee6a90b..4d5c87a5c5 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -235,7 +235,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, proutcome.persistence = { mode: files.length ? 'filesystem' : 'database', ...(files.length ? { file_written: !prepared.noop } : {}), ...(skill ? { git_state: 'not_requested' } : {}) };outcome.write_through = files.length ? { written: !prepared.noop } : { written: false, skipped: prepared.databaseOnlyReason ?? row.authority.databaseOnlyReason ?? 'no_repo_configured' };if (row.operation === 'put_page' && row.authority.remote && row.authority.databaseOnlyReason === 'no_repo_configured') outcome.write_through = withNoRepoWriteThroughWarning(outcome.write_through as { written: boolean; skipped?: string }, row.source_id);- await queuePublicationEffects(tx, row, final?.revision, outcome, prepared);+ await queuePublicationEffects(tx, row, final, outcome, prepared);await hooks.boundary?.('before_commit', row);const committed = await completeWrite(tx, current, 'committed', outcome);transactionBodyCompleted = true;diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.tsindex b2193144e0..46fd1ebac8 100644--- a/src/core/persistence/effect-git.ts+++ b/src/core/persistence/effect-git.ts@@ -1,7 +1,7 @@import { execFile } from 'node:child_process';import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';import { dirname, join, relative, resolve as resolvePath, sep } from 'node:path';-import { isDurabilityHardened } from '../brain-repo-durability.ts';+import { isDurabilityHardenedAsync } from '../brain-repo-durability.ts';import { OperationError } from '../ops/contract.ts';import { persistenceHome } from './identity.ts';import { nativeFileTarget } from './native-file-target.ts';@@ -19,9 +19,14 @@ function git(root: string, hooks: string, args: string[], signal?: AbortSignal):});}-/** Caller owns the native worktree lock. Never run pull, rebase, or legacy hooks. */-export async function publishGitEffect(root: string, relativePath: string, signal?: AbortSignal): Promise<Record<string, unknown>> {- if (!isDurabilityHardened(root)) return { git: 'skipped', reason: 'durability_not_enabled', push: 'skipped' };+/**+ * Caller owns the native worktree lock. Never run pull, rebase, or legacy hooks.+ * `hardened` is the caller's durability probe of `root`, taken before it locked+ * the worktree.+ */+export async function publishGitEffect(root: string, relativePath: string, signal?: AbortSignal,+ hardened?: boolean): Promise<Record<string, unknown>> {+ if (!(hardened ?? await isDurabilityHardenedAsync(root))) return { git: 'skipped', reason: 'durability_not_enabled', push: 'skipped' };const path = nativeFileTarget(root, resolvePath(root, relativePath), 'git_target_unsafe');relativePath = relative(root, path).split(sep).join('/');const base = join(persistenceHome(), 'empty-hooks');diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex 034602cf0e..09295ba874 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -1,6 +1,7 @@import { randomUUID } from 'node:crypto';import { relative, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';+import type { PageSnapshot } from '../page-state/types.ts';import { OperationError } from '../ops/contract.ts';import type { PreparedMutation } from './coordinator.ts';import { sha256 } from './digest.ts';@@ -10,11 +11,12 @@ import { isFactsExtractionEnabled } from '../facts/extract.ts';import { resolveDefaultVisibility } from '../facts/visibility.ts';import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';-export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest, revision: string | undefined,+/** `snapshot` is the publication's final read of the page, including deleted rows, in this transaction. */+export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest, snapshot: PageSnapshot | null,outcome: Record<string, unknown>, prepared?: PreparedMutation): Promise<void> {if (prepared?.noop || prepared?.target === 'skill_bundle') return;await declarePersistenceProtocol(tx);- const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ const revision = snapshot?.revision;const data = { slug: row.slug, page_id: snapshot?.page.id };const queue = async (kind: EffectKind, extra: Record<string, unknown> = {}) => tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,revision,data,source_id,source_incarnation,worktree_id)diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex 0624ba6ba2..1610aed677 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -27,6 +27,7 @@ import { isSourceDbOnlySlug } from './source-storage.ts';import { advanceEffectCursor, claimPersistenceEffect, completeEffect, failEffect, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect } from './effect-journal.ts';import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';import { publishGitEffect } from './effect-git.ts';+import { isDurabilityHardenedAsync } from '../brain-repo-durability.ts';import { dispatchFactsBackstopEffect } from './effect-facts.ts';import { PARK_AFTER_FAILURES, type EffectRecovery, type PersistenceEffect } from './effect-model.ts';import { recoveryStagingFile } from './staging.ts';@@ -112,11 +113,14 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindinawait recoverEffectPublication(engine, effect, opts.hostId, opts);}-async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions, attempt: EffectAttempt): Promise<void> {+async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions,+ attempt: EffectAttempt, hardened: boolean | undefined): Promise<void> {if (!binding?.local_path) { await completeEffect(engine, effect, { git: 'skipped', reason: 'no_repo_configured' }); return; }- const snapshot = await selectedEffectPage(engine, effect);+ // Only a page walk reads snapshots; a single-file effect completes by its recorded hash.+ const walk = targetedWithdrawalEffect(effect) || effect.data.source_scan;+ const snapshot = walk ? await selectedEffectPage(engine, effect) : null;let path: string;- if (targetedWithdrawalEffect(effect) || effect.data.source_scan) {+ if (walk) {if (!snapshot) { await completeEffect(engine, effect); return; }attempt.target = snapshot.page.slug;const file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,@@ -142,7 +146,7 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:await finishPage(engine, effect, snapshot, { git: 'skipped', reason: 'db_only' });return;}- const result = await publishGitEffect(binding.local_path, relative(binding.local_path, path).split(sep).join('/'), opts.signal);+ const result = await publishGitEffect(binding.local_path, relative(binding.local_path, path).split(sep).join('/'), opts.signal, hardened);if (result.reason === 'durability_not_enabled') await completeEffect(engine, effect, result);else await finishPage(engine, effect, snapshot, result);}@@ -316,13 +320,16 @@ async function parkEffectTarget(engine: BrainEngine, effect: PersistenceEffect,...(remaining.length ? { retry_slugs: remaining, target_failures: PARK_AFTER_FAILURES - 1 } : {}) }, code, 0);}-/** Bounded, idempotent work. Recovery obtains kernel exclusion before a DB claim. */-export async function runPersistenceEffects(engine: BrainEngine, config: GBrainConfig, opts: EffectWorkerOptions): Promise<void> {+/**+ * Bounded, idempotent work. Recovery obtains kernel exclusion before a DB claim.+ * Resolves with the number of effects attempted, so a caller can keep draining.+ */+export async function runPersistenceEffects(engine: BrainEngine, config: GBrainConfig, opts: EffectWorkerOptions): Promise<number> {const limit = Math.max(1, Math.min(opts.limit ?? 2, 20));const recoveries = await selectEffectRecoveries(engine, opts.hostId, limit);let attempted = 0;for (const recovery of recoveries) {- if (opts.signal?.aborted) return;+ if (opts.signal?.aborted) return attempted;const binding = await getWorktreeBinding(engine, recovery.source_id, opts.hostId);if (!binding) continue;const lock = await acquireWorktree(binding, 0, undefined, engine);@@ -337,18 +344,20 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC} catch (error) { if (claimed) await recordFailure(engine, claimed, error); }finally { await lock.release(); }}- while (attempted++ < limit && !opts.signal?.aborted) {- const claimed = await claimPersistenceEffect(engine, opts.hostId);- if (!claimed) return;+ const run = async (claimed: PersistenceEffect, binding: WorktreeBinding | null, hardened?: boolean) => {let effect = claimed;const attempt: EffectAttempt = {};let lock: Awaited<ReturnType<typeof acquireWorktree>> = null;+ // A single-file git effect in a repository without the durability hook+ // runs no git command and only records its outcome: acquiring the lock+ // still proves the owned root, but it is not held while recording.+ const recordOnly = effect.kind === 'git' && hardened === false && !targetedWithdrawalEffect(effect) && !effect.data.source_scan;try {- const binding = effect.worktree_id ? await getWorktreeBinding(engine, effect.source_id, opts.hostId) : null;if (effect.worktree_id && !['embedding', 'facts-backstop'].includes(effect.kind)) {if (!binding) throw new OperationError('owner_unavailable', 'The canonical effect owner is unavailable.');lock = await acquireWorktree(binding, 0, undefined, engine);if (!lock) throw new OperationError('writer_busy', 'The canonical worktree is busy.');+ if (recordOnly) { await lock.release(); lock = null; }}await engine.transaction(async tx => {await guardEffectSource(tx, effect, opts.hostId);@@ -359,10 +368,36 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC});effect = await upgradeWithdrawalEffect(engine, effect, opts.hostId);if (effect.kind === 'withdrawal-mirror') await mirrorPage(engine, effect, binding, opts, attempt);- else if (effect.kind === 'git') await gitPage(engine, effect, binding, opts, attempt);+ else if (effect.kind === 'git') await gitPage(engine, effect, binding, opts, attempt, hardened);else if (effect.kind === 'facts-backstop') await dispatchFactsBackstopEffect(engine, effect, opts.hostId);else await embedPage(engine, config, effect, opts);} catch (error) { await recordFailure(engine, effect, error, opts.signal, attempt.target); }finally { await lock?.release(); }+ };+ // A git effect first needs its durability probe (git child processes, one+ // probe per root per run). The probe runs while the rest of the batch+ // proceeds; git effects then run in claim order, never holding a worktree+ // lock while they wait for it.+ const probes = new Map<string, Promise<boolean>>();+ const deferred: { effect: PersistenceEffect; binding: WorktreeBinding; hardened: Promise<boolean> }[] = [];+ // A deferred effect that requeues itself (a page walk advancing its cursor,+ // or work unblocked by an earlier effect) is claimable again after the flush.+ for (;;) {+ while (attempted < limit && !opts.signal?.aborted) {+ const effect = await claimPersistenceEffect(engine, opts.hostId);+ if (!effect) break;+ attempted++;+ let binding: WorktreeBinding | null = null;+ try {+ if (effect.worktree_id && !['embedding', 'facts-backstop'].includes(effect.kind)) binding = await getWorktreeBinding(engine, effect.source_id, opts.hostId);+ } catch (error) { await recordFailure(engine, effect, error, opts.signal); continue; }+ if (effect.kind === 'git' && binding?.local_path) {+ const root = binding.local_path;+ if (!probes.has(root)) probes.set(root, isDurabilityHardenedAsync(root));+ deferred.push({ effect, binding, hardened: probes.get(root)! });+ } else await run(effect, binding);+ }+ if (!deferred.length) return attempted;+ for (const { effect, binding, hardened } of deferred.splice(0)) await run(effect, binding, await hardened);}}diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex c8323caba5..c82d8593e3 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -152,8 +152,9 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overRETURNING *`, [input.principal.kind, input.principal.id, requestId, input.operation, input.sourceId,input.sourceIncarnation, input.pageId ?? null, input.slug, input.worktreeId ?? null, input.topologyGeneration ?? null,fingerprint, JSON.stringify(input.intent), JSON.stringify(input.authority), bytes, terminalBytes, input.targetKind ?? 'page', input.protocolVersion ?? 1]);- for (const c of counters) await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count+1,- intent_bytes=intent_bytes+$2,lifetime_ids=lifetime_ids+1,terminal_bytes=terminal_bytes+$3 WHERE key=$1`, [c.key, bytes, terminalBytes]);+ await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count+1,+ intent_bytes=intent_bytes+$2,lifetime_ids=lifetime_ids+1,terminal_bytes=terminal_bytes+$3 WHERE key=ANY($1::text[])`,+ [counters.map(c => c.key), bytes, terminalBytes]);return row;} };}@@ -213,7 +214,7 @@ export async function prepareRecovery(engine: BrainEngine, row: WriteRequest, refor (const c of counters) if (Number(c.recovery_bytes) + bytes > (c.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes)) throw capacityError('recovery bytes currently reserved by other requests');await tx.executeRaw(`UPDATE persistence_requests SET recovery=$3::text::jsonb,recovery_bytes=$4,updated_at=now()WHERE id=$1::uuid AND execution_token=$2::uuid`, [row.id, row.execution_token, JSON.stringify(recovery), bytes]);- for (const c of counters) await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes+$2 WHERE key=$1', [c.key, bytes]);+ await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes+$2 WHERE key=ANY($1::text[])', [counters.map(c => c.key), bytes]);});}@@ -236,8 +237,8 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'coconst [done] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb,error_code=$4,error_message=$5,completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULLWHERE id=$1::uuid RETURNING *`, [row.id, state, JSON.stringify(outcome), error?.code ?? null, error?.message ?? null]);- for (const key of ['brain', principalKey(requestPrincipal(row))]) await tx.executeRaw(`UPDATE persistence_counters- SET outstanding_count=outstanding_count-1,intent_bytes=intent_bytes-$2 WHERE key=$1`, [key, Number(current.intent_bytes)]);+ await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count-1,intent_bytes=intent_bytes-$2+ WHERE key=ANY($1::text[])`, [['brain', principalKey(requestPrincipal(row))], Number(current.intent_bytes)]);// Recovery bytes remain reserved until physical cleanup has been verified.return done;}@@ -253,7 +254,7 @@ export async function clearResolvedRecovery(engine: BrainEngine, id: string): Prconst [locked] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [id]);if (!locked?.recovery || !isTerminal(locked)) return;for (const file of recoveryFiles(locked.recovery)) assertRecoveryStagingAbsent(file);- for (const key of keys) await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes-$2 WHERE key=$1', [key, Number(locked.recovery_bytes)]);+ await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes-$2 WHERE key=ANY($1::text[])', [keys, Number(locked.recovery_bytes)]);await tx.executeRaw('UPDATE persistence_requests SET recovery=NULL,recovery_bytes=0,blocked_reason=NULL WHERE id=$1::uuid', [id]);});}@@ -262,6 +263,18 @@ export async function markRecovering(engine: SqlEngine, row: WriteRequest, reasoerror_code=COALESCE(error_code,$4),error_message=COALESCE(error_message,$5)WHERE id=$1::uuid AND execution_token=$2::uuid AND state IN ('running','recovering') AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [row.id, row.execution_token, reason, failure?.code ?? null, failure?.message ?? null]);}+/**+ * PGLite has no autovacuum. The resident owner reclaims queue churn and keeps+ * planner statistics current, so receipt lookups keep using the request-id+ * index and claims do not walk dead queue entries.+ */+export async function vacuumPersistenceQueues(engine: BrainEngine): Promise<number> {+ if (engine.kind !== 'pglite') return 0;+ await engine.executeRaw('VACUUM (ANALYZE) persistence_requests, persistence_effects, persistence_counters, page_projection_jobs, page_write_guards');+ const [requests] = await engine.executeRaw<{ rows: number }>("SELECT GREATEST(reltuples,0)::float8 AS rows FROM pg_class WHERE oid='persistence_requests'::regclass");+ return Number(requests?.rows ?? 0);+}+export async function compactWriteReceipts(engine: BrainEngine, retentionDays?: number): Promise<number> {retentionDays ??= await readReceiptRetentionDays(engine);if (!Number.isFinite(retentionDays) || retentionDays < 0) throw new TypeError('Invalid receipt retention.');diff --git a/src/core/persistence/root-registry.ts b/src/core/persistence/root-registry.tsindex df22c95db9..e03e145157 100644--- a/src/core/persistence/root-registry.ts+++ b/src/core/persistence/root-registry.ts@@ -36,13 +36,15 @@ function syncDirectory(directory: string): void {if (!(process.platform === 'win32' && ['EISDIR', 'EPERM', 'EINVAL', 'ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? ''))) throw error;} finally { if (fd !== undefined) closeSync(fd); }}-function writePrivateRecord(file: string, value: string): void {- if (existsSync(file) && readFileSync(file, 'utf8') === value) { chmodSync(file, 0o600); return; }+/** Returns whether the record changed; a changed record is already durable with its directory entry. */+function writePrivateRecord(file: string, value: string): boolean {+ if (existsSync(file) && readFileSync(file, 'utf8') === value) { chmodSync(file, 0o600); return false; }const temporary = `${file}.${randomUUID()}.tmp`;const fd = openSync(temporary, 'wx', 0o600);try { writeFileSync(fd, value); fsyncSync(fd); } finally { closeSync(fd); }try { renameSync(temporary, file); syncDirectory(dirname(file)); }finally { try { unlinkSync(temporary); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } }+ return true;}function markerExists(path: string): boolean {try { lstatSync(path); return true; }@@ -98,20 +100,21 @@ export function recordManagedRoots(brainId: string, records: ManagedRootRecord[]if (!/^[a-f0-9-]{36}$/i.test(brainId)) throw new OperationError('storage_error', 'Invalid managed-root brain identity.');if (!records.length) return;const directory = registryDirectory(); mkdirSync(directory, { recursive: true, mode: 0o700 }); chmodSync(directory, 0o700);+ let changed = false;for (const record of records) {const root = canonicalFilesystemPath(record.local_path);const key = createHash('sha256').update(root).digest('hex');const file = join(directory, `${brainId}.${key}.json`);const value = JSON.stringify({ version: 1, brain_id: brainId, root, ...record, local_path: root,...(record.topology_generation != null ? { topology_generation: String(record.topology_generation) } : {}) });- writePrivateRecord(file, value);+ changed = writePrivateRecord(file, value) || changed;if (existsSync(root) && statSync(root).isDirectory()) {const metadata = enclosingGitMetadata(root);const marker = metadata ? join(metadata, 'gbrain-managed.json') : join(root, '.gbrain-managed');if (!existsSync(marker)) writePrivateRecord(marker, JSON.stringify({ version: 1, managed: true, brain_id: brainId }));}}- syncDirectory(directory);+ if (changed) syncDirectory(directory);}/** Available before connect, including while another process owns local PGLite. */export function registeredManagedRoots(): string[] {diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 7ed06a8219..f46fe21cb5 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -4,11 +4,12 @@ import { trackPgliteDatabase, PgliteClosingError, notifyPgliteOpened } from './pimport { mutatePageTag } from './page-state/tags.ts';import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';import { assertPageRevision } from './page-state/types.ts';-import { lockPageKeys as acquirePageKeys } from './page-state/guards.ts';+import { lockUnheldPageKeys, withHeldPageKeys, type HeldPageKeys } from './page-state/guards.ts';import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';import { createPageVersion } from './page-state/versions.ts';import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.ts';import { composablePgliteTransaction } from './page-state/transactions.ts';+import { dropRowTypeArrayParsers, PgliteStatementCache } from './pglite-statements.ts';import { GRANT_COLUMNS_SQL } from './grants/schema.ts';import type { PageReadScope } from './types.ts';import type { PageReadPolicy } from './types.ts';@@ -719,10 +720,12 @@ export class PGLiteEngine implements BrainEngine {}private _attachDatabase(database: PGLiteDB): PGLiteDB {- this._dbWork = trackPgliteDatabase(database);+ this._statements = new PgliteStatementCache(database);+ this._dbWork = trackPgliteDatabase(this._statements.attach(database, false));this._checkpointGuard = undefined;return this._dbWork.database;}+ private _statements: PgliteStatementCache | null = null;// #2034: captured at connect() so reconnect() can restore the same data dir// after a drop, matching PostgresEngine's _savedConfig contract.private _savedConfig: EngineConfig | null = null;@@ -762,7 +765,10 @@ export class PGLiteEngine implements BrainEngine {}this.vectorIterativeScan = undefined;const opening = this._connectInternal(config).then(async () => {- try { if (registerRoots) await registerManagedFilesystemEngine(this, config.database_path); }+ try {+ await dropRowTypeArrayParsers(this.db);+ if (registerRoots) await registerManagedFilesystemEngine(this, config.database_path);+ }catch (error) {try { await this._closeInternal(); }catch (closeError) {@@ -1004,6 +1010,7 @@ export class PGLiteEngine implements BrainEngine {if (lock?.acquired) await releaseLock(lock);this._lock = null;this._dbWork = null;+ this._statements = null;} finally {// A slow close keeps the watchdog armed until it actually settles. On a// failed close the lock is retained; callers must terminate the process.@@ -1709,14 +1716,15 @@ export class PGLiteEngine implements BrainEngine {}async transaction<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> {- const run = (db = this.db) => db.transaction(async handle => {- const tx = composablePgliteTransaction(handle);+ const run = (db = this.db) => withHeldPageKeys(this._pageTransaction ? this._heldPageKeys : null, held => db.transaction(async handle => {+ const tx = composablePgliteTransaction(this._statements?.attach(handle, true) ?? handle);const txEngine = Object.create(this) as PGLiteEngine;Object.defineProperty(txEngine, '_chunkWritesInTransaction', { value: true });Object.defineProperty(txEngine, '_pageTransaction', { value: true });+ Object.defineProperty(txEngine, '_heldPageKeys', { value: held });Object.defineProperty(txEngine, 'db', { get: () => tx });return fn(txEngine);- });+ }));if (this._pageTransaction || !this._dbWork) return run();const guard = this._checkpointGuard ??= new PgliteCheckpointGuard();return this._dbWork.admit(db => guard.runOutermost(sql => db.query(sql), () => run(db)));@@ -1737,8 +1745,9 @@ export class PGLiteEngine implements BrainEngine {async lockPageKeys(keys: readonly PageKey[]): Promise<void> {if (!this._pageTransaction) throw new Error('lockPageKeys requires engine.transaction()');- await acquirePageKeys(this, keys);+ await lockUnheldPageKeys(this, this._heldPageKeys!, keys);}+ private _heldPageKeys: HeldPageKeys | null = null;/*** v0.41.13 (#1309) — identity-based dedup pre-check.diff --git a/src/core/pglite-statements.ts b/src/core/pglite-statements.tsnew file mode 100644index 0000000000..2423cda174--- /dev/null+++ b/src/core/pglite-statements.ts@@ -0,0 +1,200 @@+import { protocol, types, type PGlite, type Results, type Transaction } from '@electric-sql/pglite';++type Field = { name: string; dataTypeID: number };+type BackendMessage = { name: string; dataTypeIDs?: number[]; fields?: (Field | string | null)[]; text?: string };+type Parser = (value: string, typeId: number) => unknown;+type ExclusiveDatabase = PGlite & {+ _checkReady(): Promise<void>;+ _runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>;+ _runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>;+};+interface Column { name: string; dataTypeID: number; parse: Parser | undefined }+interface Statement { name: string; paramTypes: number[]; columns: Column[] }++const { serialize } = protocol as unknown as {+ serialize: {+ parse(input: { name: string; text: string }): Uint8Array;+ describe(input: { type: 'S'; name: string }): Uint8Array;+ bind(input: { statement: string; values: (string | null)[] }): Uint8Array;+ execute(input: Record<string, never>): Uint8Array;+ close(input: { type: 'S'; name: string }): Uint8Array;+ sync(): Uint8Array;+ };+};+const defaultParsers = types.parsers as unknown as Record<number, Parser>;++/** Statements that can change a cached statement's result shape or drop session statements. */+const SHAPE_CHANGING = /^\s*(?:ALTER|CREATE|DROP|DO|DISCARD|DEALLOCATE)\b/i;+const TRANSACTION_CONTROL = /^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i;+/** Plan-cache errors that a fresh Parse resolves: changed result type, missing statement. */+const STALE_STATEMENT = new Set(['0A000', '26000']);++/** PGlite's parseResults for one statement, with parsers resolved once per prepared statement. */+function results(columns: Column[], messages: BackendMessage[]): Results {+ const rows: Record<string, unknown>[] = [];+ let affectedRows = 0;+ let completed = false;+ for (const message of messages) {+ if (message.name === 'dataRow') rows.push(Object.fromEntries(message.fields!.map((value, index) => {+ const column = columns[index];+ return [column.name, value === null || !column.parse ? value : column.parse(value as string, column.dataTypeID)];+ })));+ else if (message.name === 'commandComplete') {+ const [command, first, second] = message.text!.split(' ');+ affectedRows += command === 'INSERT' ? parseInt(second, 10)+ : ['UPDATE', 'DELETE', 'COPY', 'MERGE'].includes(command) ? parseInt(first, 10) : 0;+ completed = true;+ }+ }+ const fields = columns.map(({ name, dataTypeID }) => ({ name, dataTypeID }));+ return (completed ? { rows, fields, affectedRows } : { affectedRows: 0, rows: [], fields: [] }) as Results;+}++function concat(parts: Uint8Array[]): Uint8Array {+ const out = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));+ let offset = 0;+ for (const part of parts) { out.set(part, offset); offset += part.length; }+ return out;+}++/**+ * Named server-side statements for PGLite, the plan cache postgres.js already+ * gives the Postgres engine. PGlite's query() parses, plans, and describes+ * every call as an unnamed statement over five protocol round trips; a+ * statement seen twice is prepared once and later runs as one Bind/Execute/Sync+ * batch. PostgreSQL still replans on invalidation and rejects a changed result+ * shape, which drops the entry. Shape-changing SQL clears the cache.+ */+export class PgliteStatementCache {+ private statements = new Map<string, Statement>();+ private seen = new Set<string>();+ private retired: string[] = [];+ private next = 0;++ constructor(private readonly db: PGlite, private readonly capacity = 256) {}++ /** Route a PGlite handle's query/exec through the cache; transaction handles skip the outer mutex. */+ attach<T extends PGlite | Transaction>(handle: T, inTransaction: boolean): T {+ const query = handle.query.bind(handle);+ const exec = handle.exec.bind(handle);+ return new Proxy(handle, {+ get: (target, key) => {+ // An instance override (test seams, wrappers) owns the call; the+ // cache still serves whatever it delegates to through this proxy.+ if (!inTransaction && (key === 'query' || key === 'exec') && Object.hasOwn(target, key)) {+ return (Reflect.get(target, key, target) as (...args: unknown[]) => unknown).bind(target);+ }+ if (key === 'query') return (sql: string, params?: unknown[], options?: unknown) =>+ options !== undefined || (inTransaction && (target as Transaction).closed)+ ? this.observe(sql, () => query(sql, params as never[], options as never))+ : this.query(sql, params ?? [], inTransaction, () => query(sql, params as never[]));+ if (key === 'exec') return (sql: string, options?: unknown) => {+ if (!TRANSACTION_CONTROL.test(sql)) this.clear();+ return exec(sql, options as never);+ };+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as T;+ }++ clear(): void {+ for (const statement of this.statements.values()) this.retired.push(statement.name);+ this.statements.clear();+ this.seen.clear();+ }++ private observe<R>(sql: string, run: () => Promise<R>): Promise<R> {+ if (SHAPE_CHANGING.test(sql)) this.clear();+ return run();+ }++ private async query(sql: string, params: unknown[], inTransaction: boolean, unnamed: () => Promise<Results>): Promise<Results> {+ if (SHAPE_CHANGING.test(sql)) { this.clear(); return unnamed(); }+ if (!this.statements.has(sql) && !this.seen.has(sql)) {+ if (this.seen.size >= this.capacity * 4) this.seen.clear();+ this.seen.add(sql);+ return unnamed();+ }+ const db = this.db as ExclusiveDatabase;+ const run = () => db._runExclusiveQuery(async () => {+ let result: Results;+ try { result = await this.execute(sql, params); }+ catch (error) {+ if (!STALE_STATEMENT.has(String((error as { code?: unknown }).code))) throw error;+ this.forget(sql);+ if (inTransaction) throw error;+ result = await this.execute(sql, params);+ }+ if (!inTransaction) await db.syncToFs();+ return result;+ });+ if (inTransaction) return run();+ await db._checkReady();+ return db._runExclusiveTransaction(run);+ }++ private forget(sql: string): void {+ const statement = this.statements.get(sql);+ if (!statement) return;+ this.statements.delete(sql);+ this.retired.push(statement.name);+ }++ private async prepare(sql: string): Promise<Statement> {+ const cached = this.statements.get(sql);+ if (cached) {+ this.statements.delete(sql);+ this.statements.set(sql, cached);+ return cached;+ }+ if (this.statements.size >= this.capacity) this.forget(this.statements.keys().next().value!);+ const name = `gbrain_s${++this.next}`;+ const parts = this.retired.splice(0).map(retired => serialize.close({ type: 'S', name: retired }));+ parts.push(serialize.parse({ name, text: sql }), serialize.describe({ type: 'S', name }), serialize.sync());+ const { messages } = await this.protocol(concat(parts), sql, []);+ const parsers = this.db.parsers as unknown as Record<number, Parser>;+ const fields = (messages.find(message => message.name === 'rowDescription')?.fields ?? []) as Field[];+ const statement = { name,+ paramTypes: messages.find(message => message.name === 'parameterDescription')?.dataTypeIDs ?? [],+ columns: fields.map(({ name: column, dataTypeID }) => ({ name: column, dataTypeID,+ parse: parsers[dataTypeID] ?? defaultParsers[dataTypeID] })) };+ this.statements.set(sql, statement);+ return statement;+ }++ private async execute(sql: string, params: unknown[]): Promise<Results> {+ const statement = await this.prepare(sql);+ const serializers = this.db.serializers;+ const values = params.map((param, index) => {+ if (param === null || param === undefined) return null;+ const serializeParam = serializers[statement.paramTypes[index]];+ return serializeParam ? serializeParam(param) : String(param);+ });+ const { messages } = await this.protocol(concat([serialize.bind({ statement: statement.name, values }),+ serialize.execute({}), serialize.sync()]), sql, params);+ return results(statement.columns, messages);+ }++ private async protocol(message: Uint8Array, sql: string, params: unknown[]): Promise<{ messages: BackendMessage[] }> {+ try { return await this.db.execProtocol(message, { syncToFs: false }) as { messages: BackendMessage[] }; }+ catch (error) {+ // Same diagnostic fields PGlite's own query() attaches to a DatabaseError.+ if (error && typeof error === 'object' && 'code' in error) Object.assign(error, { query: sql, params, queryOptions: undefined });+ throw error;+ }+ }+}++/**+ * PGlite copies `db.parsers` into a fresh object for every query result. Its+ * array-type init registers one parser per composite (table row) array type,+ * most of the map in a gbrain schema, and gbrain never selects those arrays;+ * the per-query copy then dominated short statements. Their values would only+ * have been split into unparsed strings, so drop them after connect.+ */+export async function dropRowTypeArrayParsers(db: PGlite): Promise<void> {+ const { rows } = await db.query<{ oid: number }>(`SELECT a.oid::int AS oid FROM pg_type a+ JOIN pg_type e ON e.oid=a.typelem WHERE a.typcategory='A' AND e.typtype='c'`);+ for (const { oid } of rows) delete db.parsers[oid];+}diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 0436ba3255..4882846a0b 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.60.8.0 -->+<!-- gbrain-template-stamp: 0.60.10.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/persistence-consumer-scheduling.test.ts b/test/persistence-consumer-scheduling.test.tsindex e85d71526f..7197a0b3c1 100644--- a/test/persistence-consumer-scheduling.test.ts+++ b/test/persistence-consumer-scheduling.test.ts@@ -510,3 +510,20 @@ test('a retryable root becomes eligible again after its backoff expires', asyncawait cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);}}), 15_000);++test('a local waiter wakes an idle owner for a claim-only tick instead of waiting for the next poll', async () => withEnv(env, async () => {+ const ticks: boolean[] = [];+ const consumer = startPersistenceConsumer(engine, { engine: 'pglite' });+ const internals = consumer as unknown as { opts: { pollMs?: number }; doTick(afterProgress: boolean): Promise<void> };+ internals.opts.pollMs = 60_000;+ internals.doTick = async afterProgress => { ticks.push(afterProgress); };+ const row = { id: randomUUID(), request_id: randomUUID(), state: 'queued' } as import('../src/core/persistence/model.ts').WriteRequest;+ try {+ await waitFor(() => ticks.length === 1);+ await Bun.sleep(20);+ const waiter = waitForWrite(engine, row, { engine: 'pglite' }, 200);+ await waitFor(() => ticks.length === 2, { timeoutMs: 1000 });+ expect(ticks[1]).toBe(true);+ await waiter;+ } finally { await disposePersistenceConsumer(engine); }+}), 5000);diff --git a/test/pglite-statements.test.ts b/test/pglite-statements.test.tsnew file mode 100644index 0000000000..ed9a171967--- /dev/null+++ b/test/pglite-statements.test.ts@@ -0,0 +1,89 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGlite } from '@electric-sql/pglite';+import { PgliteStatementCache } from '../src/core/pglite-statements.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';++describe('PGLite named statement cache', () => {+ let raw: PGlite;+ let db: PGlite;+ let cache: PgliteStatementCache;++ beforeAll(async () => {+ raw = new PGlite();+ cache = new PgliteStatementCache(raw, 2);+ db = cache.attach(raw, false);+ await raw.exec(`CREATE TABLE items (id int PRIMARY KEY, label text, meta jsonb, tags text[], seen timestamptz, ok boolean, ref uuid)`);+ }, 30_000);++ afterAll(async () => { await raw?.close(); });++ test('prepared executions return exactly what PGlite query returns', async () => {+ const insert = 'INSERT INTO items VALUES ($1,$2,$3,$4,$5,$6,$7)';+ for (let id = 1; id <= 4; id++) {+ const params = [id, id === 2 ? null : `item-${id}`, { id, nested: [id] }, ['a', `b${id}`],+ new Date(Date.UTC(2026, 0, id)), id % 2 === 0, `00000000-0000-0000-0000-00000000000${id}`];+ const cached = await db.query(insert, params);+ expect(cached.affectedRows).toBe(1);+ }+ const select = 'SELECT * FROM items WHERE id >= $1 ORDER BY id';+ const expected = await raw.query(select, [1]);+ for (let run = 0; run < 3; run++) {+ const actual = await db.query(select, [1]);+ expect(actual.rows).toEqual(expected.rows);+ expect(actual.fields).toEqual(expected.fields);+ expect(actual.affectedRows).toBe(expected.affectedRows);+ }+ for (let run = 0; run < 3; run++) {+ expect((await db.query('UPDATE items SET ok = NOT ok WHERE id > $1', [2])).affectedRows).toBe(2);+ expect(await db.query('SELECT id FROM items WHERE id = $1', [99])).toEqual({ rows: [], fields: [{ name: 'id', dataTypeID: 23 }], affectedRows: 0 });+ }+ });++ test('eviction and shape-changing DDL keep results current', async () => {+ const select = 'SELECT * FROM items WHERE id = $1';+ for (let run = 0; run < 3; run++) await db.query(select, [1]);+ await db.query('ALTER TABLE items ADD COLUMN extra int DEFAULT 7');+ expect((await db.query<{ extra: number }>(select, [1])).rows[0].extra).toBe(7);+ for (let run = 0; run < 3; run++) await db.query(select, [1]);+ // DDL the prefix check cannot see: PostgreSQL rejects the cached shape and the query is re-prepared.+ await raw.exec(`CREATE FUNCTION widen() RETURNS void LANGUAGE plpgsql AS $$ BEGIN ALTER TABLE items ADD COLUMN wider int DEFAULT 9; END $$`);+ await raw.query('SELECT widen()');+ expect((await db.query<{ wider: number }>(select, [1])).rows[0].wider).toBe(9);+ for (const id of [1, 2, 3, 4, 1, 2]) await db.query(`SELECT label FROM items WHERE id = $1 AND ${id} > 0`, [id]);+ expect((await db.query<{ label: string }>(select, [3])).rows[0].label).toBe('item-3');+ });++ test('errors keep PGlite fields, and transactions roll back and continue', async () => {+ const insert = 'INSERT INTO items(id,label) VALUES ($1,$2)';+ await db.query(insert, [10, 'ten']);+ await db.query(insert, [11, 'eleven']);+ const error = await db.query(insert, [10, 'again']).catch(caught => caught);+ expect(error.code).toBe('23505');+ expect(error.query).toBe(insert);+ await expect(raw.transaction(async handle => {+ const tx = cache.attach(handle, true);+ for (let run = 0; run < 3; run++) await tx.query('UPDATE items SET label=$2 WHERE id=$1', [11, `tx-${run}`]);+ await tx.query(insert, [10, 'duplicate']);+ })).rejects.toMatchObject({ code: '23505' });+ expect((await db.query('SELECT label FROM items WHERE id=$1', [11])).rows).toEqual([{ label: 'eleven' }]);+ await raw.transaction(async handle => {+ const tx = cache.attach(handle, true);+ for (let run = 0; run < 3; run++) await tx.query('UPDATE items SET label=$2 WHERE id=$1', [11, `committed-${run}`]);+ });+ expect((await db.query('SELECT label FROM items WHERE id=$1', [11])).rows).toEqual([{ label: 'committed-2' }]);+ });+});++describe('PGLite engine statement cache lifecycle', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); }, 60_000);+ afterAll(async () => { await engine?.disconnect(); });++ test('a disconnected engine releases its PGLite instance with the statement cache', async () => {+ await engine.executeRaw('SELECT 1');+ await engine.executeRaw('SELECT 1');+ expect((engine as unknown as { _statements: unknown })._statements).not.toBeNull();+ await engine.disconnect();+ expect((engine as unknown as { _statements: unknown })._statements).toBeNull();+ });+});diff --git a/test/schema-pack-unify-types-handler.test.ts b/test/schema-pack-unify-types-handler.test.tsindex 78485c23ab..7314ef0656 100644--- a/test/schema-pack-unify-types-handler.test.ts+++ b/test/schema-pack-unify-types-handler.test.ts@@ -39,10 +39,20 @@ afterAll(async () => {_resetPackCacheForTests();});+// runUnifyTypes(apply) flips the active pack in ~/.gbrain/config.json. Each+// test gets its own GBRAIN_HOME so that flip never reaches later test files+// sharing the process (they would resolve gbrain-base-v2's vocabulary).+let unifyHome: string;beforeEach(async () => {await resetPgliteState(engine);_resetPackCacheForTests();+ unifyHome = mkdtempSync(join(tmpdir(), 'gbrain-unify-home-'));});+afterEach(() => { rmSync(unifyHome, { recursive: true, force: true }); });++function unify(input: Parameters<typeof runUnifyTypes>[1]) {+ return withEnv({ GBRAIN_HOME: unifyHome }, () => runUnifyTypes(ctxOf(), input));+}function ctxOf() {return {@@ -67,14 +77,14 @@ describe('runUnifyTypes', () => {describe('preflight', () => {it('refuses target pack with no mapping_rules', async () => {// gbrain-base has no mapping_rules- await expect(runUnifyTypes(ctxOf(), {+ await expect(unify({target_pack: 'gbrain-base',apply: false,})).rejects.toThrow(/mapping_rules/);});it('refuses unknown target pack', async () => {- await expect(runUnifyTypes(ctxOf(), {+ await expect(unify({target_pack: 'nonexistent-pack',apply: false,})).rejects.toThrow();@@ -84,7 +94,7 @@ describe('runUnifyTypes', () => {describe('dry-run', () => {it('returns shape with would_apply counts; no mutation', async () => {await seed('tweets/a', 'tweet-single');- const result = await runUnifyTypes(ctxOf(), {+ const result = await unify({target_pack: 'gbrain-base-v2',apply: false,});@@ -109,7 +119,7 @@ describe('runUnifyTypes', () => {await seed('wiki/concepts/redirect-1', 'concept-redirect',{},'[[wiki/concepts/canonical]] redirect body that is long enough to pass min char gates');- const result = await runUnifyTypes(ctxOf(), {+ const result = await unify({target_pack: 'gbrain-base-v2',apply: true,});@@ -141,7 +151,7 @@ describe('runUnifyTypes', () => {it('catch-all rule retypes unknown types to note with legacy_type', async () => {await seed('odd/x', 'some-weird-type'); // not in any explicit rule- const result = await runUnifyTypes(ctxOf(), {+ const result = await unify({target_pack: 'gbrain-base-v2',apply: true,});@@ -157,12 +167,12 @@ describe('runUnifyTypes', () => {describe('idempotency', () => {it('second apply run is mostly no-op', async () => {await seed('tweets/a', 'tweet-single');- const r1 = await runUnifyTypes(ctxOf(), {+ const r1 = await unify({target_pack: 'gbrain-base-v2',apply: true,});expect(r1.per_phase.retype_explicit.applied).toBeGreaterThan(0);- const r2 = await runUnifyTypes(ctxOf(), {+ const r2 = await unify({target_pack: 'gbrain-base-v2',apply: true,});@@ -186,7 +196,7 @@ describe('#2184 conversation-shaped types survive v2 unify', () => {await seed('meetings/2026-04-03', 'meeting');await seed('conversations/imessage/alice-example', 'conversation');await seed('slack/general-2026-04-03', 'slack');- await runUnifyTypes(ctxOf(), {+ await unify({target_pack: 'gbrain-base-v2',apply: true,});