Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip: PGLite queue vacuum only after heap growth; key-files docs
time-attack6c296ad6ed45
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 2a0fa9825a..fe96fb8d94 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -58,7 +58,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/projection-readiness.ts` — EXISTS probe for unsealed text revisions in the visible scope: ready, projection_pending or unknown. Cached per scope by DB generation (page clock, `pages` filenode, archive flags, no open transaction); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.-- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. Migration 161 adds the scoped pending-projection index.+- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. A pass that changed fewer pages than `plannerStatsThreshold` (max(500, 10% of pages)) leaves collected statistics alone, and PGLite then analyzes only the hot tables its row deltas mark stale. Migration 161 adds the scoped pending-projection index.- `src/core/search/query-cache.ts` — stored semantic-cache data and maintenance remain, but `semanticResultCacheAvailable()` is false. `hybridSearchCached` bypasses both result lookup and writes regardless of configuration or `useCache`, and skips the key/config setup (merged config, cache config, intent-pattern state) so the wrapper adds no engine round-trips; request-local query embeddings still work. Search metadata, cache_stats and the mode dashboard report effective caching as disabled. Historical hit counts and search_telemetry remain intact. Restoration requires complete response-dependency provenance.diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex eb6bbd2d2e..f2eee14905 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -38,7 +38,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/chunkers/def-types.ts` — `DEF_TYPES`: the ONE list of definition-shaped normalized (post-`normalizeSymbolType`) symbol types, shared by `gbrain code-def`'s lookup allowlist (`src/commands/code-def.ts` re-exports it) and the code chunker's small-sibling merge guard so the two can't drift — a symbol type code-def can resolve never has its `symbol_name` erased by merging a small definition into a neighbor. Includes the fallthrough forms `normalizeSymbolType` emits verbatim for tree-sitter node types it doesn't canonicalize (`'method declaration'`, `'struct specifier'`, `'record declaration'`, …) — most of an OO codebase's symbols arrive in those forms. Pinned by `test/chunkers/code-merge-defs.test.ts`.-- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Applies `sanitizeRemoteBody` and then `credentialSafeProjection` (`src/core/credential-projection.ts`) before splitting, so only world Facts and ordinary prose enter retrieval text and private keys enter only as `<REDACTED:private_key_pem>`; all Takes and malformed protected sections are omitted. Non-overlapping portions reassemble to that sanitized input. The overlap extractor counts chars (not whitespace tokens) for CJK-dominant chunks — same unit as `countWords` — and aligns to `。!?` or a whitespace-followed ASCII `.!?`; the L4 char-slice fallback advances through `safeSplitIndex` so astral pairs (emoji, non-BMP CJK) are never halved. Both are gated on `isCJKDominant`, so English output is byte-identical (pinned by `test/chunkers/recursive-cjk-overlap.test.ts`). The markdown chunker version records the current index format.+- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Applies `sanitizeRemoteBody` and then `credentialSafeProjection` (`src/core/credential-projection.ts`) before splitting, so only world Facts and ordinary prose enter retrieval text and private keys enter only as `<REDACTED:private_key_pem>`; all Takes and malformed protected sections are omitted. Non-overlapping portions reassemble to that sanitized input. The overlap extractor counts chars (not whitespace tokens) for CJK-dominant chunks — same unit as `countWords` — and aligns to `。!?` or a whitespace-followed ASCII `.!?`; the L4 char-slice fallback advances through `safeSplitIndex` so astral pairs (emoji, non-BMP CJK) are never halved. Both are gated on `isCJKDominant`, so English output is byte-identical (pinned by `test/chunkers/recursive-cjk-overlap.test.ts`). The hard cap skips the token count for a chunk whose UTF-8 byte length already fits the token budget (`fitsEmbedTokens` in `token-estimate.ts`: bytes bound both the cl100k count and the weighted CJK estimate), so typical CJK chunks never reach the tiktoken WASM; boundaries are unchanged (`test/chunkers/fits-embed-tokens.test.ts`). The markdown chunker version records the current index format.- `src/core/chunkers/symbol-resolver.ts` — resolves and stamps each bounded chunk batch in one transaction. It takes ordered source/page guards before edge reads, revalidates current chunk/page/slug identity under those guards, and commits edge metadata with its backfill watermark. Concurrent projection replacement cannot certify new edges using an old resolver read; rollback leaves both metadata and watermark unchanged. Pinned by `test/symbol-resolver-projection-race.test.ts` with PGLite serialization and a real PostgreSQL lock-wait receipt. A `calls` edge the extractor flagged `memberCall` (an untyped receiver, `obj.m()` emitted as bare `m`; persisted as `edge_metadata.member_call`) is never resolved within the file, since a member call cannot invoke a same-file top-level function (gbrain-evals N13-8, `test/code-intel/n13-edge-resolution.test.ts`); existing code pages pick this up when they re-import (`gbrain reindex-code`).diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 3341924bff..fa6710e282 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/import-screen.ts` — `screenImportContent`: the one content screen (published exemption, size, frontmatter hold, slug conflict, Tier 1: a fixable fence is admitted normalized, a residual refuses typed (`coordinated`) or warns (`lenient`); optional sanity reject) shared by `importFromContent`, managed import and managed sync publication. `contentRefusalError` keeps each site's wire `error`; `isContentRefusal(code, message)` matches new codes and exact pre-upgrade strings, never capacity or transient refusals; `contentRefusalFromReceipt` restores code, reason, key and line on receipt replies. Tests: `test/import-screen.test.ts`, `test/sync-frontmatter-recovery.test.ts`, `test/put-page-recoverable-frontmatter.test.ts`. #6259 marker strip: [quarantine cluster](quarantine.md).-- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). Every markdown import resolves and stamps `contextual_retrieval_mode` and `corpus_generation` with the canonical write, `--no-embed` included (#5621), so later embed passes reproduce the page's wrapping; a failed source-policy read fails the import unless the row or table is missing (`SourceRowNotFoundError`, `isUndefinedTableError`). Unchanged markdown or code content whose page is below the safe-chunk fence is re-sealed projection-only (direct imports install it; coordinated `prepare` imports stay no-ops and queue a `safe_chunk_reseal` projection job), with no page write or admission. Freshly embedded chunks carry `embedding_input_hash` for the tier they were built under. The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent` reconciles tags by provenance (`tags.tag_source`, migration v175): frontmatter tags go through `addTag(..., { tagSource: 'frontmatter' })`, and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every other `addTag` stamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, so `gbrain reindex --markdown` keeps enrichment tags; legacy NULL rows are adopted only while the frontmatter still lists them; prepared (managed) imports keep add-only tags, matching the union their canonical file renders. Pinned by `test/reindex-preserve-tags.test.ts`, `test/import-frontmatter-tag-removal.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's OWN origin proves it moved (#5675): that origin is the `file://` path `importFromFile` records in `pages.source_uri` (never replacing non-file provenance), else the source's configured root (`local_path`, or the default source's legacy `sync.repo_path`). An origin that still exists moves only when it is this very file under another relative path (overlapping roots converge); a gone origin needs this file under that same root, and differing content also needs the same file name or title, so a missing path under another root, or a new note reusing a deleted note's template id, never renames a live page. `updateSlug` carries the row (page id, links, facts incl. `entity_slug`/`source_markdown_slug`, `page_aliases`, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). An inline markdown re-import embeds only chunks whose embedding input changed: `planEmbeddingReuse` (keyed on chunk source + exact text) reuses a stored vector when the old index is sealed (`requireSafeChunks`), the page's `embedding_signature`, contextual mode, `corpus_generation` and (under the title wrapper) sanitized title are unchanged, and neither the old nor the new body holds protected fences; prepared, `--no-embed`, `--force-rechunk` and post-commit-embedding imports reuse nothing (`test/import-markdown-embedding-reuse.test.ts`). Offset-less frontmatter datetimes are read in the brain's `brain.timezone` (IANA, validated by `gbrain config set`; unset or invalid = UTC; the YAML parser tags naive timestamps with `NAIVE_DATETIME` so the wall-clock reading survives), while date-only values stay UTC calendar dates (`test/effective-date-brain-timezone.test.ts`). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the earliest of the file's birth/modification time and — when `sync.git_first_commit_dates` is on — its git first-commit date via `fileTimes`, else now; `src/core/git-first-commit.ts` maps paths in one `git log --diff-filter=A` pass per `runImport`, skipping shallow clones; `test/effective-date-git-first-commit.test.ts`), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync, but an `embed_skip` transition (present vs absent) defeats both unchanged fast paths so a threshold change rebuilds or removes chunks without `--force`. A trusted import whose content the gate no longer blocks drops an incoming `embed_skip` (and a `content_flag`) whose reason is `oversized`; other skip reasons, quarantined pages and the sanity bypass keep them. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`. A frontmatter `slug:` that would become the page identity and ends in `.md`/`.mdx` is held as `frontmatter_slug_conflict` unless that exact (source_id, slug) page is live (`persistence/suffixed-slug.ts`).+- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). Every markdown import resolves and stamps `contextual_retrieval_mode` and `corpus_generation` with the canonical write, `--no-embed` included (#5621), so later embed passes reproduce the page's wrapping; a failed source-policy read fails the import unless the row or table is missing (`SourceRowNotFoundError`, `isUndefinedTableError`). Unchanged markdown or code content whose page is below the safe-chunk fence is re-sealed projection-only (direct imports install it; coordinated `prepare` imports stay no-ops and queue a `safe_chunk_reseal` projection job), with no page write or admission. Freshly embedded chunks carry `embedding_input_hash` for the tier they were built under. The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent` reconciles tags by provenance (`tags.tag_source`, migration v175): frontmatter tags go through `addTag(..., { tagSource: 'frontmatter' })`, and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every other `addTag` stamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, so `gbrain reindex --markdown` keeps enrichment tags; legacy NULL rows are adopted only while the frontmatter still lists them; prepared (managed) imports keep add-only tags, matching the union their canonical file renders. Pinned by `test/reindex-preserve-tags.test.ts`, `test/import-frontmatter-tag-removal.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's OWN origin proves it moved (#5675): that origin is the `file://` path `importFromFile` records in `pages.source_uri` (never replacing non-file provenance), else the source's configured root (`local_path`, or the default source's legacy `sync.repo_path`). An origin that still exists moves only when it is this very file under another relative path (overlapping roots converge); a gone origin needs this file under that same root, and differing content also needs the same file name or title, so a missing path under another root, or a new note reusing a deleted note's template id, never renames a live page. `updateSlug` carries the row (page id, links, facts incl. `entity_slug`/`source_markdown_slug`, `page_aliases`, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). An inline markdown re-import embeds only chunks whose embedding input changed: `planEmbeddingReuse` (keyed on chunk source + exact text) reuses a stored vector when the old index is sealed (`requireSafeChunks`), the page's `embedding_signature`, contextual mode, `corpus_generation` and (under the title wrapper) sanitized title are unchanged, and neither the old nor the new body holds protected fences; `--force-rechunk` and post-commit-embedding imports reuse nothing (`test/import-markdown-embedding-reuse.test.ts`). Inside the import transaction, under the page lock, every import (inline, `--no-embed` and prepared alike) re-reads that reuse (`src/core/import-chunk-reuse.ts`) and keeps each stored row identical to its new chunk in place, including a never-embedded row under a chunk that gets no vector; only the other rows are deleted and written, so an edit rewrites only the chunks it changed (`test/import-inline-chunk-keep.test.ts`). Offset-less frontmatter datetimes are read in the brain's `brain.timezone` (IANA, validated by `gbrain config set`; unset or invalid = UTC; the YAML parser tags naive timestamps with `NAIVE_DATETIME` so the wall-clock reading survives), while date-only values stay UTC calendar dates (`test/effective-date-brain-timezone.test.ts`). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the earliest of the file's birth/modification time and — when `sync.git_first_commit_dates` is on — its git first-commit date via `fileTimes`, else now; `src/core/git-first-commit.ts` maps paths in one `git log --diff-filter=A` pass per `runImport`, skipping shallow clones; `test/effective-date-git-first-commit.test.ts`), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync, but an `embed_skip` transition (present vs absent) defeats both unchanged fast paths so a threshold change rebuilds or removes chunks without `--force`. A trusted import whose content the gate no longer blocks drops an incoming `embed_skip` (and a `content_flag`) whose reason is `oversized`; other skip reasons, quarantined pages and the sanity bypass keep them. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`. A frontmatter `slug:` that would become the page identity and ends in `.md`/`.mdx` is held as `frontmatter_slug_conflict` unless that exact (source_id, slug) page is live (`persistence/suffixed-slug.ts`).- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex f51583d561..18f128f818 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -811,14 +811,24 @@ export async function markRecovering(engine: SqlEngine, row: WriteRequest, reasoWHERE id=$1::uuid AND execution_token=$2::uuid AND state IN ('running','recovering') AND ${PERSISTENCE_PROTOCOL_PREDICATE}`,[row.id, row.execution_token, reason, failure?.code ?? null, failure?.message ?? null, failure?.detail ? JSON.stringify(failure.detail) : null]);}+const PERSISTENCE_QUEUE_TABLES = ['persistence_requests', 'persistence_effects', 'persistence_counters', 'page_projection_jobs', 'page_write_guards'];/*** PGLite has no autovacuum. The resident owner reclaims queue churn and keeps* planner statistics current, so receipt lookups keep using the request-id- * index and claims do not walk dead queue entries.+ * index and claims do not walk dead queue entries. A queue table is vacuumed+ * once its heap has grown more than 10% (and 8 pages) past the size its last+ * VACUUM or ANALYZE recorded: PGLite keeps no dead-tuple counters across+ * processes, and unreclaimed churn lands on new pages. Every short-lived CLI+ * process otherwise vacuumed every queue on its first tick (0.6 s per one-page+ * sync at 5k pages).*/export async function vacuumPersistenceQueues(engine: BrainEngine): Promise<number> {if (engine.kind !== 'pglite') return 0;- await engine.executeRaw('VACUUM (ANALYZE) persistence_requests, persistence_effects, persistence_counters, page_projection_jobs, page_write_guards');+ const grown = await engine.executeRaw<{ relname: string }>(+ `SELECT c.relname FROM pg_class c WHERE c.relname = ANY($1::text[]) AND c.relkind = 'r' AND c.relnamespace = 'public'::regnamespace+ AND pg_relation_size(c.oid) / current_setting('block_size')::int > c.relpages * 1.1 + 8`, [PERSISTENCE_QUEUE_TABLES]);+ const tables = PERSISTENCE_QUEUE_TABLES.filter(table => grown.some(row => row.relname === table));+ if (tables.length) await engine.executeRaw(`VACUUM (ANALYZE) ${tables.join(', ')}`);const [requests] = await engine.executeRaw<{ rows: number }>("SELECT GREATEST(reltuples,0)::float8 AS rows FROM pg_class WHERE oid='persistence_requests'::regclass");return Number(requests?.rows ?? 0);}diff --git a/test/persistence-queue-vacuum.test.ts b/test/persistence-queue-vacuum.test.tsnew file mode 100644index 0000000000..41e2e0b8af--- /dev/null+++ b/test/persistence-queue-vacuum.test.ts@@ -0,0 +1,39 @@+/**+ * PGLite queue upkeep vacuums a queue table only once its heap has grown more+ * than 10% (and 8 pages) past the size its last VACUUM or ANALYZE recorded, so+ * a short-lived CLI process does not vacuum every queue on its first tick.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { vacuumPersistenceQueues } from '../src/core/persistence/journal.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);+afterAll(async () => { await engine.disconnect(); });++async function vacuumed(): Promise<string[]> {+ const seen: string[] = [];+ const original = engine.executeRaw;+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[], opts?: unknown) {+ if (sql.startsWith('VACUUM')) seen.push(sql);+ return original.call(this, sql, params, opts as never);+ } as BrainEngine['executeRaw'];+ try { await vacuumPersistenceQueues(engine); } finally { engine.executeRaw = original; }+ return seen;+}+const pages = async () => (await engine.executeRaw<{ relpages: number; size: number }>(+ "SELECT relpages, pg_relation_size('persistence_counters'::regclass) / current_setting('block_size')::int AS size FROM pg_class WHERE oid = 'persistence_counters'::regclass"))[0]!;++test('small queues are left alone; a queue that grew past its recorded size is vacuumed once, then left alone', async () => {+ expect(await vacuumed()).toEqual([]);+ await engine.executeRaw("INSERT INTO persistence_counters(key) SELECT 'bench-' || g FROM generate_series(1, 3000) g");+ expect((await pages()).size).toBeGreaterThan(8);+ expect(await vacuumed()).toEqual(['VACUUM (ANALYZE) persistence_counters']);+ const after = await pages();+ expect(after.relpages).toBe(after.size);+ expect(await vacuumed()).toEqual([]);+ await engine.executeRaw("UPDATE persistence_counters SET lifetime_ids = lifetime_ids + 1 WHERE key LIKE 'bench-%'");+ expect(await vacuumed()).toEqual(['VACUUM (ANALYZE) persistence_counters']);+ await engine.executeRaw("DELETE FROM persistence_counters WHERE key LIKE 'bench-%'");+});