Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.51.6.0 fix(pglite): retry in-memory startup without replacing open databases (#5295)
Garry Tan9b0a1b5ead75
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex f4b1d6fa25..1cddc3fcc0 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.51.4.0",+ "version": "0.51.6.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 65cda24a45..36f18a83a1 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.51.4.0",+ "version": "0.51.6.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 972b90579a..93e9ad7d3c 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.51.4.0 -->+<!-- gbrain-runbook-stamp: 0.51.6.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 916cb64a84..0ef989c6b0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,43 @@All notable changes to GBrain will be documented in this file.+## [0.51.6.0] - 2026-09-21++**A temporary brain gets one safe second chance to start.**++An occasional startup failure no longer has to end a session that uses a fresh,+temporary brain. If the first attempt fails before the database opens, GBrain+tries once more from scratch. A successful retry tells you what happened. If+both attempts fail, it stops and keeps both errors available for diagnosis.++This second chance applies only to temporary databases held in memory. Your+saved brain keeps its existing locking and repair protections. If a database+has already opened and a later setup step fails, GBrain closes that database+instead of replacing it with another one. If cleanup itself fails, it preserves+the existing refusal to reopen until the process exits.++| Situation | Result |+|---|---|+| Startup succeeds immediately | No retry or recovery warning. |+| A temporary database fails to open once | One fresh attempt, without the cached snapshot. |+| Both attempts fail | Startup fails with the original error and retry details. |+| Setup fails after the database opens | The open database is closed; startup is not retried. |++The behavior is automatic after upgrading. It does not retry entire failed test+files, change saved-data repair rules, or guarantee recovery from every runtime+failure. The doctor's separate temporary on-disk probe is unchanged.++### Itemized changes++- Bound in-memory `PGLiteEngine.connect()` recovery to one cold create before+ any database is attached; replay the schema after snapshot fallback.+- Preserve both failed-attempt diagnostics and existing shutdown ownership.+- Add deterministic coverage for recovery, real snapshots, post-open cleanup,+ poisoned close, concurrent connect/disconnect, and process exit status.++Contributed by @RoniHenareh in #5272, with lifecycle safety and regression coverage+extended during integration.+## [0.51.4.0] - 2026-09-21**Queued writes move sooner, and contributor checks spend less time repeating work.**diff --git a/VERSION b/VERSIONindex 467f040540..24e4a0a339 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.51.4.0+0.51.6.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 1653212468..c74e9eebbb 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -3,6 +3,15 @@On-demand reference (see CLAUDE.md Reference map). Current behavior + invariantsonly.+`test/pglite-in-memory-create-retry.serial.test.ts` injects create failures while+using real PGLite instances and a validated schema snapshot. It pins one cold+retry only before an in-memory database has opened, both failure diagnostics,+schema replay after snapshot fallback, post-open cleanup and close poisoning,+concurrent connect/disconnect ordering, exit-code preservation, and exclusion of+the persistent repair path. Run it in its own Bun process because it mocks the+PGLite module. Its recovery cases discriminate against the no-retry base; its+post-open cleanup cases discriminate against a retry that replaces a live database.+`test/e2e/serve-http-oauth.test.ts` additionally pins confidential POST/Basic revocation, public-client SDK fallthrough, malformed/mixed authentication rejection, cross-client isolation, unknown-token opacity, metadata auth methods, no-store responses, strict post-revoke `401`, and retryable backend `503` semantics. SDK-driven discovery and real owner-approved PKCE also pin read-only bootstrap, explicit writer requests, scope clamping, and DCR delegation refusal. `test/oauth-scope-hint.test.ts` exercises the actual SDK middleware over HTTP without requiring a database.`test/put-page-persistence.test.ts` and `test/e2e/put-page-persistence-postgres.test.ts`diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 20024ac7fe..cd3cce3e0d 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -85,7 +85,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/search.ts:gbrain search stats` — `graph_signals` section (enabled/source/failures_count/failures_by_reason). JSON envelope adds a `graph_signals` sibling property; `_meta.metric_glossary` adds `graph_signals.enabled` + `graph_signals.failures_by_reason`. Human output prints the section after the existing block. Reads `search.graph_signals` config first, falls back to the mode default. Pinned by `test/search/search-stats-graph-signals.test.ts`. Both `gbrain search stats` and `gbrain search tune` also surface a `coverage` disclosure (JSON: `{cli_invocations: 'recorded_on_clean_exit', reason}`; human: a one-line caveat) sourced from `telemetryCoverage()`/`TELEMETRY_COVERAGE_CAVEAT` in `src/core/search/telemetry.ts`: a short-lived CLI call's buffer flushes during the bounded CLI teardown drain, so a CLEAN exit is recorded; hard kills, drains that exceed their bound, and anything buffered when an engine disconnects outside the CLI teardown path still drop — the disclosure is display-only and reads its truth from the telemetry module's single-source constants. Pinned by the coverage-disclosure tests in `test/commands-search.test.ts`.- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`).-- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` awaits mandatory resident-consumer stops, closes admission on tracked query/exec/transaction handles, drains admitted statements and best-effort background work, then awaits CHECKPOINT and close before kernel release. A deadline reports `pglite_closing` while actual shutdown continues with ownership retained; a failed close poisons reconnect until process exit. The out-of-band watchdog remains available for event-loop wedges. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass. `getRawData` pushes `p.deleted_at IS NULL` into its `where[]` unless `opts.includeDeleted` — parity twin of the Postgres `alive` fragment; see the postgres-engine.ts entry.+- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` retries a failed in-memory `PGlite.create()` once, cold, only while no database is attached. The retry omits the snapshot and clears its loaded flag so `initSchema()` replays the schema. Recovery warns on stderr; exhausted recovery retains both error diagnostics. Post-open setup errors instead close the existing database, preserving close-poison and ownership rules. The doctor scratch probe is a separate disk-backed path and does not use this retry. Remaining initialization failures use the existing classifier and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` awaits mandatory resident-consumer stops, closes admission on tracked query/exec/transaction handles, drains admitted statements and best-effort background work, then awaits CHECKPOINT and close before kernel release. A deadline reports `pglite_closing` while actual shutdown continues with ownership retained; a failed close poisons reconnect until process exit. The out-of-band watchdog remains available for event-loop wedges. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass. `getRawData` pushes `p.deleted_at IS NULL` into its `where[]` unless `opts.includeDeleted` — parity twin of the Postgres `alive` fragment; see the postgres-engine.ts entry.- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).- `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-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (a port of the electric-sql/pglite pg_resetwal contribution, PR #994, Apache-2.0). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex b3bda8f3e1..79866f1466 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.51.4.0",+ "version": "0.51.6.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 9b1930897c..90b14d8572 100644--- a/package.json+++ b/package.json@@ -177,7 +177,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.51.4.0",+ "version": "0.51.6.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 0860a73ee6..f371f7bf75 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.51.4.0",+ "version": "0.51.6.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 3d370aed69..2efd9e9884 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.51.4.0",+ "version": "0.51.6.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 33a85ef39f..42ab97e207 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.51.4.0 -->+<!-- gbrain-plugin-tree-stamp: 0.51.6.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 894a223811..04be0c454f 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.51.4.0",+ "version": "0.51.6.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 6b21642886..4d72e8a17d 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.51.4.0",+ "version": "0.51.6.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex b8aac9a775..d4d9cd491c 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.51.4.0 -->+<!-- gbrain-plugin-tree-stamp: 0.51.6.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 78290ae214..38aa31a14a 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.51.4.0 -->+<!-- gbrain-plugin-tree-stamp: 0.51.6.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 381d29cbb3..85cc60b61c 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -20,7 +20,7 @@ src/core/engine.ts 2655 ratchet grown v0.46.26.0 megawave: relational/visibilitysrc/core/import-file.ts 2354 ratchet 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 extractionsrc/core/migrate.ts 719 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 extractionsrc/core/operations.ts 323 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-src/core/pglite-engine.ts 6091 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)+src/core/pglite-engine.ts 6098 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 diagnosticssrc/core/postgres-engine.ts 5577 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)src/core/search/hybrid.ts 3306 ratchet 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 callsrc/core/types.ts 2137 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 extractiondiff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 27e2c061af..41592f2036 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -849,6 +849,22 @@ export class PGLiteEngine implements BrainEngine {const original = stringifyPgliteInitError(err); // #2674const verdict = classifyPgliteInitError(original);let ctx: PgliteInitRepairContext = { repair: 'not-attempted' };+ let retryError: string | undefined;++ if (!dataDir && !this._db) {+ let retried: PGLiteDB | null = null;+ try {+ retried = await preservingProcessExitCode(() => PGlite.create({ ...embedded }));+ } catch (error) {+ retryError = stringifyPgliteInitError(error);+ }+ if (retried) {+ this._db = this._attachDatabase(retried);+ this._snapshotLoaded = false;+ console.warn(`[pglite] in-memory init failed and was retried cold — recovered. First error: ${original}`);+ return;+ }+ }// WAL-repair wave (#223/#1670/#2575): a wasm-abort on a PERSISTENT data// dir is almost always torn WAL/checkpoint state from an unclean@@ -895,7 +911,8 @@ export class PGLiteEngine implements BrainEngine {}}- const wrapped = new Error(buildPgliteInitErrorMessage(verdict, original, process.platform, ctx));+ const wrapped = new Error(buildPgliteInitErrorMessage(verdict, original, process.platform, ctx) ++ (retryError === undefined ? '' : `\n Cold retry error: ${retryError}`));if (this._db) {try { await this._closeInternal(); }catch (closeError) {diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 7dcd541966..d60dd6cf9c 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.51.4.0 -->+<!-- gbrain-template-stamp: 0.51.6.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/pglite-in-memory-create-retry.serial.test.ts b/test/pglite-in-memory-create-retry.serial.test.tsnew file mode 100644index 0000000000..4171419154--- /dev/null+++ b/test/pglite-in-memory-create-retry.serial.test.ts@@ -0,0 +1,267 @@+import { afterEach, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import type { PGliteOptions } from '@electric-sql/pglite';+import type { EngineConfig } from '../src/core/types.ts';++const WASM_TRAP = "access to a null reference (evaluating 'getWasmTableEntry(e)(t, r, a)')";+const SNAPSHOT = resolve(import.meta.dir, 'fixtures/pglite-snapshot.tar');+const IN_MEMORY: EngineConfig = { engine: 'pglite' };+const realPglite = await import('@electric-sql/pglite');+const RealPGlite = realPglite.PGlite;+type Database = InstanceType<typeof RealPGlite>;++let failures: unknown[] = [];+let calls: (PGliteOptions | undefined)[] = [];+let beforeCreate: ((attempt: number) => Promise<void>) | undefined;+let failTimezone = false;+let failClose = false;+const opened: { db: Database; close: () => Promise<void>; closes: number }[] = [];++class FlakyPGlite extends RealPGlite {+ static async create(...args: Parameters<typeof RealPGlite.create>) {+ const attempt = calls.push(typeof args[0] === 'string' ? args[1] : args[0]);+ await beforeCreate?.(attempt);+ if (failures.length > 0) throw failures.shift();+ const db = await RealPGlite.create(...args);+ const record = { db, close: db.close.bind(db), closes: 0 };+ opened.push(record);+ const query = db.query.bind(db);+ db.query = ((...args: Parameters<typeof db.query>) => {+ if (failTimezone && args[0].includes("set_config('TimeZone'")) {+ return Promise.reject(new Error('injected timezone setup failure'));+ }+ return query(...args);+ }) as typeof db.query;+ db.close = async () => {+ record.closes++;+ if (failClose) throw new Error('injected close failure');+ await record.close();+ };+ return db;+ }+}++mock.module('@electric-sql/pglite', () => ({ ...realPglite, PGlite: FlakyPGlite }));+const { PGLiteEngine, classifyPgliteInitError } = await import('../src/core/pglite-engine.ts');+const { PgliteClosingError } = await import('../src/core/pglite-lifecycle.ts');++const engines: InstanceType<typeof PGLiteEngine>[] = [];+const roots: string[] = [];+const warnings: string[] = [];+let previousSnapshot: string | undefined;+let previousWarn: typeof console.warn;+let previousExitCode: typeof process.exitCode;++function engine() {+ const result = new PGLiteEngine();+ engines.push(result);+ return result;+}++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>(done => { resolve = done; });+ return { promise, resolve };+}++beforeAll(() => {+ const result = Bun.spawnSync(['bun', 'run', 'build:pglite-snapshot'], {+ cwd: resolve(import.meta.dir, '..'), stdout: 'pipe', stderr: 'pipe',+ timeout: 300_000, killSignal: 'SIGKILL',+ });+ expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);+}, 320_000);++beforeEach(() => {+ failures = [];+ calls = [];+ beforeCreate = undefined;+ failTimezone = false;+ failClose = false;+ warnings.length = 0;+ previousSnapshot = process.env.GBRAIN_PGLITE_SNAPSHOT;+ delete process.env.GBRAIN_PGLITE_SNAPSHOT;+ previousExitCode = process.exitCode;+ process.exitCode = 0;+ previousWarn = console.warn;+ console.warn = (...args: unknown[]) => { warnings.push(args.map(String).join(' ')); };+});++afterEach(async () => {+ failTimezone = false;+ failClose = false;+ try {+ for (const db of engines.splice(0)) {+ try { await db.disconnect(); } catch (error) {+ if (!(error instanceof PgliteClosingError)) throw error;+ }+ }+ for (const record of opened.splice(0)) {+ if (!record.db.closed) await record.close();+ }+ } finally {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+ if (previousSnapshot === undefined) delete process.env.GBRAIN_PGLITE_SNAPSHOT;+ else process.env.GBRAIN_PGLITE_SNAPSHOT = previousSnapshot;+ console.warn = previousWarn;+ process.exitCode = previousExitCode ?? 0;+ }+});++describe('in-memory PGLite create retry', () => {+ test('the observed create trap classifies as unknown', () => {+ expect(classifyPgliteInitError(WASM_TRAP)).toBe('unknown');+ });++ for (const snapshot of [false, true]) {+ test(`a single create trap recovers cold with snapshot=${snapshot}`, async () => {+ if (snapshot) process.env.GBRAIN_PGLITE_SNAPSHOT = SNAPSHOT;+ failures = [new Error(WASM_TRAP)];+ const db = engine();+ await db.connect(IN_MEMORY);+ expect(calls).toHaveLength(2);+ expect(calls[0]?.loadDataDir instanceof Blob).toBe(snapshot);+ expect(calls[1]?.loadDataDir).toBeUndefined();+ expect(calls[1]?.dataDir).toBeUndefined();+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain('retried cold');+ expect(warnings[0]).toContain(WASM_TRAP);+ const before = await db.db.query<{ pages: string | null }>("SELECT to_regclass('public.pages')::text AS pages");+ expect(before.rows[0].pages).toBeNull();+ await db.initSchema();+ await db.putPage('retry-example', { title: 'Retry example', compiled_truth: 'Recovered content', type: 'note' });+ expect((await db.getPage('retry-example', { sourceId: 'default' }))?.compiled_truth).toBe('Recovered content');+ await db.disconnect();+ expect(opened).toHaveLength(1);+ expect(opened[0].db.closed).toBe(true);+ expect(opened[0].closes).toBe(1);+ }, 120_000);++ test(`a healthy create is never retried with snapshot=${snapshot}`, async () => {+ if (snapshot) process.env.GBRAIN_PGLITE_SNAPSHOT = SNAPSHOT;+ const db = engine();+ await db.connect(IN_MEMORY);+ expect(calls).toHaveLength(1);+ expect(calls[0]?.loadDataDir instanceof Blob).toBe(snapshot);+ expect(warnings).toHaveLength(0);+ if (snapshot) {+ const rows = await db.db.query<{ pages: string | null }>("SELECT to_regclass('public.pages')::text AS pages");+ expect(rows.rows[0].pages).toBe('pages');+ }+ }, 120_000);+ }++ test('two create failures retain both causes, stop at two attempts, and allow a fresh connect', async () => {+ failures = [new Error(WASM_TRAP), { name: 'ErrnoError', errno: 20 }];+ const db = engine();+ const error = await db.connect(IN_MEMORY).then(() => null, error => error as Error);+ expect(error?.message).toContain('PGLite failed to initialize its WASM runtime.');+ expect(error?.message).toContain(`Original error: ${WASM_TRAP}`);+ expect(error?.message).toContain('Cold retry error: ErrnoError (errno 20)');+ expect(calls).toHaveLength(2);+ expect(warnings).toHaveLength(0);+ expect(() => db.db).toThrow('PGLite not connected');+ await db.connect(IN_MEMORY);+ expect(calls).toHaveLength(3);+ expect(opened).toHaveLength(1);+ }, 120_000);++ test('an empty directory and non-Error rejection use the same bounded retry', async () => {+ failures = [WASM_TRAP];+ await engine().connect({ engine: 'pglite', database_path: '' });+ expect(calls).toHaveLength(2);+ expect(warnings[0]).toContain(WASM_TRAP);+ }, 120_000);++ for (const closeFails of [false, true]) {+ test(`timezone setup failure never retries an open database with closeFails=${closeFails}`, async () => {+ process.env.GBRAIN_PGLITE_SNAPSHOT = SNAPSHOT;+ failTimezone = true;+ failClose = closeFails;+ const db = engine();+ await expect(db.connect(IN_MEMORY)).rejects.toThrow(closeFails ? 'initialization cleanup failed' : 'injected timezone setup failure');+ expect(calls).toHaveLength(1);+ expect(calls[0]?.loadDataDir).toBeInstanceOf(Blob);+ expect(opened).toHaveLength(1);+ expect(opened[0].closes).toBe(1);+ expect(opened[0].db.closed).toBe(!closeFails);+ expect(warnings.filter(message => message.includes('retried cold'))).toHaveLength(0);+ if (closeFails) {+ await expect(db.connect(IN_MEMORY)).rejects.toBeInstanceOf(PgliteClosingError);+ await expect(db.disconnect()).rejects.toBeInstanceOf(PgliteClosingError);+ expect(calls).toHaveLength(1);+ }+ }, 120_000);+ }++ test('an unknown persistent create failure never receives the in-memory retry', async () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-retry-persistent-'));+ roots.push(root);+ failures = [new Error(WASM_TRAP)];+ const db = engine();+ const config: EngineConfig = { engine: 'pglite', database_path: join(root, 'store') };+ await expect(db.connect(config)).rejects.toThrow(WASM_TRAP);+ expect(calls).toHaveLength(1);+ expect(warnings).toHaveLength(0);+ await db.connect(config);+ expect(calls).toHaveLength(2);+ expect(db.walRepairReceipt).toBeNull();+ }, 120_000);++ for (const retryFails of [false, true]) {+ test(`concurrent connects share one recovery and shutdown waits with retryFails=${retryFails}`, async () => {+ const entered = deferred(), release = deferred();+ beforeCreate = async attempt => {+ if (attempt === 2) { entered.resolve(); await release.promise; }+ };+ failures = retryFails ? [new Error(WASM_TRAP), new Error('retry rejected')] : [new Error(WASM_TRAP)];+ const db = engine();+ const first = db.connect(IN_MEMORY);+ const firstResult = first.then(() => null, error => error);+ let shutdown: Promise<void> | undefined;+ try {+ await Promise.race([entered.promise, first]);+ const second = db.connect(IN_MEMORY);+ const secondResult = second.then(() => null, error => error);+ let closed = false;+ shutdown = db.disconnect().then(() => { closed = true; });+ await Promise.resolve();+ expect(closed).toBe(false);+ await expect(db.connect(IN_MEMORY)).rejects.toBeInstanceOf(PgliteClosingError);+ expect(calls).toHaveLength(2);+ release.resolve();+ const [firstError, secondError] = await Promise.all([firstResult, secondResult]);+ expect(secondError).toBe(firstError);+ if (retryFails) expect(firstError?.message).toContain('retry rejected');+ else expect(firstError).toBeNull();+ await shutdown;+ expect(closed).toBe(true);+ expect(calls).toHaveLength(2);+ expect(() => db.db).toThrow('PGLite not connected');+ expect(opened).toHaveLength(retryFails ? 0 : 1);+ if (!retryFails) {+ expect(opened[0].db.closed).toBe(true);+ expect(opened[0].closes).toBe(1);+ }+ } finally {+ release.resolve();+ await firstResult;+ await shutdown;+ }+ }, 120_000);+ }++ for (const retryFails of [false, true]) {+ test(`both create attempts preserve the incoming process exit code with retryFails=${retryFails}`, async () => {+ process.exitCode = 7;+ beforeCreate = async () => { process.exitCode = 99; };+ failures = retryFails ? [new Error(WASM_TRAP), new Error('retry rejected')] : [new Error(WASM_TRAP)];+ const result = await engine().connect(IN_MEMORY).then(() => null, error => error);+ expect(Boolean(result)).toBe(retryFails);+ expect(calls).toHaveLength(2);+ expect(process.exitCode).toBe(7);+ }, 120_000);+ }+});