Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(pglite): the assets module loads without @electric-sql/pglite so its tier-3 diagnostic is reachable
garrytance69477582b7
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex b7dd8234c8..c6201bd4ef 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -32,7 +32,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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`, 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.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`, plus `PGLITE_START_PARAMS` (no parallel maintenance workers, `max_wal_size=8GB`: an HNSW build fits the WASM heap, its WAL under the checkpoint trigger). Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (`bun add -g`-shaped hoisted layout).+- `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.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`, 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). 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 (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; 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/`.diff --git a/src/core/pglite-embedded-assets.ts b/src/core/pglite-embedded-assets.tsindex eea62039b9..91a099bfcd 100644--- a/src/core/pglite-embedded-assets.ts+++ b/src/core/pglite-embedded-assets.ts@@ -50,7 +50,7 @@ import { createRequire } from 'node:module';import { tmpdir } from 'node:os';import { join, dirname } from 'node:path';import { createHash } from 'node:crypto';-import { PGlite, type Extension } from '@electric-sql/pglite';+import type { Extension } from '@electric-sql/pglite';/** The five on-disk asset paths PGLite's runtime needs, however they were found. */export interface PgliteAssetPaths {@@ -163,7 +163,9 @@ export interface EmbeddedPgliteOptions {}/**- * Backend start parameters, appended to PGLite's defaults. PGLite is one+ * Backend start parameters, appended to PGLite's defaults by `build()`+ * (`[...PGlite.defaultStartParams, ...PGLITE_START_PARAM_OVERRIDES]`, defaults+ * first so the overrides win). PGLite is one* backend with no worker processes, yet a CREATE INDEX still plans parallel* workers from max_parallel_maintenance_workers, and pgvector's HNSW build* then reserves maintenance_work_mem as a shared area up front inside the@@ -176,8 +178,7 @@ export interface EmbeddedPgliteOptions {* (vector-index.ts PGLITE_HNSW_GRAPH_BUDGET_BYTES); the guard still* checkpoints at 256 MB between statements.*/-export const PGLITE_START_PARAMS = [- ...PGlite.defaultStartParams,+export const PGLITE_START_PARAM_OVERRIDES = ['-c', 'max_parallel_maintenance_workers=0','-c', 'max_wal_size=8GB',];@@ -231,7 +232,15 @@ async function build(): Promise<EmbeddedPgliteOptions> {setup: async () => ({ bundlePath: pgTrgmBundle }),};- return { pgliteWasmModule, initdbWasmModule, fsBundle, extensions: { vector, pg_trgm }, startParams: PGLITE_START_PARAMS };+ // The package import stays lazy and after resolvePgliteAssetPaths(): a top-level runtime import fails at module+ // load with the raw "Cannot find module" when the package is missing, before the tier-3 reinstall sentence above+ // can run (#6512; the module's contract since #4116 is "never fail at load"). The literal specifier keeps the+ // bundler embedding intact (scripts/check-pglite-embedded.sh).+ const { PGlite } = await import('@electric-sql/pglite'); // engine-dynamic-import-ok (module must load without the package, #6512)+ return {+ pgliteWasmModule, initdbWasmModule, fsBundle, extensions: { vector, pg_trgm },+ startParams: [...PGlite.defaultStartParams, ...PGLITE_START_PARAM_OVERRIDES],+ };}/**diff --git a/test/pglite-embedded-assets.test.ts b/test/pglite-embedded-assets.test.tsindex abb4164769..6dc0c29d55 100644--- a/test/pglite-embedded-assets.test.ts+++ b/test/pglite-embedded-assets.test.ts@@ -15,7 +15,8 @@ import { describe, test, expect } from 'bun:test';import { existsSync, statSync } from 'node:fs';import { createRequire } from 'node:module';import { dirname, join } from 'node:path';-import { resolvePgliteAssetPaths, getEmbeddedPgliteOptions } from '../src/core/pglite-embedded-assets.ts';+import { PGlite } from '@electric-sql/pglite';+import { resolvePgliteAssetPaths, getEmbeddedPgliteOptions, PGLITE_START_PARAM_OVERRIDES } from '../src/core/pglite-embedded-assets.ts';describe('resolvePgliteAssetPaths (#4116)', () => {test('dev checkout resolves via the embedded anchor with all five assets present', async () => {@@ -49,4 +50,10 @@ describe('resolvePgliteAssetPaths (#4116)', () => {expect(opts.extensions.vector.name).toBe('pgvector');expect(opts.extensions.pg_trgm.name).toBe('pg_trgm');});++ test('startParams are PGLite defaults first, then the HNSW/WAL overrides (#6512 lazy import keeps the order)', async () => {+ const opts = await getEmbeddedPgliteOptions();+ expect(opts.startParams).toEqual([...PGlite.defaultStartParams, ...PGLITE_START_PARAM_OVERRIDES]);+ expect(PGLITE_START_PARAM_OVERRIDES).toEqual(['-c', 'max_parallel_maintenance_workers=0', '-c', 'max_wal_size=8GB']);+ });});diff --git a/test/pglite-hoisted-install.test.ts b/test/pglite-hoisted-install.test.tsindex 1b03e23255..c9ddac79da 100644--- a/test/pglite-hoisted-install.test.ts+++ b/test/pglite-hoisted-install.test.ts@@ -16,6 +16,11 @@* broken — no pglite anywhere above the package* → tier 3, actionable error naming the reinstall command*+ * The subprocess runs `bun --no-install`: Bun's script auto-install otherwise fetches @electric-sql/pglite from+ * the registry into ~/.bun/install/cache for the broken layout, so an eager runtime import of the package in the+ * assets module passed this test for the wrong reason on networked machines (#6512). With auto-install off the+ * broken layout proves the resolver's tier-3 sentence is reachable: the module must load without the package.+ ** Serial: spawns subprocesses + writes tmpdirs.*/import { describe, test, expect, afterAll } from 'bun:test';@@ -59,7 +64,7 @@ async function resolveInSubprocess(root: string): Promise<{ exitCode: number; st'const r = await m.resolvePgliteAssetPaths();','console.log(JSON.stringify({ source: r.source }));',].join('\n');- const proc = Bun.spawn(['bun', '-e', script], {+ const proc = Bun.spawn(['bun', '--no-install', '-e', script], {cwd: root, // NOT the repo — resolution must not walk into the repo via cwdenv: { ...process.env },stdout: 'pipe',@@ -95,6 +100,9 @@ describe('hoisted-install asset resolution (#4116, serial)', () => {const root = makeFakePackage();const r = await resolveInSubprocess(root);expect(r.exitCode).not.toBe(0);+ // #6512: the raw resolver error is what an eager `import … from '@electric-sql/pglite'` prints at module load,+ // before resolvePgliteAssetPaths() can run; the diagnostic sentence must be the surface.+ expect(r.stderr).not.toContain("Cannot find module '@electric-sql/pglite'");expect(r.stderr).toContain('PGLite runtime assets not found');expect(r.stderr).toContain('Reinstall');// The failure users hit pre-fix must not be the surface we show now.