Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
55.4 KB
Raw Blame

Key files: Engines (1/2)

Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

  • Primary searchVector generation filters in both engines require the resolved model and either a current embedded-text hash or a grandfathered pre-v133 NULL hash. A budget/resume marker alone never changes a matching-model legacy vector's eligibility; known stale hashes and incompatible models remain excluded. On HNSW-indexed columns the hash test runs after the candidate scan (see search/vector-statement.ts), so a stale chunk can occupy a candidate slot but never a result. This does not infer provenance for legacy fact vectors. test/legacy-vector-compatibility.test.ts and its PostgreSQL wrapper pin actual hybrid retrieval through a failed provider probe and retained migration marker without rewriting stored vectors.

  • src/core/connection-manager.ts — routes ordinary and direct Postgres pools. Supabase-shaped URLs derive the direct route; a valid explicit GBRAIN_DIRECT_DATABASE_URL or constructor override enables it for generic Postgres and custom-port PgBouncer. The kill switch and inherited parent route stay authoritative. direct-pool-profile.ts (per CLI command) sizes it: resident 3, short-lived 1, one-shot none until a lease; DDL stays direct. Tests: test/connection-manager.serial.test.ts, test/direct-pool-profile.test.ts.

  • src/core/db-lock.ts + lease-schema.ts — row leases survive transaction-mode PgBouncer. Migration 152 gives every gbrain_cycle_locks acquisition a UUID; refresh/release, takeover/reaper and manual/age-gated breaks match (id, holder_pid, acquisition_token), never the acquired_at epoch text, which is diagnostics only (#6028). withRefreshingLock always passes an aborting work signal, rejects results after ownership loss/TTL expiry, tracks a single actual renewal through timeout cancellation, and drains late completion before release. Release uses the live pool, surviving engine.reconnect(). Renewal deadlines start before the database round trip. performSync composes this signal with caller cancellation. inspectLock, listStaleLocks, listLiveLocks, classifyHolderLiveness and namespace-scoped reapDeadHolderLocks keep their status/recovery contracts. Tests: test/db-lock-concurrency.test.ts, test/db-lock-token-predicate.test.ts, test/e2e/db-lock-acquisition-token.test.ts, fencing/reaper/inspection suites.

  • src/core/db-repair-receipts.ts — the shared seam between gbrain db-repair (writer) and doctor's db_repair_recurrence check (reader — it must run in doctor's dead-DB filesystem lane, exactly when repairs are repeating). JSONL at ~/.gbrain/db-repair-receipts.jsonl; row shape {ts, brain_id, reason, action, outcome: 'applied'|'refused'|'diagnose'} — only applied rows count toward the recurrence threshold (3+ same-reason per brain in 7 days). Redacted before write (the classifier redacts its own copy; actions are fixed strings), fail-open (a receipts problem never blocks a repair), capped at 200 rows ON EVERY WRITE (the recurrence check reads the file on every doctor run — it must not grow unbounded on exactly the machines having chronic problems) — EXCEPT applied rows inside an 8-day retention window, which are exempt from the flat cap (separately bounded at 200): a diagnose flood from an agent loop must never evict the cooldown/recurrence memory. The reader is per-line tolerant (one torn row never discards every other receipt). Also owns rewriteCooldownBlocked (24h per (reason, action), rewrite tier only).

  • src/core/db.ts — Connection management, schema initialization. resolveSessionTimeouts() returns statement_timeout + idle_in_transaction_session_timeout (defaults 5min each, env-overridable via GBRAIN_STATEMENT_TIMEOUT/GBRAIN_IDLE_TX_TIMEOUT/GBRAIN_CLIENT_CHECK_INTERVAL). Both connect() (module singleton) and PostgresEngine.connect() (worker pool) consume the result via postgres.js's connection option, sending GUCs as startup parameters that survive PgBouncer transaction mode (setSessionDefaults kept as a back-compat no-op shim). connect(config, { onpoisoned }) passes the owner engine's poisoned-discard hook to the singleton pool and returns Promise<boolean> — true iff THIS call created the module singleton, false if it joined an existing one; the decision is atomic (no await between the if (sql) null-check and the synchronous sql = postgres(...) assignment), so two concurrent module connects can't both claim creation. PostgresEngine stores the return as its _ownsModuleSingleton token and only the creating engine may db.disconnect() the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module sql is only ever nulled by db.disconnect() (postgres.js auto-reconnects its own internal pool and never touches our reference). disconnect() snapshots + nulls sql before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through endPoolBounded(pool) — a gbrain-owned Promise.race of pool.end({ timeout: POOL_END_TIMEOUT_SECONDS }) against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the CLI teardown contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. connection-manager.ts ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. resolveMaxLifetimeSeconds(env?) — explicit client-pool max_lifetime for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; GBRAIN_POOL_MAX_LIFETIME_S overrides, 0 disables; warn-once on invalid). Pinned by test/db-pool-max-lifetime.test.ts. resolveUrlConnectTimeout(url) supplies connect_timeout to the same four call sites from each pool's own URL query (postgres.js lets the explicit option win over the URL, so the URL value is honoured only through this resolver): whole seconds, capped at the runtime's 2^31-1 ms timer limit; 0, junk or no parameter means 10s. Pinned by test/db-connect-timeout.test.ts. connectWithRetry retries the isRetryableConnError set (3 attempts, 1s/2s backoff; GBRAIN_NO_RETRY_CONNECT=1 makes it one); retryConnectTimeout: true adds postgres.js CONNECT_TIMEOUT (isConnectTimeoutError in retry-matcher.ts) and is passed only by the per-worker pools of parallel import and incremental sync, whose URL the parent engine already reached (#5946), so a first connect still fails fast on a timeout. Pinned by test/worker-pool-connect-retry.test.ts. #6543: resolveReadPoolPipeline(url) returns { value, reason } for the three read-side pools (module singleton, instance pool, connection-manager read pool; readPoolPipelineOptions spreads it): 0 for a transaction-mode URL (port 6543 or ?prepare=false, read from the URL because GBRAIN_PREPARE wins inside resolvePrepare) or GBRAIN_PREPARE=0, the key omitted (driver default 100, never undefined) for a session pooler or direct URL, and omitted whenever the URL names max_pipeline or PGMAX_PIPELINE is non-empty, since the driver lets the options object outrank both; pinned by test/read-pool-pipeline-6543.test.ts and test/e2e/pgbouncer-pipelined-read-pool.test.ts.

  • src/core/degraded-engine.ts + src/core/degraded-marker.ts — degraded-mode serve, STARTUP-SCOPED by design: when Postgres is unreachable at gbrain serve startup, serve boots on createDegradedEngine (a concrete object whose method set is enumerated from PostgresEngine's prototype at construction; kind is an explicit getter, read synchronously at ~29 branch sites; disconnect() is a no-op while dead so shutdown never triggers a reconnect) instead of dying. Every tool call attempts ONE reconnect (single-flight across concurrent callers, min-interval gated ~5s — no connect storms against a dying pooler); calls inside the window throw the STORED original error so MCP dispatch classifies the REAL error shape into the database_error envelope + marker. The reconnect callback is the FULL deferred connectEngine (config merge, gateway, migrations — guarded in cli.ts: a vanished config.json throws instead of connectEngine's process.exit killing the live server); first success swaps in the live engine permanently, aligns the stand-in with it (alignWith, #9224: every live property, fields and symbols included, delegates, and a sync method returns its own value) and fires recovery callbacks (serve re-runs deferred boot + sends tools/list_changed — clients that handshook degraded hold the reduced gate-hidden catalog and must refresh; the callback is a no-op once shutdown has started) — but the TRIGGERING call gets DegradedRecoveredRetryError, never a result: its source scope was resolved under the degraded fallback, so one client retry buys scope correctness. Callers waiting on an in-flight attempt are latency-capped (callerWaitMs, default 2s — they get the stored error while the attempt finishes in the background, so a timeout-class failure can't stall the MCP handshake). Prototype GETTERS delegate too (throw the stored error while dead — never a silent undefined); DEGRADED_LAST_ERROR is a read-only accessor for the stored diagnosis (drives the HTTP /health degraded reason without consuming a reconnect). Serve-side degraded posture: source scope honors a validated GBRAIN_SOURCE (tier env) before seed_default, and stdioVisibleTools fail-closes every gated op WITHOUT touching the engine. The degraded gate keys on the RESOLVED brain's engine (a PGLite mount on a postgres host keeps die-on-startup). Mid-session outages ride PostgresEngine.reconnect() + per-call classified envelopes — degraded mode adds no mid-session state; PGLite startup failures keep die-on-startup (single-writer lock makes a lazy proxy wrong there; that lane's repair is pglite-repair). Kill switch GBRAIN_SERVE_DEGRADED=0 (or false); structured [gbrain-serve] DEGRADED/RECOVERED stderr lines. degraded-marker.ts is the dependency-free seam (Symbol.for-registered markers + isEngineDegraded/onEngineRecovered/degradedLastError) so server.ts/serve.ts/http-transport.ts can ask about degraded state without importing the heavy Postgres engine module.

  • src/core/docker-postgres.ts — gbrain's OWN docker Postgres container, the shared seam between the init ladder's docker rung and db-repair's conn_refused auto arm. GBRAIN_PG_CONTAINER = 'gbrain-postgres' / GBRAIN_PG_IMAGE = 'pgvector/pgvector:pg16' / GBRAIN_PG_HOST_PORT = 5434 live HERE and only here (DRY — the init rung and the repair arm must never carry two string literals that can drift). Ownership contract: gbrain starts and reuses this container, NEVER stops or removes it, and never touches a container whose credentials it cannot recover via inspectCredentials (docker inspect → POSTGRES_PASSWORD env + the container's ORIGINAL port mapping — a freshly generated password can never match a surviving container; unrecoverable → refuse with a recreate-with-consent recipe). Hardening: the port binds loopback-only (127.0.0.1:5434 — a single-machine brain store, not a network service); data lives on the named gbrain-pgdata volume so a container recreate never loses the brain; the password rides the child ENVIRONMENT (bare -e POSTGRES_PASSWORD — argv is world-readable in ps); docker run gets a 10-minute timeout (the first run synchronously pulls the image; 30s stays for cheap ps/inspect/start calls). isGbrainDockerUrl is the one predicate for "does this URL point at our container" (loopback + dedicated port — never error text).

  • src/core/embedding-migration.ts — provider-agnostic embedding migration core; owns the schema-transition + env-gate primitives. runSchemaTransition(engine, targetDim): ONE transaction rebuilds all four dim-pinned text-embedding-space columns (content_chunks.embedding, query_cache.embedding, facts.embedding, takes.embedding) preserving each column's vector/halfvec type, HNSW gated on hnswIndexExpected (dims > 2000 skip the index; exact scans stay correct — 2048d targets work); the HNSW indexes of every rebuilt text-embedding column (content_chunks canonical and custom, plus each TEXT_EMBEDDING_DIM_PINNED_TABLES entry via transitionDimPinnedColumn's returned definition; the allowed set is DEFERRED_ANN_TABLES) are NOT rebuilt in the transaction but recorded in the marker as deferred_ann_indexes (recordDeferredAnnIndexes) and built after the re-embed drain by src/core/embedding-ann-build.ts (CONCURRENTLY on Postgres, INVALID remnants dropped first, one marker update per built index; config-planted definitions outside <deferred table> USING hnsw (embedding …) are rejected), while btree/partial dependents replay immediately; verifyMigrationComplete blocks on pending or INVALID ANN indexes (migrate-embeddings-ann-deferred-5088.serial.test.ts); image/multimodal columns deliberately untouched; AFTER commit it clears embedded_at in yielding 50k batches (belt-and-braces hygiene — read surfaces key on the vector itself). planEmbeddingMigration: workload via widened stale predicates (absent-column fallback counts every chunk), cost, signature_census (top-5 page signatures — DB-reality corroboration of From), synopsis_tier_pages (context-tier downgrade consent), bundle-aware reranker_warning, dim_change via the shared schemaRebuildNeeded (null ⇒ rebuild, same computation apply uses). applyEmbeddingMigration: env≠target refusal (detectEnvOverride; detectEnvPresence drives the ==target notice) → marker v2 write (same-target re-apply preserves started_at; retarget records superseded history) → full rebuild when the chunks column is off-width, else INDEPENDENT repair of stale dim-pinned columns (readDimPinnedWidths) → false-target-stamp clearing (chunk-model truth) + guarded NULL-signature-inclusive invalidation (embed_skip pages' retained vectors preserved; both via embedding-invalidation.ts) BEFORE config writes (same-dim-swap crash safety) → DB plane → file-plane callback → cache purge. verifyMigrationComplete: the ONLY basis for "nothing to migrate" — column + pinned widths, wide stale census, false-stamp census blocker (embedded chunks whose model contradicts a page already stamped with the target signature), missing_embeddings residue, chunkless-pages census, embed_skip-NULL visibility (report-only detail, never a blocker), marker state, un-merged file plane (or env-canonical), env-contradiction blocker; never trusts from_model. completeEmbeddingMigration: marker delete + completion stamp in ONE transaction (no lost-receipt crash window); accepts content-free extra (smoke-check outcome). readMigrationState (corrupt-safe), readMigrationStatus (read-only, spend-free, everything-degrades-to-null), verifySearchRoundTrip (completion smoke check: one sample per distinct eligible page, picked by an index-ordered walk of the newest eligible chunks bounded at 1,000; the longest eligible chunk is re-read under the page lock and queried as title (160 chars) plus chunk (512); query-side embedQuery + searchVector, hit identity by page_id, NEVER throws, warn-don't-block, content-free samples), resolveRerankerExposure/resolveRerankerPlan/applyRerankerAction (D8 companion switch: bundle-resolved exposure; auto→target-provider default reranker, never a silent third provider; config write + cache purge in one tx), reconcilePageSignatures (batch-boundary stamp repair). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Pinned by test/embedding-migration.test.ts, test/migrate-embeddings-hardening.serial.test.ts, test/e2e/migrate-embeddings-postgres.test.ts.

  • src/core/engine-capabilities.ts — the named capabilities an engine reports (BrainEngine.capabilities, a read-only set) and the table of what each operation, CLI command, cycle phase and minion handler needs. PGLite and Postgres report every shared capability plus raw_sql; only PGLite reports single_owner and only Postgres reports postgres_admin. capabilitiesForEngineKind returns a fresh set per engine. requiredCapabilities(consumer, name) answers ['raw_sql'] for any name without a row, and missingCapabilities(engine, consumer, name) lists what an engine lacks (empty on both SQL engines). Callers ask a capability instead of branching on engine.kind. Pinned by test/engine-capabilities.test.ts.

  • src/core/engine-constants.ts — single source of truth for engine batch-sizing constants. Exports DELETE_BATCH_SIZE = 500 consumed by both engines' deletePages + resolveSlugsByPaths and by the sync delete + rename loops. Lives outside engine.ts (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification. Also exports TRAVERSE_PATH_ROW_CAP = 5000, the raw-row bound on traversePaths/traversePathsDetailed (both engines LIMIT CAP + 1; the extra row is the truncation probe; counted before edge dedup), and TRAVERSE_WALK_ROW_CAP = 20000, the bound on simple-path rows the recursive walks enumerate (traverseGraph and traversePaths*, both engines). The walk CTE is pulled through LIMIT so a dense hub stops enumerating, rows are deduped to (page, depth) before the edge join or the per-node link aggregation, and traversePaths stops recursing one layer early because the deepest layer only terminates edges. A capped walk sets truncated on traversePathsDetailed.

  • src/core/engine-sql/bootstrap.ts — the forward-reference bootstrap, one implementation for both engines (refactor wave 1, E1): probes, in one round-trip, every column/table the embedded schema blob forward-references that older brains may lack, and adds only what is missing (column-only ADD COLUMN IF NOT EXISTS, plus the sources table + default seed and SET DEFAULT where the upgrade window needs it); fresh installs and current brains no-op. Callers: PGLiteEngine.initSchema (pgliteBootstrapTarget(db)), PostgresEngine.initSchema and db.ts:initSchema (applyPostgresForwardReferenceBootstrap(conn), on the DDL connection holding advisory lock 42; the db.ts path replays the blob without migrations, safe because NULL-tolerant read predicates accept pre-backfill rows). Engine differences are dialect hooks: probe schema (current_schema() vs 'public'), the Postgres-blob-only dream_verdicts.expires_at probe + ALTER (inside dialect-only:postgres markers so the PGLite coverage check does not count it), and the per-engine position of the v39 content_chunks ALTER. The Postgres probe runs with tagged-template driver options (prepared on direct Postgres, unprepared through PgBouncer). A snapshot-hash root (snapshot-schema-inputs.ts). Covered by test/schema-bootstrap-coverage.test.ts (parses this file), test/bootstrap.test.ts and test/e2e/postgres-bootstrap.test.ts; per-probe inventory in docs/designs/refactor-wave-1/w1-inventory.md.

  • src/core/engine-factory.ts — Engine factory with dynamic imports ('pglite' | 'postgres').

  • src/core/engine.ts — Pluggable engine interface (BrainEngine). clampSearchLimit(limit, default, cap) takes an explicit cap so per-operation caps can be tighter than MAX_SEARCH_LIMIT. Exports LinkBatchInput/TimelineBatchInput for the bulk-insert API (addLinksBatch/addTimelineEntriesBatch). readonly kind: 'postgres' | 'pglite' discriminator lets src/core/migrate.ts and others branch without instanceof + dynamic imports. Methods: batchLoadEmotionalInputs(slugs?) (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), setEmotionalWeightBatch(rows) (UPDATE FROM unnest($1::text[],$2::text[],$3::real[]) composite-keyed on (slug, source_id)), getRecentSalience(opts), findAnomalies(opts). PageFilters has sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug' + PAGE_SORT_SQL whitelist consumed by both engines. listAllPageRefs(): Promise<Array<{slug, source_id}>> ordered by (source_id, slug) — cheap cross-source enumeration instead of a getAllSlugs()→getPage(slug) N+1 (which would silently default to source_id='default'); parity across postgres-engine.ts + pglite-engine.ts; Pinned by test/e2e/multi-source-bug-class.test.ts. SearchOpts+PageFilters add sourceIds?: string[] (federated read axis; both engines apply WHERE source_id = ANY($N::text[]) when set, preserve scalar sourceId fast path when unset); traverseGraph(slug, depth, opts?) and traversePaths(slug, opts?) accept opts.sourceId/opts.sourceIds. traversePathsDetailed(slug, opts?) returns { paths: GraphPath[], truncated } — the final SELECT of the path-enumerating recursive CTE is bounded at TRAVERSE_PATH_ROW_CAP + 1 rows on both engines (the probe row signals overflow; ORDER BY depth means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so paths.length alone cannot reveal truncation) and traversePaths is its .paths projection. Each GraphPath carries from_source_id/to_source_id and the edge dedup keys on page ids; each traverseGraph GraphNode carries source_id (DISTINCT per page), so the same slug in two sources stays two edges or nodes. resolveSlugWithAliasDetailed(slug, sourceOrSources) returns { canonical_slug, source_id } | null — the winning alias row AND its owning source under the same scope/precedence rules (ORDER BY array_position(scope, source_id), id; null when nothing matches or the slug_aliases table does not exist yet); resolveSlugWithAlias is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to source_id. The by-slug read methods carry the same federated axis: getTags/getLinks/getBacklinks/getChunks opts and TimelineOpts (consumed by getTimeline) accept sourceIds?: string[] taking precedence over the scalar sourceId (source_id = ANY($::text[]) scoping the slug→page-id lookup); getChunkPage(slug, {fromIndex, limit, ...scope}) is get_chunks' paged read: the same predicate as getChunks, one count/max query plus the chunk_index range [fromIndex, fromIndex + limit) (a range, so a slug matching a page in two federated sources never splits an index across calls); getChunks falls back to the 'default' source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (getChunksWithEmbeddings stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (getLinks/getBacklinks) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers; all drop edges with a deleted origin. traverseGraph opts has frontierCap?: number (per-iteration recursive-CTE cap, approx per-BFS-layer); return type Promise<GraphNode[]> for MCP wire stability; export TraverseGraphOpts; Postgres uses parenthesized LIMIT N ORDER BY (slug, id) inside the recursive term, PGLite mirrors with positional params; Pinned by test/regressions/v0_36_frontier_cap.test.ts. Phantom-redirect methods: refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash) narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so gbrain sync sees the canonical as unchanged after fence merge); migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId) UPDATEs entity_slug+source_markdown_slug on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting row_num past the canonical page's current MAX(row_num) (all rows incl. expired — the partial idx_facts_fence_key only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at test/phantom-redirect-engine-parity.test.ts. getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>> powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing source_id); COALESCE(p.source_id,'default') null safety, HAVING >= 1, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; SearchResult gains optional base_score, backlink_boost, salience_boost, recency_boost, exact_match_boost, graph_adjacency_boost, graph_cross_source_boost, session_demote_factor, reranker_delta + internal staging fields; Pinned by test/e2e/graph-signals-engine.test.ts. Two REQUIRED methods: deletePages(slugs, {sourceId}): Promise<string[]> (single-batch primitive returning slugs actually deleted) and resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>> (batch path→slug lookup); sourceId REQUIRED on both at the type level (asymmetric with single-row deletePage which keeps optional/'default'); both short-circuit on empty input and throw when > DELETE_BATCH_SIZE. softDeletePages(slugs, {sourceId}): Promise<string[]> is the batch soft-delete twin, mirroring deletePages' contract exactly (required sourceId, > DELETE_BATCH_SIZE throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug round-trip returning only the slugs that actually flipped active→soft-deleted — the deleted_at IS NULL predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side deleted_at filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via putPage's upsert; deletePage/deletePages remain the purge/teardown primitives). getStats(opts?) / getHealth(opts?) take an optional {sourceId?, sourceIds?} scope (same shape as sourceScopeOpts output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in src/core/ops/admin.ts; getHealth is a one-line delegation to src/core/engine-sql/health.ts. Embedding-signature stale-detection quartet: countStaleChunks(opts?) gains optional signature?: string widening the stale predicate from embedding IS NULL to ALSO include chunks whose JOINed page embedding_signature IS NOT NULL AND <> $signature (NULL signature is GRANDFATHERED, never counted; omit signature for the legacy NULL-only count); sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number> = SUM(LENGTH(chunk_text)) over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by gbrain sync --all cost preview via estimateCostFromChars; setPageEmbeddingSignature(slug, {sourceId?, signature}) stamps pages.embedding_signature after a page's chunks (re)embed, idempotent no-op when page absent; invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number> NULLs embedding+embedded_at on every chunk whose page signature is set AND differs, returning the count, called BEFORE listStaleChunks so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens findOrphanPages(opts?: {sourceId?, sourceIds?}) (candidate-side scoping; inbound links from any source unless scopeInbound). Pinned by test/sum-stale-chunk-chars.test.ts, test/embedding-signature-stale.test.ts, test/e2e/engine-parity.test.ts. Free-text alias layer: resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>> (READ; maps each normalized alias to declaring (slug, source_id) pairs, source-scoped) and setPageAliases(slug, sourceId, aliasNorms) (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the importFromContent ingest projection and the reindex --aliases backfill; parity across both engines, Pinned by test/search/page-aliases-engine.test.ts. searchVector in both engines injects the shared buildBestPerPagePoolCte per-page max-pool so a page surfaces on its strongest chunk. executeRawDirect(sql, params?, opts?) is the lock-hot-path sibling of executeRaw: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to executeRaw (no pooler). Both engines implement it; the Minion lock path (claim/renewLock) is the consumer. reconnect(ctx?: {error?}) is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last connect(), so callers (autopilot health probe, batchRetry) never disconnect() + bare connect() (which loses the config and throws database_url undefined forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a _reconnecting reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null> (identity precedence is content_hash OR frontmatter->>'id', both with deleted_at IS NULL); (2) resolveSlugs(partial, opts?) extended with {sourceId?, sourceIds?} so the MCP fuzzy get_page path scopes by source (field names match sourceScopeOpts(ctx) output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker ORDER BY score DESC, page_id ASC, chunk_id ASC in searchVector in both engines: on a score tie (basis-vector eval fixtures) older page_id wins, so a new index on pages cannot flip ranking on tied scores.

  • src/core/migrate-pending.ts — hasPendingMigrations (re-exported by migrate.ts): one version read against the generated schema-migrations/latest.generated.ts, so a connect never loads the migration registry.

  • src/core/migrate.ts — schema-migration runner. Re-exports MIGRATIONS from the generated registry src/core/schema-migrations/registry.generated.ts; each migration is one file src/core/schema-migrations/v<NNN>-<name>.ts (the source of truth for schema DDL history), with the Migration type in schema-migrations/types.ts and shared handler helpers (migrationNotice, dropInvalidConcurrentIndex, buildIndexOnline with its best-effort analyzeAfterIndexBuild (a failed ANALYZE warns with the repair command and never fails the build of a valid index), the fresh-install quiet flag) in schema-migrations/helpers.ts, a leaf that never imports migrate.ts. Migration carries sqlFor?: { postgres?, pglite? } (engine-specific SQL overrides sql) and transaction?: boolean (false for CREATE INDEX CONCURRENTLY, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on engine.kind for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via pg_index.indisvalid, plain CREATE INDEX on PGLite); v15 (minion_jobs.max_stalled default 1→5 + backfill non-terminal rows); v24 rls_backfill_missing_tables (sqlFor: { pglite: '' } no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash)) (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger auto_rls_on_create_table fires on ddl_command_end for WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO') running ALTER TABLE … ENABLE ROW LEVEL SECURITY on new public.* tables (no FORCE) + one-time backfill on every existing public.* base table whose comment doesn't match ^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,} (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via sqlFor.pglite: ''; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 pages_emotional_weight (pages.emotional_weight REAL NOT NULL DEFAULT 0.0, column-only metadata-only); v46 mcp_request_log_params_jsonb_normalize (UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string', idempotent); v60-v65 six-migration chain wiring source-scoping into oauth_clients — v60 (oauth_clients_source_id_fk: source_id TEXT NULL→'default' backfill + FK to sources(id) ON DELETE SET NULL), v61 (federated_read TEXT[] NOT NULL DEFAULT '{}'), v62 (explicit-CASE backfill so source_id IS NULL → '{}'), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to ON DELETE RESTRICT), v65 (GIN index for array-containment); v68 eval_candidates_embedding_column (eval_candidates.embedding_column TEXT NULL per-row provenance for gbrain eval replay to reproduce the same retrieval space; NULL-tolerant); v108 pages_embedding_signature (pages.embedding_signature TEXT NULL = <provider:model>:<dims> stamped via setPageEmbeddingSignature; GRANDFATHER — stale predicate is embedding_signature IS NOT NULL AND embedding_signature <> $current so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 sources_newest_content_at (sources.newest_content_at TIMESTAMPTZ durable newest-COMMIT HEAD committer time written by writeSyncAnchor, read by the REMOTE staleness path instead of shelling to git; fresh-install column in src/schema.sql, generated into both blobs, plus a bootstrap probe); v110 page_aliases ((id, source_id, alias_norm, slug, ...) with UNIQUE (source_id, alias_norm, slug) + lookup indexes on (source_id, alias_norm) and (source_id, slug); alias_norm is normalizeAlias() output so WRITE/READ key on the same form; also in src/core/pglite-schema.ts); v111 search_telemetry_rank1_columns (ADD COLUMN IF NOT EXISTS on both engines: sum_rank1_score, count_rank1, three buckets rank1_lt_solid/rank1_solid/rank1_high on search_telemetry — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 links_link_source_check_kebab_regex (opens link_source from the closed allowlist to a kebab-case format gate ^[a-z][a-z0-9]*(-[a-z0-9]+)*$ + char_length<=64; Postgres branch uses NOT VALID + VALIDATE CONSTRAINT with transaction:false, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 code_edges_source_backfill_and_callee_index (idempotent: backfills NULL code_edges_symbol/code_edges_chunk source_id from each edge's from_chunk page — a NULL never matches a scoped AND source_id = … filter, so scoped code-callers/code-callees would return 0 rows on multi-source brains — plus plain CREATE INDEX on from_symbol_qualified for both edge tables, which had no index and seq-scanned per BFS node); v129 dream_verdicts_triage_v1_columns (additive ADD COLUMN IF NOT EXISTS widening dream_verdicts into a scored triage record — score, content_type, segments, entities, model, triage_version; legacy rows keep score NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since dream_verdicts is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in test/schema-bootstrap-coverage.test.ts rather than bootstrap probes); v143 dream_verdicts_ttl (30-day expires_at TTL: nullable ADD COLUMN + SET DEFAULT run BEFORE the judged_at-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail SET NOT NULL on every retry; on Postgres the schema blob's dream_verdicts_expires_idx forward-references the column, so forward-reference-bootstrap.ts probes + ALTERs it before the blob replays, and both engines' getDreamVerdict read predicate is NULL-tolerant — expires_at IS NULL OR expires_at > now() — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY runMigrations pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: repairTimelineDedupIndex (timeline_dedup_index, see timeline-dedup-repair.ts) and repairPagesUpsertArbiter (pages_source_slug_key, see pages-upsert-arbiter.ts) are not version-gated at all; repairLinkSourceCheck (links_link_source_check, see link-source-check-repair.ts) runs only when the ledger is already >= LINK_SOURCE_GATE_MIGRATION_VERSION (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no link_source column). All three are best-effort + idempotent; doctor surfaces each drift independently. retry-matcher.ts and timeline-dedup-repair.ts are static dependencies because runMigrations() executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: pages_dedup_partial_index adds CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL. Postgres uses CREATE INDEX CONCURRENTLY with transaction: false + pre-drops any invalid remnant; PGLite uses plain CREATE INDEX. Powers findDuplicatePage hot path (O(log n) instead of O(n)). v74 mcp_spend_log uses BTREE on (client_id, created_at) + (token_name, created_at) — date_trunc('day', TIMESTAMPTZ) is NOT IMMUTABLE so can't appear in index expressions; a created_at range scan covers the per-day rollup. v75 embedding_multimodal_column is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with page-state/revision-backfill-schema.ts:resumePageRevisionBackfill while pages.knowledge_revision is nullable (#5216): the page-state schema adds sources.incarnation and pages.knowledge_revision nullable with a separate default (no volatile-default table rewrite on replay; an empty pages is constrained at once), rows are backfilled in committed id batches with a config cursor (page_state.revision_backfill), a failing row is isolated and retried at most three passes, each update grants only its rows' sources to the managed writer guard (gbrain.write_sources, transaction-local), and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. With the schema version current no ordinary command runs a pass, so gbrain apply-migrations --force-schema (REVISION_BACKFILL_RESUME_COMMAND) resumes it; readRevisionBackfillStatus feeds doctor revision_backfill (src/commands/doctor/checks/revision-backfill.ts: ok when NOT NULL, warn with the pending count, the failed rows by page and the resume command, or the repair orphan-children preview when only spent rows remain). The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as backfill_pending and assertPageRevision refuses revision-bound writes with revision_backfill_pending (page-revision-backfill-5216.test.ts). Size ceiling: scripts/module-size-limits.tsv (per-change raise history: git log -p on that file). The runner (ordering, retry, verify, repair-handler hooks and the static helper imports engine-live paths require) has a plain ratchet ceiling; migrations no longer live in this file.

  • 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 squatted npm name; README install warning). getEmbeddedPgliteOptions() memoizes one build per process and hands PGLite compiled WebAssembly.Modules + fs-bundle Blob + vector/pg_trgm extensions via PGliteOptions (the tarballs are gunzipped and untarred in memory, and lazyExtension writes their files into PGLite's filesystem in the extension's init, after the backend starts, so postgres loads each .so on first use instead of PGLite preloading both on every open, about 30 ms; readExtensionFiles refuses any entry that is not a file or directory), plus startParams = PGLite's defaults then PGLITE_START_PARAM_OVERRIDES (no parallel maintenance workers, max_wal_size=8GB: an HNSW build fits the WASM heap, its WAL under the checkpoint trigger). withSharedBuffers appends -c shared_buffers=<size> when EngineConfig.pglite_shared_buffers is set: connectEngineForServe sets ONE_SHOT_READ_SHARED_BUFFERS (32MB) for a one-shot read-scope CLI process (shared op path, gbrain call <read op>, search, sources list), because the backend zero-fills the whole pool at start (about 55 ms for the 128MB default) and one read never fills it; serve and writes keep the default. The package itself is a type-only import plus one lazy await import('@electric-sql/pglite') inside build() after the resolver ran: the module must load without the package, or a missing install dies with the raw "Cannot find module" before the tier-3 sentence (#6512). Pinned by test/pglite-embedded-assets.test.ts + test/pglite-hoisted-install.test.ts (bun add -g-shaped hoisted layout, spawned with bun --no-install so script auto-install cannot mask a missing package).

  • src/core/pglite-engine.ts — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The methods of every migrated storage domain (the migrated rows of scripts/engine-sql-baseline.tsv) are one-line delegations into src/core/engine-sql/<domain>.ts over the private engineSql getter (a fresh PGLite adapter over this.db per access, so transaction clones run inside their transaction; outside one, writes take the #5449 checkpoint guard); PGLite-only code stays under src/core/pglite-engine/. listLinkSources({sourceId?, sourceIds?}) returns distinct link_source provenances + counts (scoped on from/to/origin; one implementation in engine-sql/links.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 PGLITE_SCHEMA_SQL — a one-line delegation to the shared src/core/engine-sql/bootstrap.ts (see its entry) with the PGLite dialect hooks; 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. deletePages(slugs, {sourceId}) + resolveSlugsByPaths(paths, {sourceId}) (in engine-sql/pages.ts) bind slug = ANY($1::text[]), 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); one SQL copy in src/core/engine-sql/chunks.ts, shared with PostgresEngine. 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 the chunk upsert (engine-sql/chunks.ts upsertChunksOnce, behind _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. Outermost transaction() calls run PgliteCheckpointGuard (src/core/pglite-engine/checkpoint-guard.ts) before BEGIN: when WAL since the last redo point passes half the automatic-checkpoint distance (256 MB with the default 1 GB max_wal_size) it issues a top-level CHECKPOINT (each probe is queued with its own transaction, so concurrent callers see their predecessors' WAL, and the whole guarded operation is admitted once into the datastore's shutdown drain), because PGLite runs the automatic checkpoint inline inside the WAL write that crosses the trigger and that nested checkpoint spins forever (#5449/#5284). Savepoint transactions never checkpoint; the direct read-only vector-search transaction and other direct driver transactions are not guarded. A failed WAL probe proceeds with a once-per-process warning; a failed CHECKPOINT refuses before BEGIN with a GBrainError naming gbrain pglite-repair. Tests: test/pglite-checkpoint-guard.test.ts; the large-store harness scripts/pglite-checkpoint-harness/supervisor.ts (external supervisor, WAL-bound assertion) runs outside CI. Size ceiling: scripts/module-size-limits.tsv (per-change raise history: git log -p on that file). The ceiling covers every BrainEngine method whose SQL has not moved to src/core/engine-sql/ (rows in scripts/engine-sql-baseline.tsv); each storage feature lands as a parity twin in both engines (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, statement-cache and WAL-checkpoint lifecycle); refactor wave 1 moves shared SQL to src/core/engine-sql/.

  • src/core/pglite-lifecycle.ts — tracks admitted datastore statements and transactions across early-null, rejects new work through captured handles, and supplies the typed closing error. A successful same-datastore reopen resumes its stopped persistence consumer only after database open and filesystem-registry success; replaced or disposed services unregister their lifecycle hooks. Pending or failed close never resets the admission barrier. Both engines expose registerBeforeDisconnect(stop) (returns unregister) as a mandatory resident-consumer barrier and transactionDirect(fn) for short control work on the existing direct route; nested calls stay in their transaction.

  • 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; peekLock also reports a serve holder's transport (http from its recorded --http argv) and acquiredAt, in one metadata read. heldLockFor(dataDir) answers "does this process hold it" from the in-memory retained handles (no file access while none are held). 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. An owner legacyOwnerUnverified cannot prove dead (bad or missing metadata, no PID, Linux pid_ns/boot_id mismatch) throws LegacyOwnerUnverifiedError (reason legacy_owner_unverified, not retryable, ask_user fix: the pglite-repair --legacy-lock preview). 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, ANALYZE/VACUUM (PostgreSQL keeps a prepared plan across a statistics refresh, so a plan made before the table had statistics would outlive planner-stats' first-read ANALYZE) 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. configurePgliteCodecs removes composite-row array parsers after connect, since gbrain never selects those arrays, and replaces PGlite's per-byte bytea codec with Buffer's hex codec (a 4 MiB bytea batch no longer allocates ~250 MB of garbage). Pinned by test/pglite-statements.test.ts.

Continued in Engines (1/2, continued).