Garry's Opinionated OpenClaw/Hermes Agent Brain
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
searchVectorgeneration 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 (seesearch/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.tsand 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 explicitGBRAIN_DIRECT_DATABASE_URLor 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 everygbrain_cycle_locksacquisition a UUID; refresh/release, takeover/reaper and manual/age-gated breaks match (id, holder_pid, acquisition_token), never theacquired_atepoch text, which is diagnostics only (#6028).withRefreshingLockalways 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, survivingengine.reconnect(). Renewal deadlines start before the database round trip.performSynccomposes this signal with caller cancellation.inspectLock,listStaleLocks,listLiveLocks,classifyHolderLivenessand namespace-scopedreapDeadHolderLockskeep 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 betweengbrain db-repair(writer) and doctor'sdb_repair_recurrencecheck (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'}— onlyappliedrows 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) — EXCEPTappliedrows 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 ownsrewriteCooldownBlocked(24h per (reason, action), rewrite tier only).src/core/db.ts— Connection management, schema initialization.resolveSessionTimeouts()returnsstatement_timeout+idle_in_transaction_session_timeout(defaults 5min each, env-overridable viaGBRAIN_STATEMENT_TIMEOUT/GBRAIN_IDLE_TX_TIMEOUT/GBRAIN_CLIENT_CHECK_INTERVAL). Bothconnect()(module singleton) andPostgresEngine.connect()(worker pool) consume the result via postgres.js'sconnectionoption, sending GUCs as startup parameters that survive PgBouncer transaction mode (setSessionDefaultskept as a back-compat no-op shim).connect(config, { onpoisoned })passes the owner engine's poisoned-discard hook to the singleton pool and returnsPromise<boolean>—trueiff THIS call created the module singleton,falseif it joined an existing one; the decision is atomic (noawaitbetween theif (sql)null-check and the synchronoussql = postgres(...)assignment), so two concurrent module connects can't both claim creation.PostgresEnginestores the return as its_ownsModuleSingletontoken and only the creating engine maydb.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 modulesqlis only ever nulled bydb.disconnect()(postgres.js auto-reconnects its own internal pool and never touches our reference).disconnect()snapshots + nullssqlbefore awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes throughendPoolBounded(pool)— a gbrain-ownedPromise.raceofpool.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.tsends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack.resolveMaxLifetimeSeconds(env?)— explicit client-poolmax_lifetimefor all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default;GBRAIN_POOL_MAX_LIFETIME_Soverrides, 0 disables; warn-once on invalid). Pinned bytest/db-pool-max-lifetime.test.ts.resolveUrlConnectTimeout(url)suppliesconnect_timeoutto 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 bytest/db-connect-timeout.test.ts.connectWithRetryretries theisRetryableConnErrorset (3 attempts, 1s/2s backoff;GBRAIN_NO_RETRY_CONNECT=1makes it one);retryConnectTimeout: trueadds postgres.jsCONNECT_TIMEOUT(isConnectTimeoutErrorinretry-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 bytest/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;readPoolPipelineOptionsspreads it):0for a transaction-mode URL (port 6543 or?prepare=false, read from the URL becauseGBRAIN_PREPAREwins insideresolvePrepare) orGBRAIN_PREPARE=0, the key omitted (driver default 100, neverundefined) for a session pooler or direct URL, and omitted whenever the URL namesmax_pipelineorPGMAX_PIPELINEis non-empty, since the driver lets the options object outrank both; pinned bytest/read-pool-pipeline-6543.test.tsandtest/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 atgbrain servestartup, serve boots oncreateDegradedEngine(a concrete object whose method set is enumerated from PostgresEngine's prototype at construction;kindis 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 thedatabase_errorenvelope + marker. Thereconnectcallback 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 + sendstools/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 getsDegradedRecoveredRetryError, 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 silentundefined);DEGRADED_LAST_ERRORis a read-only accessor for the stored diagnosis (drives the HTTP/healthdegraded reason without consuming a reconnect). Serve-side degraded posture: source scope honors a validatedGBRAIN_SOURCE(tierenv) before seed_default, andstdioVisibleToolsfail-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 ridePostgresEngine.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 switchGBRAIN_SERVE_DEGRADED=0(orfalse); structured[gbrain-serve] DEGRADED/RECOVEREDstderr lines.degraded-marker.tsis 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'sconn_refusedauto arm.GBRAIN_PG_CONTAINER = 'gbrain-postgres'/GBRAIN_PG_IMAGE = 'pgvector/pgvector:pg16'/GBRAIN_PG_HOST_PORT = 5434live 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 viainspectCredentials(docker inspect →POSTGRES_PASSWORDenv + 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 namedgbrain-pgdatavolume so a container recreate never loses the brain; the password rides the child ENVIRONMENT (bare-e POSTGRES_PASSWORD— argv is world-readable inps);docker rungets a 10-minute timeout (the first run synchronously pulls the image; 30s stays for cheap ps/inspect/start calls).isGbrainDockerUrlis 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'svector/halfvectype, HNSW gated onhnswIndexExpected(dims > 2000 skip the index; exact scans stay correct — 2048d targets work); the HNSW indexes of every rebuilt text-embedding column (content_chunkscanonical and custom, plus eachTEXT_EMBEDDING_DIM_PINNED_TABLESentry viatransitionDimPinnedColumn's returned definition; the allowed set isDEFERRED_ANN_TABLES) are NOT rebuilt in the transaction but recorded in the marker asdeferred_ann_indexes(recordDeferredAnnIndexes) and built after the re-embed drain bysrc/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;verifyMigrationCompleteblocks on pending or INVALID ANN indexes (migrate-embeddings-ann-deferred-5088.serial.test.ts); image/multimodal columns deliberately untouched; AFTER commit it clearsembedded_atin 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-awarereranker_warning,dim_changevia the sharedschemaRebuildNeeded(null ⇒ rebuild, same computation apply uses).applyEmbeddingMigration: env≠target refusal (detectEnvOverride;detectEnvPresencedrives the ==target notice) → marker v2 write (same-target re-apply preservesstarted_at; retarget recordssupersededhistory) → 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 viaembedding-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 whosemodelcontradicts a page already stamped with the target signature),missing_embeddingsresidue, 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 trustsfrom_model.completeEmbeddingMigration: marker delete + completion stamp in ONE transaction (no lost-receipt crash window); accepts content-freeextra(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-sideembedQuery+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 bytest/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 plusraw_sql; only PGLite reportssingle_ownerand only Postgres reportspostgres_admin.capabilitiesForEngineKindreturns a fresh set per engine.requiredCapabilities(consumer, name)answers['raw_sql']for any name without a row, andmissingCapabilities(engine, consumer, name)lists what an engine lacks (empty on both SQL engines). Callers ask a capability instead of branching onengine.kind. Pinned bytest/engine-capabilities.test.ts.src/core/engine-constants.ts— single source of truth for engine batch-sizing constants. ExportsDELETE_BATCH_SIZE = 500consumed by both engines'deletePages+resolveSlugsByPathsand by the sync delete + rename loops. Lives outsideengine.ts(the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification. Also exportsTRAVERSE_PATH_ROW_CAP = 5000, the raw-row bound ontraversePaths/traversePathsDetailed(both enginesLIMIT CAP + 1; the extra row is the truncation probe; counted before edge dedup), andTRAVERSE_WALK_ROW_CAP = 20000, the bound on simple-path rows the recursive walks enumerate (traverseGraphandtraversePaths*, both engines). The walk CTE is pulled throughLIMITso a dense hub stops enumerating, rows are deduped to(page, depth)before the edge join or the per-node link aggregation, andtraversePathsstops recursing one layer early because the deepest layer only terminates edges. A capped walk setstruncatedontraversePathsDetailed.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-onlyADD COLUMN IF NOT EXISTS, plus thesourcestable + default seed andSET DEFAULTwhere the upgrade window needs it); fresh installs and current brains no-op. Callers:PGLiteEngine.initSchema(pgliteBootstrapTarget(db)),PostgresEngine.initSchemaanddb.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-onlydream_verdicts.expires_atprobe + ALTER (insidedialect-only:postgresmarkers so the PGLite coverage check does not count it), and the per-engine position of the v39content_chunksALTER. 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 bytest/schema-bootstrap-coverage.test.ts(parses this file),test/bootstrap.test.tsandtest/e2e/postgres-bootstrap.test.ts; per-probe inventory indocs/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 thanMAX_SEARCH_LIMIT. ExportsLinkBatchInput/TimelineBatchInputfor the bulk-insert API (addLinksBatch/addTimelineEntriesBatch).readonly kind: 'postgres' | 'pglite'discriminator letssrc/core/migrate.tsand others branch withoutinstanceof+ 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).PageFiltershassort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'+PAGE_SORT_SQLwhitelist consumed by both engines.listAllPageRefs(): Promise<Array<{slug, source_id}>>ordered by(source_id, slug)— cheap cross-source enumeration instead of agetAllSlugs()→getPage(slug)N+1 (which would silently default tosource_id='default'); parity across postgres-engine.ts + pglite-engine.ts; Pinned bytest/e2e/multi-source-bug-class.test.ts.SearchOpts+PageFiltersaddsourceIds?: string[](federated read axis; both engines applyWHERE source_id = ANY($N::text[])when set, preserve scalarsourceIdfast path when unset);traverseGraph(slug, depth, opts?)andtraversePaths(slug, opts?)acceptopts.sourceId/opts.sourceIds.traversePathsDetailed(slug, opts?)returns{ paths: GraphPath[], truncated }— the final SELECT of the path-enumerating recursive CTE is bounded atTRAVERSE_PATH_ROW_CAP + 1rows on both engines (the probe row signals overflow;ORDER BY depthmeans 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, sopaths.lengthalone cannot reveal truncation) andtraversePathsis its.pathsprojection. EachGraphPathcarriesfrom_source_id/to_source_idand the edge dedup keys on page ids; eachtraverseGraphGraphNodecarriessource_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 theslug_aliasestable does not exist yet);resolveSlugWithAliasis its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read tosource_id. The by-slug read methods carry the same federated axis:getTags/getLinks/getBacklinks/getChunksopts andTimelineOpts(consumed bygetTimeline) acceptsourceIds?: string[]taking precedence over the scalarsourceId(source_id = ANY($::text[])scoping the slug→page-id lookup);getChunkPage(slug, {fromIndex, limit, ...scope})is get_chunks' paged read: the same predicate asgetChunks, 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);getChunksfalls 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 (getChunksWithEmbeddingsstays 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.traverseGraphopts hasfrontierCap?: number(per-iteration recursive-CTE cap, approx per-BFS-layer); return typePromise<GraphNode[]>for MCP wire stability; exportTraverseGraphOpts; Postgres uses parenthesizedLIMIT N ORDER BY (slug, id)inside the recursive term, PGLite mirrors with positional params; Pinned bytest/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 sogbrain syncsees the canonical as unchanged after fence merge);migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)UPDATEsentity_slug+source_markdown_slugon every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsettingrow_numpast the canonical page's current MAX(row_num) (all rows incl. expired — the partialidx_facts_fence_keyonly excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity attest/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 differingsource_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;SearchResultgains optionalbase_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 bytest/e2e/graph-signals-engine.test.ts. Two REQUIRED methods:deletePages(slugs, {sourceId}): Promise<string[]>(single-batch primitive returning slugs actually deleted) andresolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>(batch path→slug lookup);sourceIdREQUIRED on both at the type level (asymmetric with single-rowdeletePagewhich 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, mirroringdeletePages' contract exactly (requiredsourceId,> DELETE_BATCH_SIZEthrows, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): oneUPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING sluground-trip returning only the slugs that actually flipped active→soft-deleted — thedeleted_at IS NULLpredicate 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-sidedeleted_atfilters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives viaputPage's upsert;deletePage/deletePagesremain the purge/teardown primitives).getStats(opts?)/getHealth(opts?)take an optional{sourceId?, sourceIds?}scope (same shape assourceScopeOptsoutput): 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 insrc/core/ops/admin.ts;getHealthis a one-line delegation tosrc/core/engine-sql/health.ts. Embedding-signature stale-detection quartet:countStaleChunks(opts?)gains optionalsignature?: stringwidening the stale predicate fromembedding IS NULLto ALSO include chunks whose JOINed pageembedding_signature IS NOT NULL AND <> $signature(NULL signature is GRANDFATHERED, never counted; omitsignaturefor 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 bygbrain sync --allcost preview viaestimateCostFromChars;setPageEmbeddingSignature(slug, {sourceId?, signature})stampspages.embedding_signatureafter a page's chunks (re)embed, idempotent no-op when page absent;invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>NULLsembedding+embedded_aton every chunk whose page signature is set AND differs, returning the count, called BEFORElistStaleChunksso signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). WidensfindOrphanPages(opts?: {sourceId?, sourceIds?})(candidate-side scoping; inbound links from any source unlessscopeInbound). Pinned bytest/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) andsetPageAliases(slug, sourceId, aliasNorms)(WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by theimportFromContentingest projection and thereindex --aliasesbackfill; parity across both engines, Pinned bytest/search/page-aliases-engine.test.ts.searchVectorin both engines injects the sharedbuildBestPerPagePoolCteper-page max-pool so a page surfaces on its strongest chunk.executeRawDirect(sql, params?, opts?)is the lock-hot-path sibling ofexecuteRaw: 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 toexecuteRaw(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 lastconnect(), so callers (autopilot health probe,batchRetry) neverdisconnect()+ bareconnect()(which loses the config and throwsdatabase_url undefinedforever, and opens a null-connection window). PostgresEngine rebuilds its pool with a_reconnectingreentrancy 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) optionalfindDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>(identity precedence is content_hash OR frontmatter->>'id', both withdeleted_at IS NULL); (2)resolveSlugs(partial, opts?)extended with{sourceId?, sourceIds?}so the MCP fuzzyget_pagepath scopes by source (field names matchsourceScopeOpts(ctx)output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreakerORDER BY score DESC, page_id ASC, chunk_id ASCinsearchVectorin both engines: on a score tie (basis-vector eval fixtures) olderpage_idwins, so a new index onpagescannot flip ranking on tied scores.src/core/migrate-pending.ts—hasPendingMigrations(re-exported bymigrate.ts): oneversionread against the generatedschema-migrations/latest.generated.ts, so a connect never loads the migration registry.src/core/migrate.ts— schema-migration runner. Re-exportsMIGRATIONSfrom the generated registrysrc/core/schema-migrations/registry.generated.ts; each migration is one filesrc/core/schema-migrations/v<NNN>-<name>.ts(the source of truth for schema DDL history), with theMigrationtype inschema-migrations/types.tsand shared handler helpers (migrationNotice,dropInvalidConcurrentIndex,buildIndexOnlinewith its best-effortanalyzeAfterIndexBuild(a failed ANALYZE warns with the repair command and never fails the build of a valid index), the fresh-install quiet flag) inschema-migrations/helpers.ts, a leaf that never importsmigrate.ts.MigrationcarriessqlFor?: { postgres?, pglite? }(engine-specific SQL overridessql) andtransaction?: boolean(false forCREATE INDEX CONCURRENTLY, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches onengine.kindfor CONCURRENTLY-on-Postgres with invalid-remnant pre-drop viapg_index.indisvalid, plainCREATE INDEXon PGLite); v15 (minion_jobs.max_stalleddefault 1→5 + backfill non-terminal rows); v24rls_backfill_missing_tables(sqlFor: { pglite: '' }no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30dream_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 triggerauto_rls_on_create_tablefires onddl_command_endforWHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')runningALTER TABLE … ENABLE ROW LEVEL SECURITYon newpublic.*tables (no FORCE) + one-time backfill on every existingpublic.*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 viasqlFor.pglite: ''; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40pages_emotional_weight(pages.emotional_weight REAL NOT NULL DEFAULT 0.0, column-only metadata-only); v46mcp_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 intooauth_clients— v60 (oauth_clients_source_id_fk:source_id TEXTNULL→'default'backfill + FK tosources(id) ON DELETE SET NULL), v61 (federated_read TEXT[] NOT NULL DEFAULT '{}'), v62 (explicit-CASE backfill sosource_id IS NULL→'{}'), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped toON DELETE RESTRICT), v65 (GIN index for array-containment); v68eval_candidates_embedding_column(eval_candidates.embedding_column TEXT NULLper-row provenance forgbrain eval replayto reproduce the same retrieval space; NULL-tolerant); v108pages_embedding_signature(pages.embedding_signature TEXT NULL=<provider:model>:<dims>stamped viasetPageEmbeddingSignature; GRANDFATHER — stale predicate isembedding_signature IS NOT NULL AND embedding_signature <> $currentso NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109sources_newest_content_at(sources.newest_content_at TIMESTAMPTZdurable newest-COMMIT HEAD committer time written bywriteSyncAnchor, read by the REMOTE staleness path instead of shelling to git; fresh-install column insrc/schema.sql, generated into both blobs, plus a bootstrap probe); v110page_aliases((id, source_id, alias_norm, slug, ...)withUNIQUE (source_id, alias_norm, slug)+ lookup indexes on(source_id, alias_norm)and(source_id, slug);alias_normisnormalizeAlias()output so WRITE/READ key on the same form; also insrc/core/pglite-schema.ts); v111search_telemetry_rank1_columns(ADD COLUMN IF NOT EXISTSon both engines:sum_rank1_score,count_rank1, three bucketsrank1_lt_solid/rank1_solid/rank1_highonsearch_telemetry— aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114links_link_source_check_kebab_regex(openslink_sourcefrom the closed allowlist to a kebab-case format gate^[a-z][a-z0-9]*(-[a-z0-9]+)*$+char_length<=64; Postgres branch usesNOT VALID+VALIDATE CONSTRAINTwithtransaction:false, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116code_edges_source_backfill_and_callee_index(idempotent: backfills NULLcode_edges_symbol/code_edges_chunksource_idfrom each edge'sfrom_chunkpage — a NULL never matches a scopedAND source_id = …filter, so scopedcode-callers/code-calleeswould return 0 rows on multi-source brains — plus plainCREATE INDEXonfrom_symbol_qualifiedfor both edge tables, which had no index and seq-scanned per BFS node); v129dream_verdicts_triage_v1_columns(additiveADD COLUMN IF NOT EXISTSwideningdream_verdictsinto a scored triage record —score,content_type,segments,entities,model,triage_version; legacy rows keepscoreNULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines sincedream_verdictsis migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route intest/schema-bootstrap-coverage.test.tsrather than bootstrap probes); v143dream_verdicts_ttl(30-dayexpires_atTTL: nullableADD COLUMN+SET DEFAULTrun BEFORE thejudged_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 failSET NOT NULLon every retry; on Postgres the schema blob'sdream_verdicts_expires_idxforward-references the column, soforward-reference-bootstrap.tsprobes + ALTERs it before the blob replays, and both engines'getDreamVerdictread 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 EVERYrunMigrationspass, 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, seetimeline-dedup-repair.ts) andrepairPagesUpsertArbiter(pages_source_slug_key, seepages-upsert-arbiter.ts) are not version-gated at all;repairLinkSourceCheck(links_link_source_check, seelink-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 nolink_sourcecolumn). All three are best-effort + idempotent;doctorsurfaces each drift independently.retry-matcher.tsandtimeline-dedup-repair.tsare static dependencies becauserunMigrations()executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95:pages_dedup_partial_indexaddsCREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL. Postgres usesCREATE INDEX CONCURRENTLYwithtransaction: false+ pre-drops any invalid remnant; PGLite uses plainCREATE INDEX. PowersfindDuplicatePagehot path (O(log n) instead of O(n)). v74mcp_spend_loguses BTREE on(client_id, created_at)+(token_name, created_at)—date_trunc('day', TIMESTAMPTZ)is NOT IMMUTABLE so can't appear in index expressions; acreated_atrange scan covers the per-day rollup. v75embedding_multimodal_columnis column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends withpage-state/revision-backfill-schema.ts:resumePageRevisionBackfillwhilepages.knowledge_revisionis nullable (#5216): the page-state schema addssources.incarnationandpages.knowledge_revisionnullable with a separate default (no volatile-default table rewrite on replay; an emptypagesis 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, sogbrain apply-migrations --force-schema(REVISION_BACKFILL_RESUME_COMMAND) resumes it;readRevisionBackfillStatusfeeds doctorrevision_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 therepair orphan-childrenpreview when only spent rows remain). The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision asbackfill_pendingandassertPageRevisionrefuses revision-bound writes withrevision_backfill_pending(page-revision-backfill-5216.test.ts). Size ceiling:scripts/module-size-limits.tsv(per-change raise history:git log -pon 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.tsis the bundler ANCHOR: five literalwith { type: 'file' }imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package'sexportsmap 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()inpglite-embedded-assets.tsis the tiered resolver: tier 1 dynamicallyimport()s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe@electric-sql/pgliteto 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.resolvethencreateRequire— 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 compiledWebAssembly.Modules + fs-bundle Blob +vector/pg_trgmextensions viaPGliteOptions(the tarballs are gunzipped and untarred in memory, andlazyExtensionwrites their files into PGLite's filesystem in the extension'sinit, after the backend starts, so postgres loads each.soon first use instead of PGLite preloading both on every open, about 30 ms;readExtensionFilesrefuses any entry that is not a file or directory), plusstartParams= PGLite's defaults thenPGLITE_START_PARAM_OVERRIDES(no parallel maintenance workers,max_wal_size=8GB: an HNSW build fits the WASM heap, its WAL under the checkpoint trigger).withSharedBuffersappends-c shared_buffers=<size>whenEngineConfig.pglite_shared_buffersis set:connectEngineForServesetsONE_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 lazyawait import('@electric-sql/pglite')insidebuild()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 bytest/pglite-embedded-assets.test.ts+test/pglite-hoisted-install.test.ts(bun add -g-shaped hoisted layout, spawned withbun --no-installso 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 (themigratedrows ofscripts/engine-sql-baseline.tsv) are one-line delegations intosrc/core/engine-sql/<domain>.tsover the privateengineSqlgetter (a fresh PGLite adapter overthis.dbper access, so transaction clones run inside their transaction; outside one, writes take the #5449 checkpoint guard); PGLite-only code stays undersrc/core/pglite-engine/.listLinkSources({sourceId?, sourceIds?})returns distinctlink_sourceprovenances + counts (scoped on from/to/origin; one implementation inengine-sql/links.ts) poweringgbrain link-sources.addLinksBatch/addTimelineEntriesBatch/addTakesBatchpass the whole batch as one JSONB document viajsonb_to_recordset(($1::jsonb)->'rows')(bound throughexecuteRawJsonbwith a{ rows }wrapper; rows built by the sharedsrc/core/batch-rows.tshelpers, NUL-stripped), and arebatchRetry-wrapped.connect()retries a failed in-memoryPGlite.create()once, cold, only while no database is attached. The retry omits the snapshot and clears its loaded flag soinitSchema()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 thewasm-abortverdict 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 viaattemptWalRepairAndRetry(static import frompglite-repair.ts, per the engine-live rule; the retry create ispreservingProcessExitCode-wrapped; success sets the publicwalRepairReceiptfield + printsbuildWalRepairNoticeto 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 reportspglite_closingwhile 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/searchKeywordChunksmultiplyts_rankby the source-factor CASE at chunk grain;searchVectoris a two-stage CTE — inner CTE keepsORDER BY cc.embedding <=> vecso HNSW stays usable, outer SELECT re-ranks byraw_score * source_factor, inner LIMIT scales with offset to preserve pagination.searchTakes/searchTakesVectortake fullSearchOptsand apply the standard source-scope predicates (federatedsourceIds[]wins over scalarsourceId, via the joined page'ssource_id) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned bytest/e2e/think-source-isolation-pglite.test.ts.initSchema()callsapplyForwardReferenceBootstrap()BEFORE replaying PGLITE_SCHEMA_SQL — a one-line delegation to the sharedsrc/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).getBrainScorereturns 100/100 with full breakdown (35/25/15/15/10) whenpageCount === 0(vacuous truth — empty brain has no coverage problem); Pinned bytest/brain-score-breakdown.test.tsempty-brain assertion +test/doctor-report-remote.serial.test.ts.PGlite.create()runs insidepreservingProcessExitCode: PGLite's Emscripten runtime writes its own status intoprocess.exitCode(99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigningundefinedcannot 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 incli-force-exit.tsand never readsprocess.exitCodeback. ExportsclassifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'+buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)+stringifyPgliteInitError(err)+buildWalRepairNotice(receipt)+ thePgliteInitRepairContexttype, routing the catch-block hint by failure shape (bunfsmatches literal$$bunfsORENOENT[\s\S]*pglite\.dataco-occurrence, surfaces a paste-readybun 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 toreinit-pglite;wasm-abortmatches the real production shapesAborted()/RuntimeError/unreachableplus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (pglite-repair→ rebuild → engine switch) + what auto-repair did perctxincl. the honesty-criticalfailed-not-restoredarm, and links the upstream tracking issue;unknownis platform-gated).stringifyPgliteInitErroralso surfaces message-less Emscripten objects (ErrnoError (errno N)) instead of[object Object]. Pinned bytest/pglite-init-classifier.test.ts+test/pglite-wal-repair.serial.test.ts+test/fix-wave-structural.test.ts.deletePages(slugs, {sourceId})+resolveSlugsByPaths(paths, {sourceId})(inengine-sql/pages.ts) bindslug = ANY($1::text[]), caller-chunking primitive throwing when input exceedsDELETE_BATCH_SIZE,deletePagesreturnsRETURNING slugrows so callers filterpagesAffectedto confirmed deletes. Implements the embedding-signature stale-detection quartet —sumStaleChunkChars({sourceId?, signature?}),setPageEmbeddingSignature(slug, {sourceId?, signature}),invalidateStaleSignatureEmbeddings({signature, sourceId?}), widenedcountStaleChunks({sourceId?, signature?})(thesignatureopt widens viaJOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature), NULL grandfathered); one SQL copy insrc/core/engine-sql/chunks.ts, shared with PostgresEngine. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (retry, ontology, recency decay) avoid dynamicimport(); the only lazy dynamic imports areai/gateway.tsininitSchemaand the chunk upsert (engine-sql/chunks.tsupsertChunksOnce, behind_upsertChunksOnce), line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.getRawDatapushesp.deleted_at IS NULLinto itswhere[]unlessopts.includeDeleted— parity twin of the Postgresalivefragment; see the postgres-engine.ts entry. Outermosttransaction()calls runPgliteCheckpointGuard(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 GBmax_wal_size) it issues a top-levelCHECKPOINT(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 failedCHECKPOINTrefuses before BEGIN with aGBrainErrornaminggbrain pglite-repair. Tests:test/pglite-checkpoint-guard.test.ts; the large-store harnessscripts/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 -pon that file). The ceiling covers every BrainEngine method whose SQL has not moved tosrc/core/engine-sql/(rows inscripts/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 tosrc/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 exposeregisterBeforeDisconnect(stop)(returns unregister) as a mandatory resident-consumer barrier andtransactionDirect(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.lockretained inode and the native kernel binding..gbrain-lock/lockretains PID, structured argv, command/subcommand and heartbeat diagnostics forinspectLockHolder/peekLockand engine-free IPC routing;peekLockalso reports a serve holder's transport (httpfrom its recorded--httpargv) andacquiredAt, 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 ownerlegacyOwnerUnverifiedcannot prove dead (bad or missing metadata, no PID, Linux pid_ns/boot_id mismatch) throwsLegacyOwnerUnverifiedError(reasonlegacy_owner_unverified, not retryable, ask_user fix: thepglite-repair --legacy-lockpreview). 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;msSinceLastReapreads 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._attachDatabaseroutes the root handle'squery/execthrough it andtransaction()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 ofdb.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/DEALLOCATEtext,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-controlexecclear the cache, retired names are closed in the next prepare batch, an instance-levelquery/execoverride (test seams) takes precedence on the root handle, and_closeInternaldrops the cache with the database so a disconnected engine does not retain its PGLite instance.configurePgliteCodecsremoves 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 bytest/pglite-statements.test.ts.
Continued in Engines (1/2, continued).