Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(extract): batch extract --source db snapshot reads and derived-link writes per 100 pages
time-attack20181d072c34
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 4c167051bc..0bbc622947 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap; a page's frontmatter `conversation_segment_gap_minutes`, an integer from 1 to 10080, overrides the gap for that page, and any other value is ignored with a stderr warning naming the accepted range), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip). `src/commands/doctor.ts` reads the same outcomes, which survive checkpoint GC. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Explicit `slugs` batches contain page failures like the pool (cancellation and budget stops halt); logs carry only the closed reason and a retry command. Completion requires every in-scope segment (exactly `--segment-limit` counts). Extracted rows take `facts.default_visibility` (resolved once per run); audit rows stay private. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives, bar `facts/conversation-skip.ts` (prose meetings, single emails, undated turns). Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then replace the prior extractor batch in one `replaceDerivedFactsForPage` transaction after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).-- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs walk replaces each page's own markdown-derived links through `replacePageFileLinks` (the per-slug contract below; a file with no page row is skipped and not stamped); the db link walk and `extract --stale` replace through `replaceDerivedLinks`. Timeline rows are inserted in batches of 100 via `addTimelineEntriesBatch` (`ON CONFLICT DO NOTHING`; `created` counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, `--stale` — runs `retractRemovedTimelineEntries` for the page. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the non-event rows whose (date, source, summary) any stored `page_versions` text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, `--infer-dates` anchors) are kept, and the version scan only runs when the page holds a row the current text does not produce. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` (`pruneTimelineOrphans`) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-locked `withCoordinatedWrite` transaction; these rows are removals, so `gbrain repair timeline` / `timeline_history` exclude them; pinned in `test/persistence-managed-lifecycle.test.ts`); the read-only `timeline_orphans` doctor check (`src/commands/doctor/checks/timeline-orphans.ts`) samples 500 pages and points at it. Pinned by `test/timeline-reconcile-all-paths.test.ts`. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. `extractLinksForSlugs` reads the requested files first, then loads page metadata only for those pages and their link endpoints (`fileLinkOwnership(engine, sourceId, { slugs })`); the unscoped whole-brain load happens only when a DB meeting or attendance origin needs `replaceFileLinks`. Both return `ExtractForSlugsResult { created, processed, errors? }`; `errors` names pages whose read or write failed, and sync reports them as `extract_error` (stderr line plus the `SyncResult` field) instead of swallowing them. `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`; on a managed brain it hands the sweep to `extractManagedStaleLinks` in `src/core/persistence/links-maintenance.ts` for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through `src/commands/extract-stale-delegate.ts`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale, then the mention pass. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: a page's throw aborts the sweep after the batch's finished pages are flushed and stamped (S4), so the failing page and later ones stay stale and re-extract idempotently. `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. On a managed-persistence brain each page publishes its derived links (`prepareAutomaticLinks`), the coordinator's unrecorded canonical timeline tuples (`unrecordedCanonicalTimeline`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`, `test/persistence-managed-lifecycle.test.ts`. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Fresh-install schema in `src/schema.sql` (both generated blobs follow via `bun run build:schema`) + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor/checks/extraction-sync.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; pages whose attendance marker (`links_attendance_blocked_revision`, migration v180) equals their current `knowledge_revision` are left out of the lag count and reported as `details.attendance_blocked` (both `extract --stale` sweeps set the marker on an unresolved-attendance skip; pre-v180 brains fall back to the unfiltered count); strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0. W4.14: one basename index per slug set (rebuilt as it grows).+- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs walk replaces each page's own markdown-derived links through `replacePageFileLinks` (the per-slug contract below; a file with no page row is skipped and not stamped); `extract --stale` replaces through `replaceDerivedLinks`, the db link walk through `replaceDerivedLinksBatch`. Timeline rows are inserted in batches of 100 via `addTimelineEntriesBatch` (`ON CONFLICT DO NOTHING`; `created` counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, `--stale` — runs `retractRemovedTimelineEntries` for the page. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the non-event rows whose (date, source, summary) any stored `page_versions` text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, `--infer-dates` anchors) are kept, and the version scan only runs when the page holds a row the current text does not produce. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` (`pruneTimelineOrphans`) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-locked `withCoordinatedWrite` transaction; these rows are removals, so `gbrain repair timeline` / `timeline_history` exclude them; pinned in `test/persistence-managed-lifecycle.test.ts`); the read-only `timeline_orphans` doctor check (`src/commands/doctor/checks/timeline-orphans.ts`) samples 500 pages and points at it. Pinned by `test/timeline-reconcile-all-paths.test.ts`. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. `extractLinksForSlugs` reads the requested files first, then loads page metadata only for those pages and their link endpoints (`fileLinkOwnership(engine, sourceId, { slugs })`); the unscoped whole-brain load happens only when a DB meeting or attendance origin needs `replaceFileLinks`. Both return `ExtractForSlugsResult { created, processed, errors? }`; `errors` names pages whose read or write failed, and sync reports them as `extract_error` (stderr line plus the `SyncResult` field) instead of swallowing them. `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`; on a managed brain it hands the sweep to `extractManagedStaleLinks` in `src/core/persistence/links-maintenance.ts` for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through `src/commands/extract-stale-delegate.ts`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale, then the mention pass. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: a page's throw aborts the sweep after the batch's finished pages are flushed and stamped (S4), so the failing page and later ones stay stale and re-extract idempotently. `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. On a managed-persistence brain each page publishes its derived links (`prepareAutomaticLinks`), the coordinator's unrecorded canonical timeline tuples (`unrecordedCanonicalTimeline`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`, `test/persistence-managed-lifecycle.test.ts`. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Fresh-install schema in `src/schema.sql` (both generated blobs follow via `bun run build:schema`) + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor/checks/extraction-sync.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; pages whose attendance marker (`links_attendance_blocked_revision`, migration v180) equals their current `knowledge_revision` are left out of the lag count and reported as `details.attendance_blocked` (both `extract --stale` sweeps set the marker on an unresolved-attendance skip; pre-v180 brains fall back to the unfiltered count); strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0. W4.14: one basename index per slug set (rebuilt as it grows).- `src/commands/extract-timeline-db.ts` — the `extract timeline --source db` walk (`extractTimelineFromDB`), also used by `runExtractCore` for a timeline-only pass on a managed brain. Managed brains (every fresh `gbrain init` brain) publish each page that needs a change as one database-only maintenance request (`managed_maintenance_timeline_extract`, owner-checked by `maintenancePreflight`, request id bound to the page revision; `prepareTimelineExtract` is dispatched from `prepareMaintenanceMutation`): under the page lock it retracts rows the current text no longer produces and inserts the canonical tuples with no stored row (`unrecordedCanonicalTimeline`); a page with nothing to change admits no request, and a page edited meanwhile is skipped. Unmanaged brains batch raw inserts. A refused write prints `refused: <code>; nothing written; existing timeline rows are untouched`, the summary counts written versus refused (a request still pending counts as not confirmed) with `gbrain extract --stale` and the `write-refusals.md#extract-timeline-refused` anchor, and the CLI exits 1 (the `extract` job throws). Pinned by `test/extract-timeline-db-managed.test.ts`, `test/e2e/extract-timeline-db-postgres.test.ts`, `test/fresh-init-db-extract.serial.test.ts`.- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.diff --git a/docs/architecture/key-files/company-brain.md b/docs/architecture/key-files/company-brain.mdindex 5a915ab499..456fcfa748 100644--- a/docs/architecture/key-files/company-brain.md+++ b/docs/architecture/key-files/company-brain.md@@ -9,7 +9,7 @@ For the operator workflow, see the [company-brain ingestion guide](../../guides/- `src/commands/company-brain-{inspect,connect,demo}.ts` — dedicated source subcommand parsing and versioned JSON/error output. Inspection is engine-free; connect requires explicit brain/source selection and previews through the existing resident-owner route before a probe-only local connection. Human progress is stderr-scoped for JSON output. `core/company-brain/{demo,sample,evidence,status}.ts` supplies the real-pipeline offline sample, actual source-scoped evidence, and private receipt status without fabricated answers or host-path fields.-- `src/core/{derived-links,link-reconciliation}.ts` — source-qualified, revision-fenced atomic replacement of derived edges; manual rows survive. The source reconciliation API supports bounded cursors, refuses changed endpoints, and resolves no foreign-source fallback. Standard DB extraction passes the same captured endpoint revision fences. `test/derived-link-reconciliation.test.ts` and `test/extract-endpoint-revision.serial.test.ts` cover both engines and rollback/freshness behavior.+- `src/core/{derived-links,link-reconciliation}.ts` — source-qualified, revision-fenced atomic replacement of derived edges; manual rows survive. The source reconciliation API supports bounded cursors, refuses changed endpoints, and resolves no foreign-source fallback. Standard DB extraction passes the same captured endpoint revision fences. `replaceDerivedLinksBatch` (engine member) publishes many origins in one transaction: one relation-semantics prime, one sorted guard lock over every origin and endpoint, one extraction-generation check and one batched origin read (`readPageSnapshotsBatch` in `src/core/page-snapshot-batch.ts`: each exact ref's `readPageSnapshot` result in one statement, line fingerprints only for pages with withdrawals, a body-byte budget per call; `test/page-snapshot-batch.test.ts`), then each origin's own checks and writes in order; any failure rolls the batch back, and `replaceDerivedLinksBatchOrReplay` then replays the origins one by one through `replaceDerivedLinks`, so each outcome (settings-changed skip, first error) is the unbatched one (`test/extract-db-batch-equivalence.test.ts` pins `extract all --source db` rows to the per-page walk). `test/derived-link-reconciliation.test.ts` and `test/extract-endpoint-revision.serial.test.ts` cover both engines and rollback/freshness behavior.- `src/core/attendance-repair.ts` and `src/commands/extract-attendance-repair.ts` — trusted-local historical attendance preview and exact-receipt apply. Indexed source-page slug windows precede eligibility filtering; explicit Markdown evidence uses capped endpoint and adjacency lookups, while all frontmatter remains report-only and unmaterialized. A narrow `derived-links.ts` delta preserves unrelated row IDs and evidence; brain/source incarnation, page revisions, ontology/parser and affected-edge hashes fence each origin transaction. Existing `op_checkpoints` banks commit proof before the private cursor advances across committed origins and revalidated skipped pages, making interruption replay idempotent. No broad derived replacement, normal-extraction watermark updates, MCP administration or provider calls. Covered by the dual-engine `test/attendance-repair.test.ts` and real CLI `test/attendance-repair-cli.serial.test.ts`; operator contract and limits are in `docs/guides/attendance-evidence.md`.- `src/core/schema-pack/base/company-brain.yaml` — optional company vocabulary extending `gbrain-base-v2` without normalization rules or maintenance phases. Overrides company aliases and prefixes so product stays a distinct query and path type. Bundled through `schema-pack/bundled.ts` and `bundled-assets.ts`; attribution is in `third-party/company-brain/`. The generic fictional sample in `src/core/company-brain/sample/` preserves the upstream layout and relationship metadata. `test/company-brain-schema.test.ts` pins inherited lint, type closure, folder inference, read-only bundling, and sample references.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex e08a1441b3..16a93beff8 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilosrc/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2227 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts)src/commands/extract-conversation-facts.ts 2213 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start)-src/commands/extract.ts 2589 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale+src/commands/extract.ts 2614 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay)src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codessrc/commands/serve-http.ts 931 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)src/core/ai/gateway.ts 4430 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts@@ -16,12 +16,12 @@ src/commands/sync.ts 514 ratchet refactor wave 1 split target (W4 sync); ceilingsrc/core/cycle.ts 3283 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts)src/core/cycle/synthesize.ts 3227 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)src/core/cycle/extract-atoms.ts 1650 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt-src/core/engine.ts 2735 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads)+src/core/engine.ts 2737 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch membersrc/core/import-file.ts 2202 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row-src/core/pglite-engine.ts 2998 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move)-src/core/postgres-engine.ts 2979 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark+src/core/pglite-engine.ts 3002 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts)+src/core/postgres-engine.ts 2982 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts)src/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget optssrc/core/types.ts 2239 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)diff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.tsindex 5e44ce8edc..cdb3b92f85 100644--- a/src/commands/extract-timeline-db.ts+++ b/src/commands/extract-timeline-db.ts@@ -36,6 +36,8 @@ import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../core/plannimport { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { filterRefsSince } from './extract.ts';import { isQuarantined } from '../core/quarantine.ts';+import { pageSnapshotKey, readPageSnapshotsBatch } from '../core/page-snapshot-batch.ts';+import type { PageSnapshot } from '../core/page-state/types.ts';const BATCH_SIZE = 100;export const TIMELINE_EXTRACT_INTENT = 'managed_maintenance_timeline_extract';@@ -137,15 +139,22 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineD}}- for (const { slug, source_id } of refs) {+ // Pages are read BATCH_SIZE at a time (one snapshot statement, and on a+ // managed brain one read of their stored rows); a managed page with nothing+ // to change then admits no request without another read.+ let readBatch: TimelineReadBatch = { start: 0, covered: 0, snapshots: new Map(), stored: new Map() };+ for (const [index, { slug, source_id }] of refs.entries()) {if (analyzeEvery > 0 && walked > 0 && walked % analyzeEvery === 0) {await flush();await maybeRefreshPlannerStats(engine, 'extract', { throttle: false }).catch(() => undefined);}walked++;+ if (index >= readBatch.start + readBatch.covered) readBatch = await readTimelineBatch(engine, refs, index, managed);+ const snapshot = readBatch.snapshots.get(pageSnapshotKey(source_id, slug)) ?? null;if (managed) {try {- const outcome = await publishPageTimeline(engine, await authorityFor(source_id), slug, source_id, opts);+ const outcome = await publishPageTimeline(engine, await authorityFor(source_id), slug, source_id, opts,+ { snapshot, stored: snapshot ? readBatch.stored.get(Number(snapshot.page.id)) ?? [] : [] });if (outcome === 'skipped') result.skipped++;else if (outcome === 'pending') result.pending++;else if (outcome !== null) { result.created += outcome; result.pages++; }@@ -159,7 +168,7 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineDcontinue;}- const page = await engine.getPage(slug, { sourceId: source_id });+ const page = snapshot?.page ?? null;if (!page || isQuarantined(page.frontmatter)) continue;if (opts.typeFilter && page.type !== opts.typeFilter) continue;const fullContent = page.compiled_truth + '\n' + page.timeline;@@ -214,16 +223,52 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineDreturn result;}-/** The timeline change one page needs: removed rows to retract and canonical tuples (or an inferred anchor) to insert. */-async function plannedTimeline(engine: BrainEngine, page: Page, slug: string, sourceId: string, inferDates: boolean) {+/** A page's stored non-event timeline rows, read once for both planning checks. */+interface StoredTimelineRows { id: number; date: string; date_text: string; source: string; summary: string; detail: string | null }++interface TimelineReadBatch {+ start: number;+ covered: number;+ snapshots: Map<string, PageSnapshot>;+ /** Managed walks only: stored rows by page id. */+ stored: Map<number, StoredTimelineRows[]>;+}++async function readTimelineBatch(engine: BrainEngine, refs: ReadonlyArray<{ slug: string; source_id: string }>, start: number,+ withStoredRows: boolean): Promise<TimelineReadBatch> {+ const { snapshots, covered } = await readPageSnapshotsBatch(engine, refs.slice(start, start + BATCH_SIZE)+ .map(ref => ({ slug: ref.slug, sourceId: ref.source_id })));+ const stored = new Map<number, StoredTimelineRows[]>();+ const pageIds = [...snapshots.values()].map(snapshot => Number(snapshot.page.id));+ if (withStoredRows && pageIds.length) {+ const rows = await engine.executeRaw<StoredTimelineRows & { page_id: number }>(+ `SELECT page_id, id, to_char(date, 'YYYY-MM-DD') AS date, date::text AS date_text, source, summary, detail FROM timeline_entries+ WHERE page_id = ANY($1::int[]) AND event_page_id IS NULL ORDER BY date, id`, [pageIds]);+ for (const { page_id, ...row } of rows) {+ const list = stored.get(Number(page_id)) ?? [];+ list.push(row);+ stored.set(Number(page_id), list);+ }+ }+ return { start, covered, snapshots, stored };+}++/**+ * The timeline change one page needs: removed rows to retract and canonical+ * tuples (or an inferred anchor) to insert. `stored` is the caller's read of+ * the page's rows; without it the checks read them.+ */+async function plannedTimeline(engine: BrainEngine, page: Page, slug: string, sourceId: string, inferDates: boolean, stored?: StoredTimelineRows[]) {const fullContent = page.compiled_truth + '\n' + page.timeline;- const removed = await retractRemovedTimelineEntries(engine, slug, sourceId, fullContent, { dryRun: true });- let entries: Array<{ date: string; source?: string; summary: string; detail?: string }> = await unrecordedCanonicalTimeline(engine, page.id, page, slug);+ const removed = await retractRemovedTimelineEntries(engine, slug, sourceId, fullContent, { dryRun: true,+ ...(stored ? { storedRows: stored.map(({ date_text: _text, ...row }) => row) } : {}) });+ let entries: Array<{ date: string; source?: string; summary: string; detail?: string }> = await unrecordedCanonicalTimeline(engine, page.id, page, slug,+ stored?.map(row => ({ date: row.date_text, source: row.source, summary: row.summary })));if (entries.length === 0 && inferDates && parseTimelineEntries(fullContent).length === 0) {const anchor = anchorFor(page, slug);- const [stored] = anchor ? await engine.executeRaw<{ n: number }>(- 'SELECT count(*)::int AS n FROM timeline_entries WHERE page_id=$1 AND event_page_id IS NULL', [page.id]) : [{ n: 1 }];- if (anchor && !stored?.n) entries = [anchor];+ const [count] = !anchor ? [{ n: 1 }] : stored ? [{ n: stored.length }] : await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM timeline_entries WHERE page_id=$1 AND event_page_id IS NULL', [page.id]);+ if (anchor && !count?.n) entries = [anchor];}return { fullContent, removed: removed.length, entries };}@@ -241,13 +286,14 @@ async function writePageTimeline(tx: BrainEngine, page: Page, slug: string, sour* One page on a managed brain: null when the page is missing or filtered out,* 0 when nothing changes (no request admitted), else the rows the committed* request added. The request id is bound to the page revision, so a rerun- * replays an accepted request instead of admitting a second one.+ * replays an accepted request instead of admitting a second one. `read` is+ * the caller's batched read of the page and its stored rows.*/async function publishPageTimeline(engine: BrainEngine, authority: MaintenanceAuthority, slug: string, sourceId: string,- opts: TimelineDbOptions): Promise<number | null | 'skipped' | 'pending'> {- const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ opts: TimelineDbOptions, read?: { snapshot: PageSnapshot | null; stored: StoredTimelineRows[] }): Promise<number | null | 'skipped' | 'pending'> {+ const snapshot = read ? read.snapshot : await engine.readPageSnapshot(slug, { sourceId });if (!snapshot || isQuarantined(snapshot.page.frontmatter) || (opts.typeFilter && snapshot.page.type !== opts.typeFilter)) return null;- const plan = await plannedTimeline(engine, snapshot.page, slug, sourceId, opts.inferDates === true);+ const plan = await plannedTimeline(engine, snapshot.page, slug, sourceId, opts.inferDates === true, read?.stored);if (!plan.removed && !plan.entries.length) return 0;for (let attempt = 0; ; attempt++) {const h = digest(['extract-timeline-db-v1', sourceId, slug, snapshot.revision, attempt]);diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex bbdc4b7ad4..c98a65d926 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -50,7 +50,9 @@ import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetadaimport { collectWantedLinks, isWantedPagesEnabled } from '../core/wanted-links.ts';import { readLineGrammarSettings, statedRelationTypes } from '../core/line-grammar.ts';import { effectiveLinkExtractorWatermark, linkExtractorWatermarkFor } from '../core/link-extraction-watermark.ts';-import { replaceDerivedLinksUnlessSettingsChanged, settingsChangedSkipLine } from '../core/derived-links.ts';+import { replaceDerivedLinksBatchOrReplay, replaceDerivedLinksUnlessSettingsChanged, settingsChangedSkipLine, type DerivedLinkBatchItem } from '../core/derived-links.ts';+import { pageSnapshotKey, readPageSnapshotsBatch } from '../core/page-snapshot-batch.ts';+import type { PageSnapshot } from '../core/page-state/types.ts';export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';export { extractMarkdownLinks } from '../core/link-extraction.ts';import {@@ -1891,8 +1893,32 @@ async function extractLinksFromDB(// Dedup in dry-run only — DB enforces uniqueness via ON CONFLICT in batch writes.const dryRunSeen = dryRun ? new Set<string>() : null;- for (const { slug, source_id } of walkRefs) {- const snapshot = await engine.readPageSnapshot(slug, { sourceId: source_id });+ // Pages are read and their links published BATCH_SIZE at a time (one+ // snapshot statement, one write transaction); a failed batch is replayed+ // page by page, so each page's outcome is the unbatched one.+ const pendingWrites: Array<{ slug: string; source_id: string; item: DerivedLinkBatchItem }> = [];+ async function flushLinkWrites() {+ const writes = pendingWrites.splice(0);+ const results = await replaceDerivedLinksBatchOrReplay(engine, writes.map(write => write.item), item => {+ if (jsonMode) process.stderr.write(JSON.stringify({ event: 'batch_error', size: item.links.length, code: 'graph_write_failed' }) + '\n');+ });+ writes.forEach(({ slug, source_id }, i) => {+ const written = results[i];+ if (written) { created += written.created; processed++; processedRefs.push({ slug, source_id }); } else skippedSettingsChanged++;+ progress.tick(1);+ });+ }+ let snapshotBatch = { start: 0, covered: 0, snapshots: new Map<string, PageSnapshot>() };+ let wantedPages = false;++ for (const [index, { slug, source_id }] of walkRefs.entries()) {+ if (index >= snapshotBatch.start + snapshotBatch.covered) {+ await flushLinkWrites();+ snapshotBatch = { start: index, ...await readPageSnapshotsBatch(engine, walkRefs.slice(index, index + BATCH_SIZE)+ .map(ref => ({ slug: ref.slug, sourceId: ref.source_id }))) };+ wantedPages = !dryRun && await isWantedPagesEnabled(engine);+ }+ const snapshot = snapshotBatch.snapshots.get(pageSnapshotKey(source_id, slug)) ?? null;if (!snapshot || isQuarantined(snapshot.page.frontmatter)) continue;const page = snapshot.page;if (typeFilter && page.type !== typeFilter) continue;@@ -1959,25 +1985,24 @@ async function extractLinksFromDB(}if (!dryRun) {try {- const wanted = await isWantedPagesEnabled(engine) ? collectWantedLinks({ candidates: extracted.candidates,+ const wanted = wantedPages ? collectWantedLinks({ candidates: extracted.candidates,frontmatterUnresolved: includeFrontmatter ? extracted.unresolved : [], originSourceId: source_id,crossSourceAllowed: federatedSourceIds.has(source_id) || crossSource, resolve: c => resolveCandidateSources(c, slug, source_id,allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource, defaultSourceId: linkDefaultSourceId }) }) : [];- const written = await replaceDerivedLinksUnlessSettingsChanged(engine, { slug, sourceId: source_id, expectedRevision: snapshot.revision,- sourceIncarnation: snapshot.sourceIncarnation }, batch, { includeFrontmatter, lineGrammar: grammar,+ pendingWrites.push({ slug, source_id, item: { origin: { slug, sourceId: source_id, expectedRevision: snapshot.revision,+ sourceIncarnation: snapshot.sourceIncarnation }, links: batch, opts: { includeFrontmatter, lineGrammar: grammar,wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] : ['body'], rows: wanted },- expectedEndpoints: capturedLinkEndpoints(batch, targetMetadata) });- if (!written) { skippedSettingsChanged++; progress.tick(1); continue; }- created += written.created;+ expectedEndpoints: capturedLinkEndpoints(batch, targetMetadata) } } });} catch (error) {if (jsonMode) process.stderr.write(JSON.stringify({ event: 'batch_error', size: batch.length, code: 'graph_write_failed' }) + '\n');throw error;}+ continue;}processed++;- if (!dryRun) processedRefs.push({ slug, source_id });progress.tick(1);}+ await flushLinkWrites();// v0.42.7 (#1696): stamp the extraction watermark for every page we// processed (incl. zero-link pages — they WERE extracted). Chunked so the// unnest UPDATE stays bounded on big brains. Best-effort (stampExtracteddiff --git a/src/core/derived-links.ts b/src/core/derived-links.tsindex c8f218f8a6..14dddb250c 100644--- a/src/core/derived-links.ts+++ b/src/core/derived-links.ts@@ -2,6 +2,7 @@ import type { BrainEngine, LinkBatchInput } from './engine.ts';import { assertPageRevision, type PageSnapshot } from './page-state/types.ts';import { pipelined } from './page-state/transactions.ts';import { executeRawJsonb } from './sql-query.ts';+import { pageSnapshotKey, readPageSnapshotsBatch } from './page-snapshot-batch.ts';import { sanitizeForJsonb } from './batch-rows.ts';import { replaceWantedLinks, type WantedLinksReplacement } from './wanted-links-store.ts';import { applyTemporalEvidence, relationshipKeysForOrigin } from './link-temporal-apply.ts';@@ -84,12 +85,8 @@ export async function applyAttendanceDelta(tx: Pick<BrainEngine, 'executeRaw' |return { created, removed: removed.length };}-export async function replaceDerivedLinks(- engine: Pick<BrainEngine, 'transaction'>,- origin: DerivedLinkOrigin,- links: LinkBatchInput[],- opts: DerivedLinkReplacementOptions = {},-): Promise<{ created: number; removed: number }> {+/** Validate and normalize one origin's candidate rows (deduplicated, producer and origin stamped). */+function derivedLinkRows(origin: DerivedLinkOrigin, links: LinkBatchInput[], opts: DerivedLinkReplacementOptions) {const producers = ['markdown', 'wikilink-resolved', ...(opts.includeFrontmatter === false ? [] : ['frontmatter'])];const unique = new Map<string, LinkBatchInput>();for (const link of links) {@@ -114,45 +111,119 @@ export async function replaceDerivedLinks(const key = JSON.stringify([row.from_source_id, row.from_slug, row.to_source_id, row.to_slug, row.link_type ?? '', producer]);if (!unique.has(key)) unique.set(key, row);}- const rows = [...unique.values()];+ return { producers, rows: [...unique.values()] };+}++const derivedLinkLockKeys = (origin: DerivedLinkOrigin, rows: LinkBatchInput[]) => [{ sourceId: origin.sourceId, slug: origin.slug },+ ...rows.flatMap(row => [{ sourceId: row.from_source_id!, slug: row.from_slug }, { sourceId: row.to_source_id!, slug: row.to_slug }])];++/** FOR SHARE: a concurrent setting change (which updates this row) waits for this publication, or this one sees it. */+const lockedExtractionGeneration = async (tx: BrainEngine) => (await tx.executeRaw<{ value: string }>(+ 'SELECT value FROM config WHERE key = $1 FOR SHARE', [LINK_EXTRACTION_GENERATION_KEY]))[0]?.value ?? null;++export async function replaceDerivedLinks(+ engine: Pick<BrainEngine, 'transaction'>,+ origin: DerivedLinkOrigin,+ links: LinkBatchInput[],+ opts: DerivedLinkReplacementOptions = {},+): Promise<{ created: number; removed: number }> {+ const { producers, rows } = derivedLinkRows(origin, links, opts);return engine.transaction(async tx => {await pipelined(tx, [async () => { if (!opts.semanticsPrimed) await primeRelationSemantics(tx); },- () => tx.lockPageKeys([{ sourceId: origin.sourceId, slug: origin.slug }, ...rows.flatMap(row => [- { sourceId: row.from_source_id!, slug: row.from_slug }, { sourceId: row.to_source_id!, slug: row.to_slug },- ])]),+ () => tx.lockPageKeys(derivedLinkLockKeys(origin, rows)),]);- if (opts.lineGrammar) {- // FOR SHARE: a concurrent setting change (which updates this row) waits for this publication, or this one sees it.- const [gen] = await tx.executeRaw<{ value: string }>('SELECT value FROM config WHERE key = $1 FOR SHARE', [LINK_EXTRACTION_GENERATION_KEY]);- if ((gen?.value ?? null) !== opts.lineGrammar.generation) throw new DerivedLinkSettingsChangedError();- }+ if (opts.lineGrammar && await lockedExtractionGeneration(tx) !== opts.lineGrammar.generation) throw new DerivedLinkSettingsChangedError();const snapshot = origin.snapshot !== undefined ? origin.snapshot : await tx.readPageSnapshot(origin.slug, { sourceId: origin.sourceId });- assertPageRevision(snapshot, { expectedRevision: origin.expectedRevision });- if (!snapshot || snapshot.sourceIncarnation !== origin.sourceIncarnation || snapshot.page.deleted_at) {- throw new Error('Derived link origin changed or was deleted');+ return publishDerivedLinks(tx, origin, producers, rows, opts, snapshot);+ });+}++export interface DerivedLinkBatchItem { origin: DerivedLinkOrigin; links: LinkBatchInput[]; opts?: DerivedLinkReplacementOptions }++/**+ * replaceDerivedLinks for many origins in one transaction (bulk `extract+ * --source db`). Each origin runs the same checks and writes as its own call,+ * in order; the relation-semantics prime, the page guards (every origin and+ * endpoint, one sorted lock), the extraction-generation check and the origin+ * reads are shared. Any failure, a settings change included, rolls the whole+ * batch back; callers that need per-origin outcomes then replay the origins+ * one by one through replaceDerivedLinks.+ */+export async function replaceDerivedLinksBatch(+ engine: Pick<BrainEngine, 'transaction'>,+ items: readonly DerivedLinkBatchItem[],+): Promise<Array<{ created: number; removed: number }>> {+ const prepared = items.map(item => ({ origin: item.origin, opts: item.opts ?? {}, ...derivedLinkRows(item.origin, item.links, item.opts ?? {}) }));+ if (!prepared.length) return [];+ return engine.transaction(async tx => {+ await pipelined(tx, [+ async () => { if (prepared.some(item => !item.opts.semanticsPrimed)) await primeRelationSemantics(tx); },+ () => tx.lockPageKeys(prepared.flatMap(item => derivedLinkLockKeys(item.origin, item.rows))),+ ]);+ if (prepared.some(item => item.opts.lineGrammar)) {+ const generation = await lockedExtractionGeneration(tx);+ if (prepared.some(item => item.opts.lineGrammar && item.opts.lineGrammar.generation !== generation)) throw new DerivedLinkSettingsChangedError();+ }+ const { snapshots } = await readPageSnapshotsBatch(tx, prepared.filter(item => item.origin.snapshot === undefined)+ .map(item => ({ slug: item.origin.slug, sourceId: item.origin.sourceId })), { maxBytes: Number.MAX_SAFE_INTEGER });+ const results: Array<{ created: number; removed: number }> = [];+ for (const { origin, producers, rows, opts } of prepared) {+ const snapshot = origin.snapshot !== undefined ? origin.snapshot : snapshots.get(pageSnapshotKey(origin.sourceId, origin.slug)) ?? null;+ results.push(await publishDerivedLinks(tx, origin, producers, rows, opts, snapshot));+ }+ return results;+ });+}++/**+ * Publish through replaceDerivedLinksBatch; when that transaction fails,+ * replay the origins one by one so every outcome is the unbatched one: null+ * for a settings-changed skip, and the first failing origin's error thrown+ * (after `onError`) with the origins before it committed.+ */+export async function replaceDerivedLinksBatchOrReplay(engine: Pick<BrainEngine, 'replaceDerivedLinks' | 'replaceDerivedLinksBatch'>,+ items: readonly DerivedLinkBatchItem[], onError?: (item: DerivedLinkBatchItem) => void): Promise<Array<{ created: number; removed: number } | null>> {+ if (!items.length) return [];+ try { return await engine.replaceDerivedLinksBatch(items); }+ catch {+ const results: Array<{ created: number; removed: number } | null> = [];+ for (const item of items) {+ try { results.push(await replaceDerivedLinksUnlessSettingsChanged(engine, item.origin, item.links, item.opts)); }+ catch (error) { onError?.(item); throw error; }}- const id = snapshot.page.id;- // The wanted-page replacement and every read the checks below need are sent together, then judged in order.- // Temporal evidence (tense, dated transitions, relationship state) is part- // of the same derived projection: captured before, replaced after.- type Existing = { id: number; from_slug: string; to_slug: string; from_source_id: string; to_source_id: string; link_type: string;- link_source: string | null; origin_slug: string | null; origin_source_id: string | null; context: string; origin_field: string | null };- const [, temporalKeysBefore, ambiguous, missing, changed, existing, inlineRanges] = await pipelined(tx, [- async () => { if (opts.wanted) await replaceWantedLinks(tx, { pageId: id, sourceId: origin.sourceId }, opts.wanted); },- () => relationshipKeysForOrigin(tx, Number(id)),- () => opts.includeFrontmatter !== false && !opts.preserveExisting ? tx.executeRaw(`SELECT 1 FROM links WHERE link_source='frontmatter'+ return results;+ }+}++/** Under the caller's guards: check the origin read, then replace its derived links and temporal evidence. */+async function publishDerivedLinks(tx: BrainEngine, origin: DerivedLinkOrigin, producers: string[], rows: LinkBatchInput[],+ opts: DerivedLinkReplacementOptions, snapshot: PageSnapshot | null): Promise<{ created: number; removed: number }> {+ assertPageRevision(snapshot, { expectedRevision: origin.expectedRevision });+ if (!snapshot || snapshot.sourceIncarnation !== origin.sourceIncarnation || snapshot.page.deleted_at) {+ throw new Error('Derived link origin changed or was deleted');+ }+ const id = snapshot.page.id;+ // The wanted-page replacement and every read the checks below need are sent together, then judged in order.+ // Temporal evidence (tense, dated transitions, relationship state) is part+ // of the same derived projection: captured before, replaced after.+ type Existing = { id: number; from_slug: string; to_slug: string; from_source_id: string; to_source_id: string; link_type: string;+ link_source: string | null; origin_slug: string | null; origin_source_id: string | null; context: string; origin_field: string | null };+ const [, temporalKeysBefore, ambiguous, missing, changed, existing, inlineRanges] = await pipelined(tx, [+ async () => { if (opts.wanted) await replaceWantedLinks(tx, { pageId: id, sourceId: origin.sourceId }, opts.wanted); },+ () => relationshipKeysForOrigin(tx, Number(id)),+ () => opts.includeFrontmatter !== false && !opts.preserveExisting ? tx.executeRaw(`SELECT 1 FROM links WHERE link_source='frontmatter'AND origin_page_id IS NULL AND (from_page_id=$1 OR to_page_id=$1) LIMIT 1`, [id]) : Promise.resolve([]),- () => executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')+ () => executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')AS v(from_slug text, to_slug text, from_source_id text, to_source_id text)LEFT JOIN pages f ON f.slug=v.from_slug AND f.source_id=v.from_source_id AND f.deleted_at IS NULLLEFT JOIN pages t ON t.slug=v.to_slug AND t.source_id=v.to_source_id AND t.deleted_at IS NULLWHERE f.id IS NULL OR t.id IS NULL LIMIT 1`, [], [{ rows }]),- () => opts.expectedEndpoints?.length ? executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')+ () => opts.expectedEndpoints?.length ? executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')AS v(slug text, "sourceId" text, revision text)LEFT JOIN pages p ON p.slug=v.slug AND p.source_id=v."sourceId" AND p.deleted_at IS NULLWHERE p.id IS NULL OR p.knowledge_revision::text <> v.revision LIMIT 1`, [], [{ rows: opts.expectedEndpoints }]) : Promise.resolve([]),- () => opts.preserveExisting ? tx.executeRaw<Existing>(`SELECT l.id, f.slug from_slug, t.slug to_slug,+ () => opts.preserveExisting ? tx.executeRaw<Existing>(`SELECT l.id, f.slug from_slug, t.slug to_slug,f.source_id from_source_id, t.source_id to_source_id, l.link_type, l.link_source,o.slug origin_slug, o.source_id origin_source_id, l.context, l.origin_fieldFROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id@@ -160,58 +231,57 @@ export async function replaceDerivedLinks(WHERE (l.link_source=ANY($2::text[]) OR ($3::boolean AND l.link_source IS NULL))AND (l.origin_page_id=$1 OR (l.origin_page_id IS NULL AND l.from_page_id=$1AND (l.link_source IN ('markdown','wikilink-resolved') OR l.link_source IS NULL)))`, [id, producers, opts.includeLegacyNullProducer !== false]) : Promise.resolve([]),- () => opts.lineGrammar ? Promise.resolve(opts.lineGrammar.effectiveRanges) : effectiveRangesEnabled(tx),- ]) as [unknown, Awaited<ReturnType<typeof relationshipKeysForOrigin>>, unknown[], unknown[], unknown[], Existing[], boolean];- const withTemporal = async (result: { created: number; removed: number }) => {- await applyTemporalEvidence(tx, snapshot.page, rows, temporalKeysBefore, { inlineRanges });- return result;- };- if (ambiguous.length) throw new DerivedLinkRepairRequiredError();- if (missing.length) throw new DerivedLinkEndpointChangedError('A derived link endpoint changed or was deleted');- if (changed.length) throw new DerivedLinkEndpointChangedError('A derived link endpoint changed after type resolution');- const reversed = rows.filter(row => row.link_type === 'attended' && row.origin_slug- && row.to_slug === origin.slug && row.to_source_id === origin.sourceId- && (row.from_slug !== origin.slug || row.from_source_id !== origin.sourceId));- if (reversed.length) {- if (snapshot.page.type !== 'meeting' || reversed.some(row => row.link_source !== 'frontmatter' && !opts.expectedEndpoints?.some(endpoint =>- endpoint.slug === row.from_slug && endpoint.sourceId === row.from_source_id))) {- throw new TypeError('Canonical attendance requires a meeting origin and revision-bound person endpoints');- }- const invalid = await executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')+ () => opts.lineGrammar ? Promise.resolve(opts.lineGrammar.effectiveRanges) : effectiveRangesEnabled(tx),+ ]) as [unknown, Awaited<ReturnType<typeof relationshipKeysForOrigin>>, unknown[], unknown[], unknown[], Existing[], boolean];+ const withTemporal = async (result: { created: number; removed: number }) => {+ await applyTemporalEvidence(tx, snapshot.page, rows, temporalKeysBefore, { inlineRanges });+ return result;+ };+ if (ambiguous.length) throw new DerivedLinkRepairRequiredError();+ if (missing.length) throw new DerivedLinkEndpointChangedError('A derived link endpoint changed or was deleted');+ if (changed.length) throw new DerivedLinkEndpointChangedError('A derived link endpoint changed after type resolution');+ const reversed = rows.filter(row => row.link_type === 'attended' && row.origin_slug+ && row.to_slug === origin.slug && row.to_source_id === origin.sourceId+ && (row.from_slug !== origin.slug || row.from_source_id !== origin.sourceId));+ if (reversed.length) {+ if (snapshot.page.type !== 'meeting' || reversed.some(row => row.link_source !== 'frontmatter' && !opts.expectedEndpoints?.some(endpoint =>+ endpoint.slug === row.from_slug && endpoint.sourceId === row.from_source_id))) {+ throw new TypeError('Canonical attendance requires a meeting origin and revision-bound person endpoints');+ }+ const invalid = await executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')AS v(from_slug text, from_source_id text)JOIN pages p ON p.slug=v.from_slug AND p.source_id=v.from_source_idWHERE p.type <> 'person' LIMIT 1`, [], [{ rows: reversed }]);- if (invalid.length) throw new TypeError('Canonical attendance requires person endpoints');- }- if (opts.preserveExisting) {- const identity = (row: Pick<LinkBatchInput, 'from_source_id' | 'from_slug' | 'to_source_id' | 'to_slug' | 'link_type'>- & { link_source?: string | null; origin_slug?: string | null }) => JSON.stringify([row.from_source_id, row.from_slug,- row.to_source_id, row.to_slug, row.link_type ?? '', row.link_source ?? 'markdown', row.origin_slug ?? null]);- const wanted = new Map(rows.map(row => [identity(row), row]));- const retained = new Set(existing.map(identity));- const obsolete = existing.filter(row => !wanted.has(identity(row))).map(row => row.id);- if (obsolete.length) await tx.executeRaw('DELETE FROM links WHERE id=ANY($1::bigint[])', [obsolete]);- const updates = existing.flatMap(previous => {- const desired = wanted.get(identity(previous));- if (!desired) return [];- const context = sanitizeForJsonb(desired.context || '');- const origin_field = desired.origin_field || null;- return previous.context !== context || previous.origin_field !== origin_field- ? [{ id: previous.id, context, origin_field }] : [];- });- if (updates.length) await executeRawJsonb(tx, `UPDATE links l SET context=v.context, origin_field=v.origin_field+ if (invalid.length) throw new TypeError('Canonical attendance requires person endpoints');+ }+ if (opts.preserveExisting) {+ const identity = (row: Pick<LinkBatchInput, 'from_source_id' | 'from_slug' | 'to_source_id' | 'to_slug' | 'link_type'>+ & { link_source?: string | null; origin_slug?: string | null }) => JSON.stringify([row.from_source_id, row.from_slug,+ row.to_source_id, row.to_slug, row.link_type ?? '', row.link_source ?? 'markdown', row.origin_slug ?? null]);+ const wanted = new Map(rows.map(row => [identity(row), row]));+ const retained = new Set(existing.map(identity));+ const obsolete = existing.filter(row => !wanted.has(identity(row))).map(row => row.id);+ if (obsolete.length) await tx.executeRaw('DELETE FROM links WHERE id=ANY($1::bigint[])', [obsolete]);+ const updates = existing.flatMap(previous => {+ const desired = wanted.get(identity(previous));+ if (!desired) return [];+ const context = sanitizeForJsonb(desired.context || '');+ const origin_field = desired.origin_field || null;+ return previous.context !== context || previous.origin_field !== origin_field+ ? [{ id: previous.id, context, origin_field }] : [];+ });+ if (updates.length) await executeRawJsonb(tx, `UPDATE links l SET context=v.context, origin_field=v.origin_fieldFROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(id bigint, context text, origin_field text)WHERE l.id=v.id`, [], [{ rows: updates }]);- const additions = rows.filter(row => !retained.has(identity(row)));- const created = additions.length ? await tx.addLinksBatch(additions, { auditSite: 'addLinksBatch' }) : 0;- if (created !== additions.length) throw new Error('Derived link replacement did not persist every candidate');- return withTemporal({ created, removed: obsolete.length });- }- const removed = await tx.executeRaw(`DELETE FROM links WHERE link_source=ANY($2::text[])+ const additions = rows.filter(row => !retained.has(identity(row)));+ const created = additions.length ? await tx.addLinksBatch(additions, { auditSite: 'addLinksBatch' }) : 0;+ if (created !== additions.length) throw new Error('Derived link replacement did not persist every candidate');+ return withTemporal({ created, removed: obsolete.length });+ }+ const removed = await tx.executeRaw(`DELETE FROM links WHERE link_source=ANY($2::text[])AND (origin_page_id=$1 OR (origin_page_id IS NULL AND from_page_id=$1AND link_source IN ('markdown','wikilink-resolved'))) RETURNING id`, [id, producers]);- const created = await tx.addLinksBatch(rows, { auditSite: 'addLinksBatch' });- if (created !== rows.length) throw new Error('Derived link replacement did not persist every candidate');- return withTemporal({ created, removed: removed.length });- });+ const created = await tx.addLinksBatch(rows, { auditSite: 'addLinksBatch' });+ if (created !== rows.length) throw new Error('Derived link replacement did not persist every candidate');+ return withTemporal({ created, removed: removed.length });}diff --git a/src/core/engine.ts b/src/core/engine.tsindex 3a166351df..153aa3ee90 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -2,7 +2,7 @@ import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } froimport type { GetVersionsOpts, PageVersionRows } from './page-state/version-types.ts';import type { LinkReadScope } from './link-validity.ts';import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';-import type { DerivedLinkOrigin, DerivedLinkReplacementOptions } from './derived-links.ts';+import type { DerivedLinkBatchItem, DerivedLinkOrigin, DerivedLinkReplacementOptions } from './derived-links.ts';export type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions, PageMutationPrecondition, PageWithdrawal } from './page-state/types.ts';import type {Page, PageInput, PageFilters, GetPageOpts, PageReadScope, PageReadPolicy,@@ -1413,6 +1413,8 @@ export interface BrainEngine {*/addLinksBatch(links: LinkBatchInput[], opts?: BatchOpts): Promise<number>;replaceDerivedLinks(origin: DerivedLinkOrigin, links: LinkBatchInput[], opts?: DerivedLinkReplacementOptions): Promise<{ created: number; removed: number }>;+ /** replaceDerivedLinks for many origins in one transaction; any failure rolls back every origin (derived-links.ts). */+ replaceDerivedLinksBatch(items: readonly DerivedLinkBatchItem[]): Promise<Array<{ created: number; removed: number }>>;/*** Remove links from `from` to `to`. If linkType is provided, only that specific* (from, to, type) row is removed. If omitted, ALL link types between the pairdiff --git a/src/core/page-snapshot-batch.ts b/src/core/page-snapshot-batch.tsnew file mode 100644index 0000000000..179754df5b--- /dev/null+++ b/src/core/page-snapshot-batch.ts@@ -0,0 +1,81 @@+/**+ * Batched exact-key page snapshots for bulk walks (`gbrain extract --source db`).+ *+ * One statement returns, for a run of `(slug, sourceId)` refs, the same+ * `PageSnapshot` that `engine.readPageSnapshot(slug, { sourceId })` returns+ * for each: live rows only, tags, withdrawals, source incarnation and the+ * withdrawal overlay. The projection mirrors `page-state/snapshot.ts`+ * (pinned by test/page-snapshot-batch.test.ts); the line fingerprints the+ * overlay needs are only computed for a page that has withdrawals, because+ * `overlayWithdrawalBody` ignores them otherwise.+ *+ * Page bodies are unbounded, so a call covers the longest prefix of `refs`+ * whose bodies fit `maxBytes` (always at least one ref); `covered` says how+ * many refs the result answers. A ref the statement does not return is read+ * again through `readPageSnapshot`, so a caller never gets less than the+ * per-page read would give it.+ */+import type { BrainEngine } from './engine.ts';+import { overlayWithdrawalBody } from './facts/withdrawal-overlay.ts';+import type { PageSnapshot, PageWithdrawal } from './page-state/types.ts';+import { REVISION_BACKFILL_PENDING } from './page-state/types.ts';+import { rowToPage } from './utils.ts';++export const PAGE_SNAPSHOT_BATCH_MAX_BYTES = 32 * 1024 * 1024;++export const pageSnapshotKey = (sourceId: string, slug: string) => `${sourceId}\u0000${slug}`;++export interface PageSnapshotBatch {+ /** Keyed by `pageSnapshotKey(sourceId, slug)`; refs with no live page are absent. */+ snapshots: Map<string, PageSnapshot>;+ /** How many leading refs this batch answers. */+ covered: number;+}++export async function readPageSnapshotsBatch(+ engine: Pick<BrainEngine, 'executeRaw' | 'readPageSnapshot'>,+ refs: ReadonlyArray<{ slug: string; sourceId: string }>,+ opts: { maxBytes?: number } = {},+): Promise<PageSnapshotBatch> {+ const snapshots = new Map<string, PageSnapshot>();+ if (!refs.length) return { snapshots, covered: 0 };+ const rows = await engine.executeRaw<Record<string, unknown>>(`WITH wanted AS (+ SELECT v.slug AS batch_slug, v.source_id AS batch_source_id, v.n AS batch_n, p.id AS batch_page_id,+ COALESCE(sum(octet_length(p.compiled_truth) + COALESCE(octet_length(p.timeline), 0))+ OVER (ORDER BY v.n ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS batch_prior_bytes+ FROM unnest($1::text[], $2::text[]) WITH ORDINALITY AS v(slug, source_id, n)+ LEFT JOIN pages p ON p.slug = v.slug AND p.source_id = v.source_id AND p.deleted_at IS NULL+ ), chosen AS (+ SELECT w.batch_n, w.batch_slug, w.batch_source_id, p.* FROM wanted w LEFT JOIN pages p ON p.id = w.batch_page_id+ WHERE w.batch_n = 1 OR w.batch_prior_bytes < $3+ ) SELECT p.*,+ (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation,+ COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags,+ wd.snapshot_withdrawals,+ CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)+ FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body,+ CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)+ FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline+ FROM chosen p+ CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at)+ ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at+ FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug)+ GROUP BY visibility,fact_hash) w), '[]'::jsonb) AS snapshot_withdrawals) wd+ ORDER BY p.batch_n`,+ [refs.map(r => r.slug), refs.map(r => r.sourceId), opts.maxBytes ?? PAGE_SNAPSHOT_BATCH_MAX_BYTES]);+ for (const row of rows) {+ const key = pageSnapshotKey(String(row.batch_source_id), String(row.batch_slug));+ if (row.id == null) {+ const snapshot = await engine.readPageSnapshot(String(row.batch_slug), { sourceId: String(row.batch_source_id) });+ if (snapshot) snapshots.set(key, snapshot);+ continue;+ }+ const page = rowToPage(row);+ const withdrawals = row.snapshot_withdrawals as PageWithdrawal[];+ page.compiled_truth = overlayWithdrawalBody(page.compiled_truth, String(row.fingerprint_body ?? ''), withdrawals);+ page.timeline = overlayWithdrawalBody(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);+ snapshots.set(key, { page, tags: row.snapshot_tags as string[], revision: row.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(row.knowledge_revision),+ sourceIncarnation: String(row.source_incarnation), withdrawals });+ }+ return { snapshots, covered: rows.length };+}diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex 501f903d99..460e4c6328 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -172,10 +172,12 @@ function storedTimeline(engine: BrainEngine, pageId: number): Promise<StoredTime* Timeline tuples the coordinator projects from a canonical page body that* have no stored row on the page under the same normalized key. Insert-only* callers (managed `extract --stale`) add exactly these, so a stored row that- * differs only by whitespace is not duplicated.+ * differs only by whitespace is not duplicated. `storedRows` is the caller's+ * own read of the page's non-event rows (a batched walk).*/-export async function unrecordedCanonicalTimeline(engine: BrainEngine, pageId: number, body: CanonicalBody, slug: string): Promise<ExtractedTimelineEntry[]> {- const stored = new Set((await storedTimeline(engine, pageId)).map(row => timelineKey(row)));+export async function unrecordedCanonicalTimeline(engine: BrainEngine, pageId: number, body: CanonicalBody, slug: string,+ storedRows?: ReadonlyArray<Pick<StoredTimelineRow, 'date' | 'source' | 'summary'>>): Promise<ExtractedTimelineEntry[]> {+ const stored = new Set((storedRows ?? await storedTimeline(engine, pageId)).map(row => timelineKey(row)));return [...canonicalTimeline(body, slug)].filter(([key]) => !stored.has(key)).map(([, entry]) => entry);}diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 3c75c6b41e..b36d631b49 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1,5 +1,5 @@import { registerManagedFilesystemEngine } from './persistence/filesystem-guard.ts';-import { replaceDerivedLinks, type DerivedLinkOrigin, type DerivedLinkReplacementOptions } from './derived-links.ts';+import { replaceDerivedLinks, replaceDerivedLinksBatch, type DerivedLinkBatchItem, type DerivedLinkOrigin, type DerivedLinkReplacementOptions } from './derived-links.ts';import { trackPgliteDatabase, PgliteClosingError, notifyPgliteOpened } from './pglite-lifecycle.ts';import { mutatePageTag } from './page-state/tags.ts';import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';@@ -1883,6 +1883,10 @@ export class PGLiteEngine implements BrainEngine {return replaceDerivedLinks(this, origin, links, opts);}+ async replaceDerivedLinksBatch(items: readonly DerivedLinkBatchItem[]) {+ return replaceDerivedLinksBatch(this, items);+ }+// #3674 — see BrainEngine.removeLinksByPagesAndSource JSDoc. Identical SQL// shape in PostgresEngine (parity). JSONB recordset binding (never// JSON.stringify into ::jsonb — executeRawJsonb passes raw objects).diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 263ecc71fc..a8762ef34b 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -1,5 +1,5 @@import { tryAcquirePoolLongHold, PoolCapacityError } from './pool-budget.ts';-import { replaceDerivedLinks, type DerivedLinkOrigin, type DerivedLinkReplacementOptions } from './derived-links.ts';+import { replaceDerivedLinks, replaceDerivedLinksBatch, type DerivedLinkBatchItem, type DerivedLinkOrigin, type DerivedLinkReplacementOptions } from './derived-links.ts';import { mutatePageTag } from './page-state/tags.ts';import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';import type { GetVersionsOpts, PageVersionRows } from './page-state/version-types.ts';@@ -1602,6 +1602,10 @@ export class PostgresEngine implements BrainEngine {return replaceDerivedLinks(this, origin, links, opts);}+ async replaceDerivedLinksBatch(items: readonly DerivedLinkBatchItem[]) {+ return replaceDerivedLinksBatch(this, items);+ }+// #3674 — see BrainEngine.removeLinksByPagesAndSource JSDoc. Identical SQL// shape in PGLiteEngine (parity). JSONB recordset binding (never// JSON.stringify into ::jsonb — executeRawJsonb passes raw objects).diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.tsindex 7ed1280637..4720f84631 100644--- a/src/core/timeline-extract.ts+++ b/src/core/timeline-extract.ts@@ -138,6 +138,9 @@ function markdownTimelineKeys(text: string, slug: string): Set<string> {return keys;}+/** A page's stored non-event timeline row as reconciliation reads it (`date` is `YYYY-MM-DD`). */+export type StoredTimelineTuple = TimelineTuple & { id: number; detail: string | null };+/*** Reconcile a page's timeline rows with its current text: retract every row* an earlier version of the page produced that the current text no longer@@ -145,17 +148,18 @@ function markdownTimelineKeys(text: string, slug: string): Set<string> {* version of the page ever produced (enrichment, meeting fan-out, inferred* anchors) and event-page projections are never touched. The page_versions* scan only runs when the page holds a row the current text does not produce.- * Returns the orphaned rows; they are deleted unless `dryRun`.+ * Returns the orphaned rows; they are deleted unless `dryRun`. `storedRows`+ * is the caller's own read of those rows (a batched walk), used instead of reading them here.*/export async function retractRemovedTimelineEntries(engine: Pick<BrainEngine, 'executeRaw'>,slug: string,sourceId: string,currentText: string,- opts: { dryRun?: boolean } = {},+ opts: { dryRun?: boolean; storedRows?: ReadonlyArray<StoredTimelineTuple> } = {},): Promise<Array<TimelineTuple & { id: number }>> {const kept = markdownTimelineKeys(currentText, slug);- const rows = await engine.executeRaw<TimelineTuple & { id: number; detail: string | null }>(+ const rows = opts.storedRows ?? await engine.executeRaw<StoredTimelineTuple>(`SELECT t.id, to_char(t.date, 'YYYY-MM-DD') AS date, t.source, t.summary, t.detail FROM timeline_entries tJOIN pages p ON p.id = t.page_idWHERE p.source_id = $1 AND p.slug = $2 AND t.event_page_id IS NULL`, [sourceId, slug]);diff --git a/test/e2e/extract-db-batch-equivalence.test.ts b/test/e2e/extract-db-batch-equivalence.test.tsnew file mode 100644index 0000000000..26874a6234--- /dev/null+++ b/test/e2e/extract-db-batch-equivalence.test.ts@@ -0,0 +1,27 @@+/**+ * Postgres arm of test/extract-db-batch-equivalence.test.ts (GBRA-69): the+ * batched `extract all --source db` walk, and its page-by-page replay, leave+ * the rows the per-page walk left (the same golden as PGLite).+ */+import { describe, test } from 'bun:test';+import { expectGolden } from '../helpers/golden.ts';+import { managedBrain } from '../helpers/managed-brain.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { EXTRACT_ROWS, failEveryBatch, managedRounds, seedExtractFixture, unmanagedRounds } from '../helpers/extract-db-batch-fixture.ts';++const url = process.env.DATABASE_URL;+describe.skipIf(!url)('Postgres batched extract all --source db', () => {+ for (const replay of [false, true]) {+ test(`unmanaged brain${replay ? ', every batch replayed' : ''}: the rows the per-page walk left`, async () => {+ const { engine, close } = await isolatedPersistencePostgres(url!);+ try {+ if (replay) failEveryBatch(engine);+ expectGolden('extract-db-batch/unmanaged', await unmanagedRounds(engine), EXTRACT_ROWS);+ } finally { await close(); }+ }, 240_000);+ test(`managed brain${replay ? ', every batch replayed' : ''}: the rows the per-page walk left`, () => managedBrain(async ({ engine }) => {+ if (replay) failEveryBatch(engine);+ expectGolden('extract-db-batch/managed', await managedRounds(engine), EXTRACT_ROWS);+ }, { databaseUrl: url, setup: ({ engine }) => seedExtractFixture(engine) }), 240_000);+ }+});diff --git a/test/e2e/page-snapshot-batch.test.ts b/test/e2e/page-snapshot-batch.test.tsnew file mode 100644index 0000000000..9be25adb2f--- /dev/null+++ b/test/e2e/page-snapshot-batch.test.ts@@ -0,0 +1,15 @@+/** Postgres arm of test/page-snapshot-batch.test.ts (GBRA-69). */+import { afterAll, beforeAll, describe, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { pageSnapshotBatchMatchesPerPageReads, pageSnapshotBatchRespectsByteBudget } from '../helpers/page-snapshot-batch-cases.ts';++const url = process.env.DATABASE_URL;+describe.skipIf(!url)('Postgres readPageSnapshotsBatch', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => { ({ engine, close } = await isolatedPersistencePostgres(url!)); }, 120_000);+ afterAll(async () => { await close?.(); });+ test('batched snapshots equal the per-page reads, missing and deleted refs included', () => pageSnapshotBatchMatchesPerPageReads(engine));+ test('a batch covers the longest prefix that fits the byte budget, never less than one ref', () => pageSnapshotBatchRespectsByteBudget(engine));+});diff --git a/test/engine-surface-coverage.test.ts b/test/engine-surface-coverage.test.tsindex 112aacbf0f..f7fed2a10b 100644--- a/test/engine-surface-coverage.test.ts+++ b/test/engine-surface-coverage.test.ts@@ -62,7 +62,7 @@ const INTERFACE_METHODS: readonly string[] = [// Extraction watermark'countStalePagesForExtraction', 'listStalePagesForExtraction', 'markPagesExtractedBatch', 'markPagesAttendanceBlocked',// Links + graph- 'addLink', 'addLinksBatch', 'replaceDerivedLinks', 'removeLink', 'getLinks', 'getBacklinks', 'listLinkSources',+ 'addLink', 'addLinksBatch', 'replaceDerivedLinks', 'replaceDerivedLinksBatch', 'removeLink', 'getLinks', 'getBacklinks', 'listLinkSources','findByTitleFuzzy', 'traverseGraph', 'traversePaths', 'traversePathsDetailed', 'relationalFanout', 'relationalChainHop', 'getBacklinkCounts','getAdjacencyBoosts', 'getContentFlagsByPageIds', 'getUnverifiedExtractionPageIds','getPageTimestamps', 'getEffectiveDates', 'getSalienceScores', 'findOrphanPages',diff --git a/test/extract-db-batch-equivalence.test.ts b/test/extract-db-batch-equivalence.test.tsnew file mode 100644index 0000000000..83579d32cb--- /dev/null+++ b/test/extract-db-batch-equivalence.test.ts@@ -0,0 +1,43 @@+/**+ * GBRA-69: `gbrain extract all --source db` reads and publishes pages in+ * batches. The rows it leaves are pinned by a golden captured with the+ * per-page walk it replaced (master before the change), so batching changes+ * no link, timeline, transition, relationship, wanted-link, stamp or request+ * row. A batch whose transaction fails is replayed page by page and must+ * leave the same rows. Postgres arm: test/e2e/extract-db-batch-equivalence.test.ts.+ */+import { expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { expectGolden } from './helpers/golden.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { EXTRACT_ROWS, failEveryBatch, managedRounds, seedExtractFixture, unmanagedRounds } from './helpers/extract-db-batch-fixture.ts';++/** Each unmanaged case starts from a freshly initialized brain, like the golden's capture. */+async function withPglite(run: (engine: BrainEngine) => Promise<void>) {+ const { engine, close } = await isolatedSharedSkillsEngine();+ try { await run(engine); } finally { await close(); }+}++test('unmanaged brain: batched extract leaves the rows the per-page walk left', () => withPglite(async engine => {+ const rounds = await unmanagedRounds(engine);+ expect(rounds.first.exitCode).toBe(0);+ expect(rounds.afterFirst.links.length).toBeGreaterThan(300);+ expectGolden('extract-db-batch/unmanaged', rounds, EXTRACT_ROWS);+}), 180_000);++test('unmanaged brain: a failed batch replays page by page to the same rows', () => withPglite(async engine => {+ failEveryBatch(engine);+ expectGolden('extract-db-batch/unmanaged', await unmanagedRounds(engine), EXTRACT_ROWS);+}), 180_000);++test('managed brain: batched extract leaves the rows the per-page walk left', () => managedBrain(async ({ engine }) => {+ const rounds = await managedRounds(engine);+ expect(rounds.afterFirst.extract_requests.length).toBeGreaterThan(0);+ expectGolden('extract-db-batch/managed', rounds, EXTRACT_ROWS);+}, { setup: ({ engine }) => seedExtractFixture(engine) }), 240_000);++test('managed brain: a failed batch replays page by page to the same rows', () => managedBrain(async ({ engine }) => {+ failEveryBatch(engine);+ expectGolden('extract-db-batch/managed', await managedRounds(engine), EXTRACT_ROWS);+}, { setup: ({ engine }) => seedExtractFixture(engine) }), 240_000);diff --git a/test/extract-endpoint-revision.serial.test.ts b/test/extract-endpoint-revision.serial.test.tsindex d346f69d54..de9b064d33 100644--- a/test/extract-endpoint-revision.serial.test.ts+++ b/test/extract-endpoint-revision.serial.test.ts@@ -1,6 +1,6 @@import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';import type { BrainEngine, LinkBatchInput } from '../src/core/engine.ts';-import type { DerivedLinkReplacementOptions } from '../src/core/derived-links.ts';+import type { DerivedLinkOrigin, DerivedLinkReplacementOptions } from '../src/core/derived-links.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runExtract, extractStaleFromDB } from '../src/commands/extract.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -69,18 +69,26 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1 AND slug=$2', [sourceId, originSlug]);const targetSnapshot = (await engine.readPageSnapshot(targetSlug, { sourceId: targetSourceId }))!;const original = engine.replaceDerivedLinks;+ const originalBatch = engine.replaceDerivedLinksBatch;let retyped = false;let captured: LinkBatchInput[] = [];let fences: DerivedLinkReplacementOptions['expectedEndpoints'];- engine.replaceDerivedLinks = async (origin, links, opts) => {+ const retypeBeforePublishing = async (origin: DerivedLinkOrigin, links: LinkBatchInput[], opts?: DerivedLinkReplacementOptions) => {if (!retyped && origin.sourceId === sourceId && origin.slug === originSlug) {retyped = true;captured = links;fences = opts?.expectedEndpoints;await engine.putPage(targetSlug, { type: 'decision', title: 'Decision Example', compiled_truth: 'Retyped after inference.' }, { sourceId: targetSourceId });}+ };+ engine.replaceDerivedLinks = async (origin, links, opts) => {+ await retypeBeforePublishing(origin, links, opts);return original.call(engine, origin, links, opts);};+ engine.replaceDerivedLinksBatch = async items => {+ for (const item of items) await retypeBeforePublishing(item.origin, item.links, item.opts);+ return originalBatch.call(engine, items);+ };const errors: string[] = [];const errorSpy = spyOn(console, 'error').mockImplementation((...args) => { errors.push(args.join(' ')); });const exitSpy = spyOn(process, 'exit').mockImplementation(code => { throw new Error(`extract exited ${code}`); });@@ -92,6 +100,7 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]}} finally {engine.replaceDerivedLinks = original;+ engine.replaceDerivedLinksBatch = originalBatch;errorSpy.mockRestore();exitSpy.mockRestore();}diff --git a/test/fixtures/goldens/extract-db-batch/managed.json b/test/fixtures/goldens/extract-db-batch/managed.jsonnew file mode 100644index 0000000000..585f45d27b--- /dev/null+++ b/test/fixtures/goldens/extract-db-batch/managed.json@@ -0,0 +1,101 @@+{+ "golden": {+ "afterFirst": {+ "extract_requests": {+ "rows": 150,+ "sha256": "e5f71a914d25580d3fc36e596da534fe40c0d0a8372db70492cf3fff505de00e"+ },+ "facts": {+ "rows": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "link_relationships": {+ "rows": 136,+ "sha256": "393f60423b8b08070af353b1009cf6f196549188e88d46b9da71bd9eb6ec38dc"+ },+ "link_transitions": {+ "rows": 8,+ "sha256": "feac8f234bd36003f0982af6fd41ada4b59f6eb8d0e4385289d4fa06ce899255"+ },+ "links": {+ "rows": 613,+ "sha256": "e5574e1644d5688ac084ff5a11511d4e3f9d0d4cd7790addfa408942fba118ca"+ },+ "pages": {+ "rows": 225,+ "sha256": "0da3bcbfe226af0c98403618f91cd341fc1e53de8001b2a3ce7d4a96751dc70c"+ },+ "tags": {+ "rows": 1,+ "sha256": "a434b780ac89394fc00ef3eda220e530225f65b3be98c0c8efcdf930c1be8fd5"+ },+ "timeline_entries": {+ "rows": 198,+ "sha256": "6ff1b450d65f319d5edb69764ea9e77a5a96e47d4dc85ab209dc035fa148844f"+ },+ "wanted_links": {+ "rows": 24,+ "sha256": "eb7a473a72827b9be947cfad0b4d028f695f08285a59f7628475e92b0d917f76"+ }+ },+ "afterSecond": {+ "extract_requests": {+ "rows": 150,+ "sha256": "e5f71a914d25580d3fc36e596da534fe40c0d0a8372db70492cf3fff505de00e"+ },+ "facts": {+ "rows": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "link_relationships": {+ "rows": 136,+ "sha256": "393f60423b8b08070af353b1009cf6f196549188e88d46b9da71bd9eb6ec38dc"+ },+ "link_transitions": {+ "rows": 8,+ "sha256": "feac8f234bd36003f0982af6fd41ada4b59f6eb8d0e4385289d4fa06ce899255"+ },+ "links": {+ "rows": 613,+ "sha256": "e5574e1644d5688ac084ff5a11511d4e3f9d0d4cd7790addfa408942fba118ca"+ },+ "pages": {+ "rows": 225,+ "sha256": "0da3bcbfe226af0c98403618f91cd341fc1e53de8001b2a3ce7d4a96751dc70c"+ },+ "tags": {+ "rows": 1,+ "sha256": "a434b780ac89394fc00ef3eda220e530225f65b3be98c0c8efcdf930c1be8fd5"+ },+ "timeline_entries": {+ "rows": 198,+ "sha256": "6ff1b450d65f319d5edb69764ea9e77a5a96e47d4dc85ab209dc035fa148844f"+ },+ "wanted_links": {+ "rows": 24,+ "sha256": "eb7a473a72827b9be947cfad0b4d028f695f08285a59f7628475e92b0d917f76"+ }+ },+ "first": {+ "exitCode": 0,+ "result": {+ "links_created": 612,+ "pages_processed": 224,+ "skipped_cross_source": 0,+ "skipped_missing_target": 24,+ "timeline_entries_created": 198+ }+ },+ "second": {+ "exitCode": 0,+ "result": {+ "links_created": 612,+ "pages_processed": 224,+ "skipped_cross_source": 0,+ "skipped_missing_target": 24,+ "timeline_entries_created": 0+ }+ }+ },+ "normalizer": "extract-db-batch-rows-v1"+}diff --git a/test/fixtures/goldens/extract-db-batch/unmanaged.json b/test/fixtures/goldens/extract-db-batch/unmanaged.jsonnew file mode 100644index 0000000000..d945d51f14--- /dev/null+++ b/test/fixtures/goldens/extract-db-batch/unmanaged.json@@ -0,0 +1,101 @@+{+ "golden": {+ "afterFirst": {+ "extract_requests": {+ "rows": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "facts": {+ "rows": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "link_relationships": {+ "rows": 136,+ "sha256": "393f60423b8b08070af353b1009cf6f196549188e88d46b9da71bd9eb6ec38dc"+ },+ "link_transitions": {+ "rows": 8,+ "sha256": "feac8f234bd36003f0982af6fd41ada4b59f6eb8d0e4385289d4fa06ce899255"+ },+ "links": {+ "rows": 613,+ "sha256": "e5574e1644d5688ac084ff5a11511d4e3f9d0d4cd7790addfa408942fba118ca"+ },+ "pages": {+ "rows": 225,+ "sha256": "0da3bcbfe226af0c98403618f91cd341fc1e53de8001b2a3ce7d4a96751dc70c"+ },+ "tags": {+ "rows": 1,+ "sha256": "a434b780ac89394fc00ef3eda220e530225f65b3be98c0c8efcdf930c1be8fd5"+ },+ "timeline_entries": {+ "rows": 198,+ "sha256": "6ff1b450d65f319d5edb69764ea9e77a5a96e47d4dc85ab209dc035fa148844f"+ },+ "wanted_links": {+ "rows": 24,+ "sha256": "eb7a473a72827b9be947cfad0b4d028f695f08285a59f7628475e92b0d917f76"+ }+ },+ "afterSecond": {+ "extract_requests": {+ "rows": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "facts": {+ "rows": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "link_relationships": {+ "rows": 136,+ "sha256": "82323cef7c8325ca6a76906613163916a6b05475373b96e458a80e669e0bfc67"+ },+ "link_transitions": {+ "rows": 8,+ "sha256": "feac8f234bd36003f0982af6fd41ada4b59f6eb8d0e4385289d4fa06ce899255"+ },+ "links": {+ "rows": 602,+ "sha256": "c2da06a1ee2d0b634f4b2c67e5f3523828e8d33321f9ee769ca089aea6742aca"+ },+ "pages": {+ "rows": 225,+ "sha256": "2b40409816e9bce9fad4f9e4e9d034e28e391dba316e84054301eda547bf3023"+ },+ "tags": {+ "rows": 1,+ "sha256": "a434b780ac89394fc00ef3eda220e530225f65b3be98c0c8efcdf930c1be8fd5"+ },+ "timeline_entries": {+ "rows": 217,+ "sha256": "ed46d6ec785d238c785b9ccf0b17a1a5b5f3c3bc5ceddf025a85e497f35e3125"+ },+ "wanted_links": {+ "rows": 24,+ "sha256": "fc161886a205ab56e552784d27684f8963d0ab2f88fcd401d7d27f9f7a771e85"+ }+ },+ "first": {+ "exitCode": 0,+ "result": {+ "links_created": 612,+ "pages_processed": 224,+ "skipped_cross_source": 0,+ "skipped_missing_target": 24,+ "timeline_entries_created": 198+ }+ },+ "second": {+ "exitCode": 0,+ "result": {+ "links_created": 601,+ "pages_processed": 224,+ "skipped_cross_source": 0,+ "skipped_missing_target": 24,+ "timeline_entries_created": 19+ }+ }+ },+ "normalizer": "extract-db-batch-rows-v1"+}diff --git a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.jsonindex 27893a88d3..19b834dc1a 100644--- a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json+++ b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json@@ -290,6 +290,10 @@"raw": 12,"tx": 1},+ "replaceDerivedLinksBatch#default": {+ "raw": 13,+ "tx": 1+ },"resolveSlugWithAlias#default": {},"resolveSlugWithAliasDetailed#default": {},"resolveSlugWithAliasDetailed#excludePrivate": {},diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.jsonindex 723080250d..5d6f4f0876 100644--- a/test/fixtures/goldens/rls-scope-inventory.json+++ b/test/fixtures/goldens/rls-scope-inventory.json@@ -2551,6 +2551,19 @@"src-a"]},+ "replaceDerivedLinksBatch#default": {+ "flagOffLanes": [+ "tx",+ "tx>sp"+ ],+ "flagOffOpensTransaction": true,+ "flagOn": "unscoped",+ "flagOnLanes": [+ "tx",+ "tx>sp"+ ],+ "flagOnScopes": []+ },"resolveSlugWithAlias#default": {"flagOffLanes": ["pool"@@ -3495,6 +3508,7 @@"removeLinksByPagesAndSource": "none","removeTag": "none","replaceDerivedLinks": "none",+ "replaceDerivedLinksBatch": "none","resolveAliases": "none","resolveFactsEmbeddingCast": "none","resolveSlugWithAlias": "none",diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.jsonindex 817dcfa7ae..685bfb75fb 100644--- a/test/fixtures/goldens/sql-text/_classification.json+++ b/test/fixtures/goldens/sql-text/_classification.json@@ -6,7 +6,7 @@"code-edges": 5,"facts": 19,"files": 3,- "links": 12,+ "links": 13,"out-of-scope:config": 5,"out-of-scope:dream-verdicts": 3,"out-of-scope:eval-capture": 5,@@ -166,6 +166,7 @@"removeLinksByPagesAndSource": "links","removeTag": "tags","replaceDerivedLinks": "links",+ "replaceDerivedLinksBatch": "links","resolveAliases": "out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)","resolveFactsEmbeddingCast": "out-of-scope:internal-helper (private; exercised through public callers)","resolveSlugWithAlias": "pages",diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.jsonindex 91d0ccf8f8..5d70b5abac 100644--- a/test/fixtures/goldens/sql-text/_driver.json+++ b/test/fixtures/goldens/sql-text/_driver.json@@ -2188,6 +2188,143 @@}]},+ "replaceDerivedLinksBatch": {+ "default": [+ {+ "paramCount": 1,+ "via": "tagged"+ },+ {+ "paramCount": 1,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 2,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 2,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 2,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 1,+ "via": "tagged"+ },+ {+ "paramCount": 3,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 2,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 1,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 1,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 1,+ "via": "tagged"+ },+ {+ "paramCount": 1,+ "via": "tagged"+ },+ {+ "paramCount": 2,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 1,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 2,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 2,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },+ {+ "paramCount": 2,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ }+ ]+ },"traverseGraph": {"default": [{diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.jsonindex cf195bb136..40b5db4a58 100644--- a/test/fixtures/goldens/sql-text/links.json+++ b/test/fixtures/goldens/sql-text/links.json@@ -451,6 +451,181 @@}]},+ "replaceDerivedLinksBatch": {+ "default": [+ {+ "event": "begin",+ "lane": "tx"+ },+ {+ "lane": "tx",+ "params": [+ "string"+ ],+ "sql": "SELECT key FROM config WHERE key LIKE $1 ESCAPE '\\' ORDER BY key",+ "textSha256": "3b7f63477b863dc13bb07fe9cd6980979bd0f7e84196810c1f74ea994df43e79"+ },+ {+ "lane": "tx",+ "params": [+ "string"+ ],+ "sql": "SELECT incarnation FROM sources WHERE id=$1 FOR SHARE",+ "textSha256": "414efa2a18b3a4ac2f6f6675b6f7273b71c262a6bab8a44f82963606fed221d7"+ },+ {+ "lane": "tx",+ "params": [+ "array<string>",+ "array<string>"+ ],+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT i,s FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n) ORDER BY n ON CONFLICT DO NOTHING",+ "textSha256": "db6394eda2abba2a8ba0e233234bb764b79859d5462be942b725e581e8249151"+ },+ {+ "lane": "tx",+ "params": [+ "array<string>",+ "array<string>"+ ],+ "sql": "SELECT g.slug FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n) JOIN page_write_guards g ON g.source_incarnation=k.i AND g.slug=k.s ORDER BY k.n FOR UPDATE OF g",+ "textSha256": "69ee3b628ca6ff5d3e9e33077b9b22cb99da711d1bce84a4a566944b81d83d8e"+ },+ {+ "lane": "tx",+ "params": [+ "array<string>",+ "array<string>"+ ],+ "sql": "SELECT p.id FROM unnest($1::text[],$2::text[]) WITH ORDINALITY AS k(src,s,n) JOIN pages p ON p.source_id=k.src AND p.slug=k.s ORDER BY k.n FOR UPDATE OF p",+ "textSha256": "d2598c8eb0d051b3f8d25208513a7494b6db488c95574a3781e6db376d945b56"+ },+ {+ "lane": "tx",+ "params": [+ "string"+ ],+ "sql": "SELECT value FROM config WHERE key = $1",+ "textSha256": "32d050605cb95dccb4dcc33a20003cfd10f1fd8e194c317d54e08869acb32e9c"+ },+ {+ "lane": "tx",+ "params": [+ "array<string>",+ "array<string>",+ "number"+ ],+ "sql": "WITH wanted AS ( SELECT v.slug AS batch_slug, v.source_id AS batch_source_id, v.n AS batch_n, p.id AS batch_page_id, COALESCE(sum(octet_length(p.compiled_truth) + COALESCE(octet_length(p.timeline), 0)) OVER (ORDER BY v.n ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS batch_prior_bytes FROM unnest($1::text[], $2::text[]) WITH ORDINALITY AS v(slug, source_id, n) LEFT JOIN pages p ON p.slug = v.slug AND p.source_id = v.source_id AND p.deleted_at IS NULL ), chosen AS ( SELECT w.batch_n, w.batch_slug, w.batch_source_id, p.* FROM wanted w LEFT JOIN pages p ON p.id = w.batch_page_id WHERE w.batch_n = 1 OR w.batch_prior_bytes < $3 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) AS snapshot_withdrawals) wd ORDER BY p.batch_n",+ "textSha256": "831bb872f432b759aa480dc25b68755c59a83977fe089b4cfe149876fc972c84"+ },+ {+ "lane": "tx",+ "params": [+ "number",+ "number",+ "array<string>",+ "number",+ "number"+ ],+ "sql": "SELECT from_page_id, to_page_id, link_type FROM links WHERE (origin_page_id = $1 OR (origin_page_id IS NULL AND from_page_id = $2)) AND link_type = ANY($3::text[]) UNION SELECT from_page_id, to_page_id, link_type FROM link_transitions WHERE origin_page_id = $4 UNION SELECT from_page_id, to_page_id, link_type FROM link_relationships WHERE from_page_id = $5 AND scope = 'all'",+ "textSha256": "205ec70125f3e9182b0e9a6bb8865f923305e5652e69c750bca14d3568aecdb3"+ },+ {+ "lane": "tx",+ "params": [+ "number",+ "number"+ ],+ "sql": "SELECT 1 FROM links WHERE link_source='frontmatter' AND origin_page_id IS NULL AND (from_page_id=$1 OR to_page_id=$2) LIMIT 1",+ "textSha256": "b2c03345c2ab3512619e399a0e0aa81f14e82a23f6d3d9dedbac5a7066525049"+ },+ {+ "lane": "tx",+ "params": [+ "object"+ ],+ "sql": "SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(from_slug text, to_slug text, from_source_id text, to_source_id text) LEFT JOIN pages f ON f.slug=v.from_slug AND f.source_id=v.from_source_id AND f.deleted_at IS NULL LEFT JOIN pages t ON t.slug=v.to_slug AND t.source_id=v.to_source_id AND t.deleted_at IS NULL WHERE f.id IS NULL OR t.id IS NULL LIMIT 1",+ "textSha256": "6446f477cc034315f2e55e7d2489029b3229ffa2bcd339ee147aa3475914c957"+ },+ {+ "lane": "tx",+ "params": [+ "string"+ ],+ "sql": "SELECT value FROM config WHERE key = $1",+ "textSha256": "32d050605cb95dccb4dcc33a20003cfd10f1fd8e194c317d54e08869acb32e9c"+ },+ {+ "lane": "tx",+ "params": [+ "string"+ ],+ "sql": "SELECT value FROM config WHERE key = $1",+ "textSha256": "32d050605cb95dccb4dcc33a20003cfd10f1fd8e194c317d54e08869acb32e9c"+ },+ {+ "lane": "tx",+ "params": [+ "array<string>",+ "number",+ "number"+ ],+ "sql": "DELETE FROM links WHERE link_source=ANY($1::text[]) AND (origin_page_id=$2 OR (origin_page_id IS NULL AND from_page_id=$3 AND link_source IN ('markdown','wikilink-resolved'))) RETURNING id",+ "textSha256": "139b6f1adbab926678851d9ab9aa31c10522ad78488ed0ce1daca8c5b2952cac"+ },+ {+ "event": "savepoint",+ "lane": "tx>sp"+ },+ {+ "lane": "tx>sp",+ "params": [+ "object"+ ],+ "sql": "INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, link_kind, origin_page_id, origin_field) SELECT f.id, t.id, v.link_type, v.context, v.link_source, v.link_kind, o.id, v.origin_field FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v( from_slug text, to_slug text, link_type text, context text, link_source text, origin_slug text, origin_field text, from_source_id text, to_source_id text, origin_source_id text, link_kind text ) JOIN pages f ON f.slug = v.from_slug AND f.source_id = v.from_source_id JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id LEFT JOIN pages o ON o.slug = v.origin_slug AND o.source_id = v.origin_source_id ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO NOTHING RETURNING from_page_id, to_page_id, link_type",+ "textSha256": "feee32f8e94cf3aafc82c8d95828ed2d63babe9d9caf645435bc20050158e1b8"+ },+ {+ "event": "savepoint-release",+ "lane": "tx>sp"+ },+ {+ "lane": "tx",+ "params": [+ "object",+ "number",+ "number"+ ],+ "sql": "UPDATE links l SET assertion_tense = v.tense FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(from_slug text, to_slug text, link_type text, link_source text, from_source_id text, to_source_id text, tense text) JOIN pages f ON f.slug = v.from_slug AND f.source_id = v.from_source_id JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id WHERE l.from_page_id = f.id AND l.to_page_id = t.id AND l.link_type = v.link_type AND l.link_source = v.link_source AND (l.origin_page_id = $2 OR (l.origin_page_id IS NULL AND l.from_page_id = $3)) AND l.assertion_tense IS DISTINCT FROM v.tense",+ "textSha256": "3e981a0e85ebda344f510e8c26068decb62c8c54a85f1e3bcfc2cae0963ef3aa"+ },+ {+ "lane": "tx",+ "params": [+ "number",+ "array<string>"+ ],+ "sql": "DELETE FROM link_transitions WHERE origin_page_id = $1 AND producer = ANY($2::text[])",+ "textSha256": "968b36242f79a4ab122e45782864f2b3d0a9a7fb0f415c42b01a84985d19e7c3"+ },+ {+ "lane": "tx",+ "params": [+ "number",+ "number",+ "array<string>",+ "number",+ "number"+ ],+ "sql": "SELECT from_page_id, to_page_id, link_type FROM links WHERE (origin_page_id = $1 OR (origin_page_id IS NULL AND from_page_id = $2)) AND link_type = ANY($3::text[]) UNION SELECT from_page_id, to_page_id, link_type FROM link_transitions WHERE origin_page_id = $4 UNION SELECT from_page_id, to_page_id, link_type FROM link_relationships WHERE from_page_id = $5 AND scope = 'all'",+ "textSha256": "205ec70125f3e9182b0e9a6bb8865f923305e5652e69c750bca14d3568aecdb3"+ },+ {+ "event": "commit",+ "lane": "tx"+ }+ ]+ },"traverseGraph": {"default": [{diff --git a/test/helpers/extract-db-batch-fixture.ts b/test/helpers/extract-db-batch-fixture.tsnew file mode 100644index 0000000000..fbb1cc1054--- /dev/null+++ b/test/helpers/extract-db-batch-fixture.ts@@ -0,0 +1,179 @@+/**+ * Synthetic brain for the batched `gbrain extract all --source db` walk+ * (GBRA-69): enough pages for several 100-page batches across two sources,+ * with every derived row the walk writes (markdown, wikilink and typed links,+ * meeting attendance, stated relation lines with validity ranges, dated+ * transitions, wanted links, timeline bullets, headers and citations), plus+ * the pages it must leave alone (quarantined, a manual link, another+ * source's duplicate slug) and a withdrawn fact the snapshot overlays.+ *+ * `extractDbState` dumps those tables row by row on natural keys (slugs, not+ * ids; timestamps reduced to presence), so a dump captured before the change+ * pins the state after it. Shared by the PGLite test and the Postgres E2E.+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { runExtract } from '../../src/commands/extract.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../../src/core/cli-force-exit.ts';+import { normalizeLoweredClaim } from '../../src/core/facts/withdrawal-schema.ts';+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './write-attribution.ts';+import { defineNormalizer, sha256 } from './golden.ts';++export const NOTES_SOURCE = 'notes-example';++const person = (i: number) => `people/person-${i}-example`;+const company = (i: number) => `companies/company-${i}-example`;+const day = (i: number) => `2026-0${1 + (i % 9)}-${String(1 + (i % 27)).padStart(2, '0')}`;++const FACTS_FENCE = '<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n'+ + '| 1 | Ships weekly | fact | 1.0 | world | high | 2026-01-01 | | remember | |\n'+ + '| 2 | Hires slowly | fact | 1.0 | world | high | 2026-01-01 | | remember | |\n<!--- gbrain:facts:end -->';++function personBody(i: number, round: number): { compiled_truth: string; timeline: string } {+ const peer = person((i + 1 + round) % 60);+ const lines = [+ `Person ${i} works closely with [Person](${peer}).`,+ `- works_at [[${company(i % 20)}]]${i % 4 === 0 ? ' @effective[2024-01-01,2025-06-01)' : ''}`,+ i % 5 === 0 ? `Mentioned [[people/missing-${i}-example]] and [[companies/missing-${i % 3}-example]] once.` : '',+ i % 7 === 0 ? '```\n[Not a link](people/person-1-example)\n```' : '',+ i % 9 === 0 ? `Inline \`[[${company(1)}]]\` code stays text. <!-- [Hidden](${person(2)}) -->` : '',+ i % 6 === 0 ? `Shipped the launch with the team [Source: call, ${day(i)}]` : '',+ ].filter(Boolean);+ const timeline = [+ `- **${day(i)}** | meeting — Met [[${peer}]]`,+ i % 3 === 0 ? `- **${day(i + 1)}** | update — Left [Company](${company((i + 1) % 20)}) to join [Company](${company((i + 2) % 20)})` : '',+ i % 8 === 0 ? `- **${day(i + 2)}** | note — Started advises [[${company((i + 3) % 20)}]]` : '',+ round > 0 && i % 2 === 0 ? `- **${day(i + 3)}** | note — Second round entry ${i}` : '',+ ].filter(Boolean).join('\n');+ return { compiled_truth: lines.join('\n\n'), timeline };+}++async function put(engine: BrainEngine, slug: string, type: string, body: { compiled_truth: string; timeline: string },+ frontmatter: Record<string, unknown> = {}, sourceId = 'default') {+ await engine.putPage(slug, { type, title: slug.split('/').pop()!, ...body, frontmatter }, { sourceId });+}++/** Writes the fixture; `round` 1 edits a subset so a second extract replaces and retracts rows. */+export async function seedExtractFixture(engine: BrainEngine, round = 0): Promise<void> {+ if (round === 0) {+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES ($1,$1,'{"federated":true}'::jsonb) ON CONFLICT (id) DO NOTHING`, [NOTES_SOURCE]);+ for (let k = 0; k < 20; k++) {+ await put(engine, company(k), 'company', { compiled_truth: `[Person](${person(k)}) is the CEO of [Company](${company(k)}).`+ + (k === 3 ? `\n\n${FACTS_FENCE}` : ''), timeline: '' });+ }+ }+ for (let i = 0; i < 60; i++) {+ if (round > 0 && i % 4 !== 1) continue;+ await put(engine, person(i), 'person', personBody(i, round));+ }+ for (let m = 0; m < 20; m++) {+ if (round > 0 && m % 5 !== 0) continue;+ const attendees = [person(m), person((m + 7 + round) % 60)].map(p => `[Attendee](${p})`).join(', ');+ await put(engine, `meetings/meeting-${m}-example`, 'meeting', { compiled_truth: `Attendees: ${attendees}.\n\n### ${day(m)} — Kickoff ${m}\nDiscussed the plan.`, timeline: '' });+ }+ for (let n = 0; n < 110; n++) {+ if (round > 0 && n % 10 !== 0) continue;+ const quarantine = n === 13 ? { quarantine: { reason: 'synthetic' } } : {};+ await put(engine, `notes/note-${n}-example`, 'note', {+ compiled_truth: `Note ${n} about [[${person(n % 60)}]] and [[${company(n % 20)}]]${round > 0 ? '' : ` and [Person](${person((n + 5) % 60)})`}.`+ + (n % 4 === 0 ? `\n\nWe agreed on terms [Source: email, ${day(n)}]` : ''),+ timeline: n % 3 === 0 ? `- **${day(n)}** | email — Note entry ${n}${round > 0 ? ' revised' : ''}` : '',+ }, quarantine);+ }+ if (round === 0) {+ for (let j = 0; j < 15; j++) {+ await put(engine, j === 0 ? person(0) : `notes/notes-side-${j}-example`, j === 0 ? 'person' : 'note',+ { compiled_truth: `Side ${j} cites [[default:${person(j)}]] and [[${j === 0 ? 'notes/notes-side-1-example' : person(0)}]].`, timeline: `- **${day(j)}** | side — Side entry ${j}` },+ {}, NOTES_SOURCE);+ }+ await engine.addLink(person(1), company(5), 'Manual evidence', 'mentions', 'manual');+ await engine.addTag(person(11), 'founder');+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES ('default','world',$1)`,+ [createHash('sha256').update(normalizeLoweredClaim('ships weekly')).digest('hex')]);+ }+}++const TABLES: Record<string, string> = {+ links: `SELECT jsonb_build_array(f.source_id, f.slug, t.source_id, t.slug, l.link_type, l.link_source, l.link_kind, o.source_id, o.slug,+ l.context, l.origin_field, l.assertion_tense)::text AS r+ FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id LEFT JOIN pages o ON o.id=l.origin_page_id`,+ timeline_entries: `SELECT jsonb_build_array(p.source_id, p.slug, t.date::text, t.source, t.summary, t.detail, e.slug)::text AS r+ FROM timeline_entries t JOIN pages p ON p.id=t.page_id LEFT JOIN pages e ON e.id=t.event_page_id`,+ link_transitions: `SELECT jsonb_build_array(lt.source_id, f.slug, t.slug, lt.link_type, lt.kind, lt.occurred_on::text, lt.date_precision, lt.producer, o.slug, lt.line_hash)::text AS r+ FROM link_transitions lt JOIN pages f ON f.id=lt.from_page_id JOIN pages t ON t.id=lt.to_page_id LEFT JOIN pages o ON o.id=lt.origin_page_id`,+ link_relationships: `SELECT jsonb_build_array(lr.source_id, f.slug, t.slug, lr.link_type, lr.scope, lr.semantics, lr.valid_ranges::text, lr.status_now,+ lr.first_start::text, lr.last_start::text, lr.last_end::text, lr.undated_present, lr.undated_past, lr.disputed, lr.retired_at IS NULL, lr.evidence_hash)::text AS r+ FROM link_relationships lr JOIN pages f ON f.id=lr.from_page_id JOIN pages t ON t.id=lr.to_page_id`,+ wanted_links: `SELECT jsonb_build_array(o.source_id, o.slug, w.source_id, w.producer, w.ref_kind, w.target_source_id, w.target_ref, w.link_type, w.context,+ w.checked_at = '-infinity'::timestamptz)::text AS r FROM wanted_links w JOIN pages o ON o.id=w.origin_page_id`,+ pages: `SELECT jsonb_build_array(source_id, slug, type, content_hash, links_extracted_at IS NOT NULL, links_attendance_blocked_revision IS NOT NULL,+ deleted_at IS NULL)::text AS r FROM pages`,+ tags: `SELECT jsonb_build_array(p.source_id, p.slug, t.tag)::text AS r FROM tags t JOIN pages p ON p.id=t.page_id`,+ facts: `SELECT jsonb_build_array(source_id, fact, kind, visibility)::text AS r FROM facts`,+ extract_requests: `SELECT jsonb_build_array(operation, state, source_id, slug, error_code)::text AS r FROM persistence_requests+ WHERE operation <> 'put_page' AND operation <> 'put_skill'`,+};++/** Every row the walk writes or must keep, on natural keys, sorted by code unit (collation-independent). */+export async function extractDbState(engine: BrainEngine): Promise<Record<string, string[]>> {+ const state: Record<string, string[]> = {};+ for (const [table, sql] of Object.entries(TABLES)) {+ state[table] = (await engine.executeRaw<{ r: string }>(sql)).map(row => row.r).sort();+ }+ return state;+}++/** `gbrain extract <args>` in process: the parsed --json result and the exit verdict. */+export async function runExtractJson(engine: BrainEngine, args: string[]): Promise<{ result: unknown; exitCode: number }> {+ const out: string[] = [];+ const log = console.log;+ const error = console.error;+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };+ console.error = () => {};+ const priorExitCode = process.exitCode;+ _resetCliExitVerdictForTests();+ try {+ await runExtract(engine, args);+ } finally {+ console.log = log;+ console.error = error;+ process.exitCode = priorExitCode ?? 0;+ }+ const exitCode = currentExitCode();+ _resetCliExitVerdictForTests();+ const text = out.join('\n');+ return { result: JSON.parse(text.slice(text.indexOf('{'))), exitCode };+}++export async function unmanagedRounds(engine: BrainEngine) {+ await seedExtractFixture(engine);+ const first = await runExtractJson(engine, ['all', '--source', 'db', '--json']);+ const afterFirst = await extractDbState(engine);+ await seedExtractFixture(engine, 1);+ const second = await runExtractJson(engine, ['all', '--source', 'db', '--json']);+ return { first, afterFirst, second, afterSecond: await extractDbState(engine) };+}++/** Every 10th seeded page lost its stored timeline rows, so the coordinator writes them back. */+export async function managedRounds(engine: BrainEngine) {+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(`DELETE FROM timeline_entries+ WHERE page_id IN (SELECT id FROM pages WHERE source_id = 'default' AND id % 10 = 0)`), TEST_WRITE_ATTRIBUTION));+ const first = await runExtractJson(engine, ['all', '--source', 'db', '--json']);+ const afterFirst = await extractDbState(engine);+ const second = await runExtractJson(engine, ['all', '--source', 'db', '--json']);+ return { first, afterFirst, second, afterSecond: await extractDbState(engine) };+}++/** Make every batch transaction fail, so each batch is replayed page by page. */+export function failEveryBatch(engine: BrainEngine) {+ (engine as { replaceDerivedLinksBatch: unknown }).replaceDerivedLinksBatch = async () => { throw new Error('synthetic batch failure'); };+}++type Rounds = Awaited<ReturnType<typeof unmanagedRounds>>;+/** Each table as its row count and the sha256 of its sorted rows: equal digests are equal rows. */+export const EXTRACT_ROWS = defineNormalizer<Rounds>('extract-db-batch-rows-v1', rounds => ({ ...rounds,+ afterFirst: digests(rounds.afterFirst), afterSecond: digests(rounds.afterSecond) }));+const digests = (state: Record<string, string[]>) =>+ Object.fromEntries(Object.entries(state).map(([table, rows]) => [table, { rows: rows.length, sha256: sha256(rows.join('\n')) }]));diff --git a/test/helpers/page-snapshot-batch-cases.ts b/test/helpers/page-snapshot-batch-cases.tsnew file mode 100644index 0000000000..1406b8818a--- /dev/null+++ b/test/helpers/page-snapshot-batch-cases.ts@@ -0,0 +1,68 @@+/** Shared cases for readPageSnapshotsBatch (PGLite unit test and Postgres E2E). */+import { createHash } from 'node:crypto';+import { expect } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { normalizeLoweredClaim } from '../../src/core/facts/withdrawal-schema.ts';+import { pageSnapshotKey, readPageSnapshotsBatch } from '../../src/core/page-snapshot-batch.ts';++const OTHER = 'snapshot-batch-example';+const FENCE = '<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n'+ + '| 1 | Ships Weekly | fact | 1.0 | world | high | 2026-01-01 | | remember | |\n'+ + '| 2 | Hires slowly | fact | 1.0 | world | high | 2026-01-01 | | remember | |\n<!--- gbrain:facts:end -->';++async function seed(engine: BrainEngine) {+ if ((await engine.executeRaw('SELECT 1 FROM sources WHERE id=$1', [OTHER])).length) return;+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [OTHER]);+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice', compiled_truth: `Alice.\n\n${FENCE}`, timeline: '- **2026-01-02** | call — Met' });+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice elsewhere', compiled_truth: `Other Alice.\n\n${FENCE}`, timeline: '' }, { sourceId: OTHER });+ await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme', compiled_truth: 'Acme Corp\nSecond line', timeline: 'T' });+ await engine.putPage('notes/deleted-example', { type: 'note', title: 'Deleted', compiled_truth: 'Gone.', timeline: '' });+ await engine.addTag('companies/acme-example', 'b-tag');+ await engine.addTag('companies/acme-example', 'a-tag');+ await engine.softDeletePage('notes/deleted-example');+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES ('default','world',$1)`,+ [createHash('sha256').update(normalizeLoweredClaim('ships weekly')).digest('hex')]);+}++const REFS = [+ { slug: 'people/alice-example', sourceId: 'default' },+ { slug: 'companies/acme-example', sourceId: 'default' },+ { slug: 'people/alice-example', sourceId: OTHER },+ { slug: 'notes/deleted-example', sourceId: 'default' },+ { slug: 'notes/missing-example', sourceId: 'default' },+ { slug: 'companies/acme-example', sourceId: OTHER },+];++export async function pageSnapshotBatchMatchesPerPageReads(engine: BrainEngine) {+ await seed(engine);+ const { snapshots, covered } = await readPageSnapshotsBatch(engine, REFS);+ expect(covered).toBe(REFS.length);+ for (const ref of REFS) {+ const single = await engine.readPageSnapshot(ref.slug, { sourceId: ref.sourceId });+ expect(snapshots.get(pageSnapshotKey(ref.sourceId, ref.slug)) ?? null).toEqual(single);+ }+ expect([...snapshots.keys()].sort()).toEqual([pageSnapshotKey('default', 'companies/acme-example'),+ pageSnapshotKey('default', 'people/alice-example'), pageSnapshotKey(OTHER, 'people/alice-example')].sort());+ const alice = snapshots.get(pageSnapshotKey('default', 'people/alice-example'))!;+ expect(alice.withdrawals).toHaveLength(1);+ const [stored] = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE source_id='default' AND slug='people/alice-example'`);+ expect(alice.page.compiled_truth).not.toBe(stored!.compiled_truth);+ expect(snapshots.get(pageSnapshotKey(OTHER, 'people/alice-example'))!.withdrawals).toEqual([]);+ expect(snapshots.get(pageSnapshotKey('default', 'companies/acme-example'))!.tags).toEqual(['a-tag', 'b-tag']);+}++export async function pageSnapshotBatchRespectsByteBudget(engine: BrainEngine) {+ await seed(engine);+ const live = [REFS[0]!, REFS[1]!, REFS[2]!];+ const bytes = (await engine.executeRaw<{ n: number }>(`SELECT octet_length(compiled_truth) + octet_length(timeline) AS n FROM pages+ WHERE source_id='default' AND slug='people/alice-example'`))[0]!.n;+ expect((await readPageSnapshotsBatch(engine, live, { maxBytes: 1 })).covered).toBe(1);+ const two = await readPageSnapshotsBatch(engine, live, { maxBytes: Number(bytes) + 1 });+ expect(two.covered).toBe(2);+ expect([...two.snapshots.keys()]).toEqual([pageSnapshotKey('default', 'people/alice-example'), pageSnapshotKey('default', 'companies/acme-example')]);+ const missingFirst = await readPageSnapshotsBatch(engine, [REFS[4]!, REFS[3]!, REFS[1]!], { maxBytes: 1 });+ expect(missingFirst.covered).toBe(3);+ expect([...missingFirst.snapshots.keys()]).toEqual([pageSnapshotKey('default', 'companies/acme-example')]);+ expect((await readPageSnapshotsBatch(engine, [])).covered).toBe(0);+}diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.tsindex c26ae02cce..11ec5f4b48 100644--- a/test/helpers/postgres-engine-sql-cases.ts+++ b/test/helpers/postgres-engine-sql-cases.ts@@ -90,7 +90,7 @@ export const DOMAIN_OF: Record<string, string> = {'countStalePagesForExtraction': 'pages', 'listStalePagesForExtraction': 'pages', 'markPagesExtractedBatch': 'pages','markPagesAttendanceBlocked': 'pages',// links- 'addLink': 'links', 'addLinksBatch': 'links', 'replaceDerivedLinks': 'links', 'removeLinksByPagesAndSource': 'links',+ 'addLink': 'links', 'addLinksBatch': 'links', 'replaceDerivedLinks': 'links', 'replaceDerivedLinksBatch': 'links', 'removeLinksByPagesAndSource': 'links','removeLink': 'links', 'getLinks': 'links', 'getBacklinks': 'links', 'listLinkSources': 'links','traverseGraph': 'links', 'traversePaths': 'links', 'traversePathsDetailed': 'links', 'findOrphanPages': 'links','rewriteLinks': OOS.stub,@@ -394,6 +394,11 @@ export const SQL_CASES: SqlCase[] = [...variants('replaceDerivedLinks', [['default', (e) => e.replaceDerivedLinks({ slug: SLUG, sourceId: SRC, expectedRevision: REVISION, sourceIncarnation: INCARNATION }, [{ from_slug: SLUG, to_slug: SLUG2, link_type: 'works_at' }]), [[/INSERT INTO links \(from_page_id, to_page_id, link_type, context, link_source, link_kind/, [{ one: 1 }]]]],]),+ ...variants('replaceDerivedLinksBatch', [+ ['default', (e) => e.replaceDerivedLinksBatch([{ origin: { slug: SLUG, sourceId: SRC, expectedRevision: REVISION, sourceIncarnation: INCARNATION }, links: [{ from_slug: SLUG, to_slug: SLUG2, link_type: 'works_at' }] }]), [+ [/AS batch_prior_bytes/, [{ ...PAGE_ROW, batch_n: 1, batch_slug: SLUG, batch_source_id: SRC, source_incarnation: INCARNATION, snapshot_tags: [], snapshot_withdrawals: [], fingerprint_body: null, fingerprint_timeline: null }]],+ [/INSERT INTO links \(from_page_id, to_page_id, link_type, context, link_source, link_kind/, [{ one: 1 }]]]],+ ]),...variants('removeLinksByPagesAndSource', [['default', (e) => e.removeLinksByPagesAndSource([{ slug: SLUG, source_id: SRC }], { linkSource: 'markdown' })],]),diff --git a/test/page-snapshot-batch.test.ts b/test/page-snapshot-batch.test.tsnew file mode 100644index 0000000000..c27940e27e--- /dev/null+++ b/test/page-snapshot-batch.test.ts@@ -0,0 +1,21 @@+/**+ * GBRA-69: readPageSnapshotsBatch returns, for exact (slug, source) refs, the+ * snapshot readPageSnapshot returns for each (tags, revision, incarnation,+ * withdrawals and the withdrawal overlay), and covers the longest prefix of+ * refs whose bodies fit the byte budget. Postgres arm: test/e2e/page-snapshot-batch.test.ts.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { pageSnapshotBatchMatchesPerPageReads, pageSnapshotBatchRespectsByteBudget } from './helpers/page-snapshot-batch-cases.ts';++let engine: BrainEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await engine?.disconnect(); });++test('batched snapshots equal the per-page reads, missing and deleted refs included', () => pageSnapshotBatchMatchesPerPageReads(engine));+test('a batch covers the longest prefix that fits the byte budget, never less than one ref', () => pageSnapshotBatchRespectsByteBudget(engine));