Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

large pages PR 2 lane 2e2: conversation facts over a segmented page through ranged reads

garrytane9c2a6e908ca
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index de20f916a6..3cc24f9e37 100644
--- a/docs/architecture/key-files/commands-3.md
+++ b/docs/architecture/key-files/commands-3.md
@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source through `resolveRestoreTarget` (`src/core/restore-target.ts`, shared with `gbrain storage status`) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Wave B PR 2: a segmented page streams (`segmentedExportMarkdown`: serializeMarkdown's head, the trusted stored body through `readBodyRange` with the same withdrawal overlay, the timeline separator before the first timeline byte) into its own stage file (`ExportStage.addStream`, a full collection per 1 MiB read), published with the native path API; its payload estimate is `body_bytes`, the per-page limit is `exportPayloadLimit(pages.max_bytes)` (32 MiB while segmented storage is off), a streamed page adds 1 ms per KiB to the 10-minute snapshot deadline and stage files must leave 512 MiB free on the staging filesystem (`test/e2e/large-pages-export.test.ts`: inline vs segmented same bytes at 2 and 20 MiB, export(import(F)) == F, a gated 128 MiB memory arm). Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.
-- `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 bounded windows via `src/core/facts/conversation-windows.ts` (#6267: eligibility per 30-min gap group of ≥2 messages decided before windowing; windows close at 30 messages or when the rendered text with its header would exceed 6,500 chars; oversized turns split at sentence boundaries with the speaker prefix repeated; a trailing single reply of an eligible group is its own window, never glued across a gap; nothing is clipped and an unrepresentable header fails the page before prior-fact cleanup; 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` = `CONVERSATION_BODY_MAX_BYTES` in `conversation-parser/body.ts`, `PAGE_MAX_BYTES` + 1 MiB = 25 MiB, measured on the parser input; `readConversationBodyForParsing` stats a `raw_transcript` sidecar and throws `ConversationBodyTooLargeError` over the cap before any read, the snapshot carries `oversizedSidecarBytes`, and a size skip writes a `skipped_too_large` receipt to `page_extraction_state` (doctor `extraction_input_truncated`) that a later run under the cap clears; test `test/conversation-facts-oversized-sidecar.test.ts`); **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-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 bounded windows via `src/core/facts/conversation-windows.ts` (#6267: eligibility per 30-min gap group of ≥2 messages decided before windowing; windows close at 30 messages or when the rendered text with its header would exceed 6,500 chars; oversized turns split at sentence boundaries with the speaker prefix repeated; a trailing single reply of an eligible group is its own window, never glued across a gap; nothing is clipped and an unrepresentable header fails the page before prior-fact cleanup; 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` = `CONVERSATION_BODY_MAX_BYTES` in `conversation-parser/body.ts`, `PAGE_MAX_BYTES` + 1 MiB = 25 MiB, measured on the parser input; `readConversationBodyForParsing` stats a `raw_transcript` sidecar and throws `ConversationBodyTooLargeError` over the cap before any read, the snapshot carries `oversizedSidecarBytes`, and a size skip writes a `skipped_too_large` receipt to `page_extraction_state` (doctor `extraction_input_truncated`) that a later run under the cap clears; test `test/conversation-facts-oversized-sidecar.test.ts`; a segmented page is read through ranged reads, and one over `CONVERSATION_WINDOW_BYTES` is extracted from its newest window with the window's day-header date and a `tail_window` receipt (page-body/segment-conversation.ts; test `test/large-pages/segmented-conversation-facts.test.ts`)); **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); `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`.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 73799729a5..754007ba72 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -7,7 +7,7 @@ src/cli/main.ts 3009 ratchet +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE
src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)
src/commands/doctor.ts 686 ratchet +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +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.ts
src/commands/embed.ts 2304 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); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
-src/commands/extract-conversation-facts.ts 2087 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); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087
+src/commands/extract-conversation-facts.ts 2094 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); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts)
src/commands/extract.ts 2637 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); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline
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 codes
src/commands/serve-http.ts 932 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); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts)
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index c1d5b13bb7..cb7b18b8c8 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -372,7 +372,8 @@ import {
parseConversation,
type ParseConversationOpts as OrchestratorParseOpts,
} from '../core/conversation-parser/parse.ts';
-import { ConversationBodyTooLargeError, CONVERSATION_BODY_MAX_BYTES, readConversationBodyForParsing } from '../core/conversation-parser/body.ts';
+import { ConversationBodyTooLargeError, CONVERSATION_BODY_MAX_BYTES, readConversationInput } from '../core/conversation-parser/body.ts';
+import { CONVERSATION_WINDOW_BYTES, type ConversationWindow } from '../core/page-body/segment-conversation.ts';
import { setExtractionReceipt } from '../core/extraction-watermark.ts';
import { conversationSkip } from '../core/facts/conversation-skip.ts';
import { runLlmFallback } from '../core/conversation-parser/llm-fallback.ts';
@@ -539,8 +540,11 @@ async function skippedForSize(state: ExtractCoreState, snapshot: ConversationPag
process.stderr.write(`[extract-conversation-facts] SKIP ${snapshot.page.slug}: ${origin === 'sidecar' ? 'raw_transcript sidecar ' : ''}`
+ `${(bytes / 1024 / 1024).toFixed(1)}MB exceeds ${MAX_PAGE_BODY_BYTES / 1024 / 1024}MB cap\n`);
}
+ const window = snapshot.window;
if (!state.dryRun) await setExtractionReceipt(state.engine, snapshot.page.id, 'conversation_facts', over
- ? { kind: 'skipped_too_large', pipeline: 'conversation_facts', processed_chars: 0, total_bytes: bytes, cap_bytes: MAX_PAGE_BODY_BYTES, origin } : null);
+ ? { kind: 'skipped_too_large', pipeline: 'conversation_facts', processed_chars: 0, total_bytes: bytes, cap_bytes: MAX_PAGE_BODY_BYTES, origin }
+ : window ? { kind: 'tail_window', pipeline: 'conversation_facts', processed_chars: snapshot.body.length, total_bytes: window.totalBytes,
+ cap_bytes: CONVERSATION_WINDOW_BYTES, origin: 'page' } : null);
return over;
}
@@ -717,6 +721,8 @@ export type DurableExtractionOutcome = 'complete' | 'non_extractable';
interface ConversationPageSnapshot {
page: Page;
body: string;
+ /** A segmented page over the window cap: `body` is its newest window. */
+ window?: ConversationWindow;
versionToken: string;
/** The `raw_transcript` sidecar was over the cap and not read; `body` is empty. */
oversizedSidecarBytes?: number;
@@ -769,8 +775,8 @@ async function preparePageSnapshot(
page: Page,
): Promise<ConversationPageSnapshot> {
try {
- const body = await readConversationBodyForParsing(engine, page);
- return { page, body, versionToken: snapshotVersionToken(page, body) };
+ const { body, window } = await readConversationInput(engine, page);
+ return { page, body, ...(window ? { window } : {}), versionToken: snapshotVersionToken(page, body) };
} catch (error) {
if (!(error instanceof ConversationBodyTooLargeError)) throw error;
return { page, body: '', versionToken: `sidecar-oversized-${error.bytes}-${error.mtimeMs}`, oversizedSidecarBytes: error.bytes };
@@ -879,7 +885,8 @@ async function processPage(
// `parseConversationMessages(body)` shape only saw the body, which
// meant Telegram-bracket pages with frontmatter dates landed at
// 1970-01-01. Now they pick up the correct date.
- const parseResult = parseConversation(body, { page });
+ const fallbackDate = snapshot.window?.fallbackDate ?? undefined;
+ const parseResult = parseConversation(body, { page, ...(fallbackDate ? { fallbackDate } : {}) });
let messages = parseResult.messages;
if (parseResult.timezone_warning) {
process.stderr.write(parseResult.timezone_warning + '\n');
@@ -926,7 +933,7 @@ async function processPage(
body,
engine: state.engine,
signal: state.signal,
- fallbackDate: deriveDateContext({ page }).fallbackDate,
+ fallbackDate: deriveDateContext({ page, ...(fallbackDate ? { fallbackDate } : {}) }).fallbackDate,
propagateError: (error) =>
error instanceof BudgetExhausted ||
(state.signal?.aborted === true && isAbortError(error)),
diff --git a/src/core/conversation-parser/body.ts b/src/core/conversation-parser/body.ts
index 8a7a874b9b..9f686301ca 100644
--- a/src/core/conversation-parser/body.ts
+++ b/src/core/conversation-parser/body.ts
@@ -4,6 +4,8 @@ import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
import { loadSourceRow } from '../contextual-retrieval-service.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { readSegmentedConversationInput, type SegmentedConversationInput } from '../page-body/segment-conversation.ts';
/**
* The largest conversation parser input (UTF-8 bytes): the page ceiling plus
@@ -125,6 +127,17 @@ export async function readConversationBodyForParsing(
engine: BrainEngine,
page: Page,
): Promise<string> {
+ return (await readConversationInput(engine, page)).body;
+}
+
+/**
+ * readConversationBodyForParsing with the window it read: a segmented page's summary body is read through ranged
+ * reads, and one over CONVERSATION_WINDOW_BYTES is its newest window (page-body/segment-conversation.ts).
+ */
+export async function readConversationInput(
+ engine: BrainEngine,
+ page: Page,
+): Promise<SegmentedConversationInput> {
const rawTranscript = extractRawTranscriptPath(page);
if (rawTranscript) {
const resolved = await resolveTranscriptPath(engine, page, rawTranscript);
@@ -132,7 +145,7 @@ export async function readConversationBodyForParsing(
const { size, mtimeMs } = statSync(resolved);
if (size > CONVERSATION_BODY_MAX_BYTES) throw new ConversationBodyTooLargeError(size, mtimeMs);
const rawBody = readFileSync(resolved, 'utf8').trim();
- if (rawBody.length > 0) return rawBody;
+ if (rawBody.length > 0) return { body: rawBody };
}
if (!resolved) {
// Refusal is loud but class-only: never echo the attempted path
@@ -142,5 +155,5 @@ export async function readConversationBodyForParsing(
);
}
}
- return readSummaryBody(page);
+ return isSegmentedPage(page) ? readSegmentedConversationInput(engine, page) : { body: readSummaryBody(page) };
}
diff --git a/src/core/page-body/segment-conversation.ts b/src/core/page-body/segment-conversation.ts
new file mode 100644
index 0000000000..952655b07a
--- /dev/null
+++ b/src/core/page-body/segment-conversation.ts
@@ -0,0 +1,78 @@
+/**
+ * Segmented page storage (Wave B, spec 8, PR 2 full-pass mode): the
+ * conversation parser input of a segmented page, through ranged reads.
+ *
+ * The input is readSummaryBody's join of the trusted stored body
+ * (`${compiled_truth}\n\n${timeline}`, either side alone when the other is
+ * empty), as readPageSnapshot gives it for an inline page. A body within
+ * CONVERSATION_WINDOW_BYTES is read whole, exactly as an inline page of that
+ * size. A larger body, which Wave A could only skip, is read as its newest
+ * window: the last whole segments (never starting inside a run of forced
+ * cuts) that fit the window, so the extraction covers the newest messages,
+ * as Wave A's tail windows do for appended text. Conversation segments cut at
+ * message lines and day headers, and the window's first segment carries the
+ * day-header date in its entry state, which the parse takes as its fallback
+ * date. Reads at most the window's bytes.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
+import { readEntryState } from './entry-state.ts';
+import { openSegmentedBody, readBodyRange } from './read-range.ts';
+import { readGarbageCollector, segmentedPassWork } from './segment-blocks.ts';
+import type { BodyRegion } from './types.ts';
+
+/** The largest parser input held as one string: Wave A's single-string ceiling. */
+export const CONVERSATION_WINDOW_BYTES = PAGE_MAX_BYTES;
+
+/** A parser input that is the newest window of a larger body. */
+export interface ConversationWindow {
+ /** UTF-8 bytes of the whole stored body (truth plus timeline). */
+ totalBytes: number;
+ /** The day-header date in force where the window starts, or null. */
+ fallbackDate: string | null;
+}
+
+export interface SegmentedConversationInput { body: string; window?: ConversationWindow }
+
+/** The parser input of a segmented page: its whole summary body within `cap` bytes, else its newest window. */
+export async function readSegmentedConversationInput(engine: BrainEngine, page: { id: number },
+ cap = CONVERSATION_WINDOW_BYTES): Promise<SegmentedConversationInput> {
+ const body = await openSegmentedBody(engine, { pageId: Number(page.id) });
+ const rows = [...body.rows.filter(row => row.region === 'truth'), ...body.rows.filter(row => row.region === 'timeline')];
+ let first = 0;
+ let window: ConversationWindow | undefined;
+ if (body.bodyBytes > cap) {
+ const forced = new Set((await engine.executeRaw<{ seq: number }>(`SELECT seq FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULL
+ AND gen_from<=$2 AND (gen_to IS NULL OR gen_to>$2) AND cut_kind='forced'`, [body.pageId, body.generation])).map(row => Number(row.seq)));
+ let bytes = 0;
+ first = rows.length;
+ for (let i = rows.length - 1; i >= 0; i--) {
+ bytes += rows[i]!.byteLen;
+ if (bytes > cap) break;
+ const startsFresh = i === 0 || rows[i - 1]!.region !== rows[i]!.region || !forced.has(rows[i - 1]!.seq);
+ if (startsFresh) first = i;
+ }
+ const [entry] = first < rows.length ? await engine.executeRaw<{ entry_state: unknown }>(`SELECT entry_state FROM page_body_manifest
+ WHERE page_id=$1 AND seq=$2 AND staging_id IS NULL AND gen_from<=$3 AND (gen_to IS NULL OR gen_to>$3)`, [body.pageId, rows[first]!.seq, body.generation]) : [];
+ const state = readEntryState(typeof entry?.entry_state === 'string' ? JSON.parse(entry.entry_state) : entry?.entry_state);
+ window = { totalBytes: body.bodyBytes, fallbackDate: state?.conversation.fallbackDate ?? null };
+ }
+ const collect = readGarbageCollector();
+ const regionText = async (region: BodyRegion): Promise<string> => {
+ const own = rows.slice(first).filter(row => row.region === region);
+ if (!own.length) return '';
+ const parts: Buffer[] = [];
+ const start = own[0]!.byteStart;
+ const end = own[own.length - 1]!.byteStart + own[own.length - 1]!.byteLen;
+ for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'stored', start, end, audience: 'trusted', region, body })) {
+ parts.push(piece.bytes);
+ segmentedPassWork.bytes += piece.bytes.length;
+ collect(piece.bytes.length);
+ }
+ return Buffer.concat(parts).toString('utf8');
+ };
+ const truth = await regionText('truth');
+ const timeline = await regionText('timeline');
+ const text = !truth ? timeline : !timeline ? truth : `${truth}\n\n${timeline}`;
+ return window ? { body: text, window } : { body: text };
+}
diff --git a/test/large-pages/segmented-conversation-facts.test.ts b/test/large-pages/segmented-conversation-facts.test.ts
new file mode 100644
index 0000000000..2d985b82f5
--- /dev/null
+++ b/test/large-pages/segmented-conversation-facts.test.ts
@@ -0,0 +1,191 @@
+/**
+ * Wave B PR 2 lane 2e2 (spec 8, full-pass mode): conversation facts read a
+ * segmented page through ranged reads.
+ *
+ * 1. Protects:
+ * - a segmented conversation within the window cap gives the parser the
+ * inline page's input, and extract-conversation-facts hands the
+ * extractor the same windows;
+ * - over the cap, readSegmentedConversationInput reads only the newest
+ * whole segments that fit, the window is the suffix of the summary body,
+ * it carries the day-header date in force there, and its parse is the
+ * suffix of the whole body's parse (the same speakers, texts and times);
+ * - a page over the single-string ceiling is extracted from its newest
+ * window with a `tail_window` receipt instead of skipped, reading at most
+ * the window's bytes.
+ * 2. Fails when: a segmented page reads its throwing body getters, the window
+ * is not the body's suffix or starts inside a forced run, its date context
+ * is lost, or a read exceeds the window.
+ * 3. Why existing coverage misses it: conversation-facts tests use inline pages.
+ * Seams: `segmentedPassWork.bytes` counts bytes read.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent, importFromFile } from '../../src/core/import-file.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { runExtractConversationFactsCore } from '../../src/commands/extract-conversation-facts.ts';
+import { readConversationInput, readSummaryBody } from '../../src/core/conversation-parser/body.ts';
+import { parseConversation } from '../../src/core/conversation-parser/parse.ts';
+import { CONVERSATION_WINDOW_BYTES, readSegmentedConversationInput } from '../../src/core/page-body/segment-conversation.ts';
+import { segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';
+import { materializedPage } from '../../src/core/persistence/segmented-apply.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { withoutBody } from '../../src/core/page-body/page-shape.ts';
+import type { Page } from '../../src/core/types.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+let dir: string;
+
+const WORDS = ['launch', 'pricing', 'budget', 'roadmap', 'hiring', 'review', 'contract', 'latency', 'onboarding', 'forecast', 'retention', 'deploy'];
+const SPEAKERS = ['Alice Example', 'Bob Example', 'Carol Example'];
+
+/** A dated chat log of about `bytes`: a `## YYYY-MM-DD` header per day, timed speaker turns under it. */
+function chat(bytes: number, seed: number): string {
+ let s = seed;
+ const next = () => { s = (s * 1103515245 + 12345) & 0x7fffffff; return s / 0x7fffffff; };
+ const parts: string[] = [];
+ let size = 0;
+ for (let day = 0; size < bytes; day++) {
+ const date = new Date(Date.UTC(2025, 0, 1) + day * 86_400_000).toISOString().slice(0, 10);
+ parts.push(`## ${date}\n\n`);
+ for (let turn = 0; turn < 60; turn++) {
+ const words = Array.from({ length: 10 + Math.floor(next() * 40) }, () => WORDS[Math.floor(next() * WORDS.length)]);
+ const line = `**${SPEAKERS[turn % 3]}** (${9 + Math.floor(turn / 6)}:${String((turn * 7) % 60).padStart(2, '0')} AM): ${words.join(' ')}.\n\n`;
+ parts.push(line);
+ size += line.length;
+ }
+ }
+ return parts.join('');
+}
+
+const page = (title: string, body: string) => `---\ntype: conversation\ntitle: ${title}\ndate: 2025-01-01\n---\n\n${body}`;
+const SMALL = chat(1_500_000, 7);
+const TAIL = chat(400_000, 9);
+/** A chat log with a line longer than a segment (a run of forced cuts) shortly before its newest messages. */
+const FORCED = `${chat(600_000, 8)}**Alice Example** (9:00 AM): ${'longline '.repeat(300_000)}\n\n${TAIL}`;
+
+beforeAll(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'segmented-conversation-'));
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ for (const engine of engines) {
+ for (const storage of ['inline', 'segmented'] as const) {
+ await engine.setConfig('pages.segmented_storage', storage === 'segmented' ? 'on' : 'off');
+ expect(await importFromContent(engine, `conversations/chat-${storage}`, page('Chat', SMALL), { sourceId: 'default', noEmbed: true }))
+ .toMatchObject({ status: 'imported' });
+ expect(await importFromContent(engine, `conversations/timeline-${storage}`, page('Timeline', `${SMALL}\n<!-- timeline -->\n\n${chat(300_000, 10)}`),
+ { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
+ }
+ expect(await importFromContent(engine, 'conversations/forced-segmented', page('Forced', FORCED), { sourceId: 'default', noEmbed: true }))
+ .toMatchObject({ status: 'imported' });
+ }
+}, 600_000);
+
+afterAll(async () => {
+ for (const engine of engines) await engine.disconnect();
+ await closePostgres?.();
+ rmSync(dir, { recursive: true, force: true });
+});
+
+const stored = async (engine: BrainEngine, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page;
+
+/** Every extractor input of one run over `slug`, with the run's counts. */
+async function extraction(engine: BrainEngine, slug: string) {
+ await engine.executeRaw('DELETE FROM facts WHERE source_markdown_slug=$1', [slug]);
+ const inputs: unknown[] = [];
+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [slug], sleepMs: 0, force: true,
+ extractor: async input => {
+ inputs.push(Object.fromEntries(Object.entries(input).filter(([, v]) => ['string', 'number', 'boolean'].includes(typeof v))
+ .map(([k, v]) => [k, typeof v === 'string' ? v.replaceAll(slug, 'SLUG') : v])));
+ return [];
+ } });
+ return { inputs, processed: result.pages_processed, segments: result.segments_processed, tooLarge: result.pages_skipped_too_large };
+}
+
+describe('conversation facts over a segmented page (full-pass mode)', () => {
+ test('within the cap: the parser input and the extractor windows match the inline page', async () => {
+ for (const engine of engines) {
+ const seg = await stored(engine, 'conversations/chat-segmented');
+ expect(seg.body_storage).toBe('segmented');
+ const inline = await stored(engine, 'conversations/chat-inline');
+ expect(await readConversationInput(engine, seg)).toEqual({ body: readSummaryBody(inline) });
+ // Truth and timeline joined as readSummaryBody joins them.
+ const withTimeline = await stored(engine, 'conversations/timeline-segmented');
+ expect(withTimeline.body_storage).toBe('segmented');
+ const inlineTimeline = await stored(engine, 'conversations/timeline-inline');
+ expect(inlineTimeline.timeline.length).toBeGreaterThan(100_000);
+ expect(await readConversationInput(engine, withTimeline)).toEqual({ body: readSummaryBody(inlineTimeline) });
+ const a = await extraction(engine, 'conversations/chat-inline');
+ const b = await extraction(engine, 'conversations/chat-segmented');
+ expect(a.inputs.length).toBeGreaterThan(10);
+ expect(b).toEqual(a);
+ }
+ }, 600_000);
+
+ test('over the cap: the newest whole segments that fit, the body suffix, its day date, and the suffix of the parse', async () => {
+ for (const engine of engines) {
+ const seg = await stored(engine, 'conversations/chat-segmented');
+ const whole = readSummaryBody(await materializedPage(engine, seg));
+ const cap = 900_000;
+ const before = segmentedPassWork.bytes;
+ const input = await readSegmentedConversationInput(engine, seg, cap);
+ expect(segmentedPassWork.bytes - before).toBeLessThanOrEqual(cap);
+ expect(Buffer.byteLength(input.body)).toBeGreaterThan(cap / 3);
+ expect(whole.endsWith(input.body)).toBe(true);
+ const head = whole.slice(0, whole.length - input.body.length);
+ const dates = [...head.matchAll(/^## (\d{4}-\d{2}-\d{2})$/gm)].map(m => m[1]);
+ expect(input.window).toEqual({ totalBytes: Number(seg.body_bytes), fallbackDate: dates.at(-1)! });
+ const pageArg = { ...withoutBody(seg), compiled_truth: '', timeline: '' } as Page;
+ const full = parseConversation(whole, { page: pageArg }).messages;
+ const tail = parseConversation(input.body, { page: pageArg, fallbackDate: input.window!.fallbackDate! }).messages;
+ expect(tail.length).toBeGreaterThan(100);
+ const pick = (m: { speaker: string; text: string; timestamp?: unknown }) => ({ speaker: m.speaker, text: m.text, timestamp: m.timestamp });
+ expect(tail.map(pick)).toEqual(full.slice(full.length - tail.length).map(pick));
+ }
+ }, 300_000);
+
+ test('over the cap: a window whose edge falls inside a run of forced cuts starts after the run', async () => {
+ for (const engine of engines) {
+ const seg = await stored(engine, 'conversations/forced-segmented');
+ expect(seg.body_storage).toBe('segmented');
+ const [forced] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL AND cut_kind='forced'`, [seg.id]);
+ expect(forced!.n).toBeGreaterThan(1);
+ const whole = readSummaryBody(await materializedPage(engine, seg));
+ const input = await readSegmentedConversationInput(engine, seg, Buffer.byteLength(TAIL) + 1_500_000);
+ expect(whole.endsWith(input.body)).toBe(true);
+ expect(input.body.length).toBeGreaterThan(TAIL.length / 2);
+ expect(input.body).not.toContain('longline');
+ }
+ }, 300_000);
+
+ test('a page over the single-string ceiling is extracted from its newest window with a tail_window receipt, reading at most the window', async () => {
+ const engine = engines[0]!;
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const file = join(dir, 'huge.md');
+ writeFileSync(file, page('Huge', chat(PAGE_MAX_BYTES + 2 * 1024 * 1024, 11)));
+ expect(await importFromFile(engine, file, 'conversations/huge.md', { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) }))
+ .toMatchObject({ status: 'imported' });
+ const huge = await stored(engine, 'conversations/huge');
+ expect(Number(huge.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);
+ const before = segmentedPassWork.bytes;
+ let calls = 0;
+ let last = '';
+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: ['conversations/huge'], sleepMs: 0, segmentLimit: 2,
+ extractor: async input => { calls++; last = input.turnText; return []; } });
+ expect(result.pages_skipped_too_large).toBe(0);
+ expect(calls).toBeGreaterThan(0);
+ expect(last.length).toBeGreaterThan(0);
+ // One snapshot read of the window, plus the version-token recheck.
+ expect(segmentedPassWork.bytes - before).toBeLessThanOrEqual(2 * CONVERSATION_WINDOW_BYTES);
+ const [receipt] = await engine.executeRaw<{ input_truncated: Record<string, unknown> }>(
+ "SELECT input_truncated FROM page_extraction_state WHERE page_id=$1 AND pipeline='conversation_facts'", [huge.id]);
+ expect(receipt?.input_truncated).toMatchObject({ kind: 'tail_window', pipeline: 'conversation_facts', total_bytes: Number(huge.body_bytes),
+ cap_bytes: CONVERSATION_WINDOW_BYTES, origin: 'page' });
+ }, 900_000);
+});