Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

P2.5 (#6267): bounded conversation windows, every eligible turn reaches the extractor

garrytan89ea8825f62c
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index 0bbc622947..db25349e12 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. 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 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-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=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); `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/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 94d3c5537d..b50b1c8568 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -6,7 +6,8 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; #5430 (W14 P1.9): a valid `frontmatter.timezone` (IANA) converts every built timestamp from that zone's wall clock to UTC through `localToUtcIso(date, hour, minute, tz)` (`Intl` `longOffset`, no dependency, host-TZ independent; a DST fold takes the first occurrence, a gap the pre-transition offset), an invalid zone is reported as `DateContext.invalid_timezone` and the warning names it while timestamps stay UTC (`test/conversation-parser/timezone.test.ts`); also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection; an unreadable fixture returns `skipped` with `fixture_unavailable`, which the autopilot wiring audits, and the wiring reads the embedded fixtures from `cycle/nightly-probe-fixtures.ts`). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true`. The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading is plausible in prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only one role falls back to the ordinary flat-density score. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because one genuine pair embedded deep in an unrelated long document would otherwise pass: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (a short title preamble is tolerated). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).
-- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). It also owns the granular collector aliases (`ALLOWED_TYPE_ALIASES`, `pageTypesForAllowed`) and the one eligibility rule (#5330): `isConversationFactsEligiblePage` and its SQL twin `conversationFactsEligibleSql` admit an allowed concrete type unless frontmatter says `conversation_parseable: false`; with `cycle.conversation_facts_backfill.require_parseable_flag` on, only `type: conversation` or `conversation_parseable: true`. The extractor (slug, batch and enumeration paths), the doctor backlog SQL and its in-process verifier, and the format-coverage sample all use it, so the backlog can drain. Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`. `isFrontmatterFlagOff` (the same off spellings) is shared with `facts/eligibility.ts`.
+- `src/core/facts/conversation-windows.ts` — conversation windowing for `extract-conversation-facts` (#6267, wave 15 P2.5): `splitIntoSegments(messages, { gapMinutes, maxMessages, sinceIso, maxChars, pageTitle })` cuts gap groups, keeps only groups with `MIN_SEGMENT_MESSAGES` (2) original messages, then packs each eligible group into windows bounded by `DEFAULT_SEGMENT_MAX_MESSAGES` (30) and `SEGMENT_TEXT_CHAR_LIMIT` (6,500 rendered chars, header included). Every eligible turn lands in exactly one window; a turn whose own line overflows is split by `splitTurnText` at sentence, then whitespace, then code-point boundaries (never inside a surrogate pair; `pieces.join('')` is the original) with the `speaker (timestamp): ` prefix on every piece; an original singleton stays ineligible; a header that leaves fewer than 32 chars of room throws before any window exists. `renderSegmentForExtraction(pageTitle, segment)` renders the unchanged prompt shape and throws on an over-budget hand-built segment instead of clipping it. Owns the tunables the command re-exports (`DEFAULT_SEGMENT_GAP_MINUTES`, `MAX_PAGE_SEGMENT_GAP_MINUTES`). Pinned by `test/conversation-windows-6267.test.ts`.
+- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). It also owns the granular collector aliases (`ALLOWED_TYPE_ALIASES`, `pageTypesForAllowed`) and the one eligibility rule (#5330): `isConversationFactsEligiblePage` and its SQL twin `conversationFactsEligibleSql` admit an allowed concrete type unless frontmatter says `conversation_parseable: false`; with `cycle.conversation_facts_backfill.require_parseable_flag` on, only `type: conversation` or `conversation_parseable: true`. The extractor (slug, batch and enumeration paths), the doctor backlog SQL and its in-process verifier, and the format-coverage sample all use it, so the backlog can drain. Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`. `isFrontmatterFlagOff` (the same off spellings) is shared with `facts/eligibility.ts`. Since #6267 it also owns the `ConversationMessage`, `ConversationSegment` and `SplitSegmentsOpts` types the windowing module and the command share.
- `src/core/facts/eligibility.ts` — `isFactsBackstopEligible`, the one automatic facts-extraction predicate (page-write outbox, its `body_unchanged` check, sync's post-import hook, the facts-absorb job's re-check). Skips `wiki/agents/`, `dream_generated: true`, `facts_backstop` set off (`opted_out`, #6232: a writer's opt-out for a page whose facts another page carries, such as a meeting's raw transcript; removing it re-offers the page even with an unchanged body), bodies under 80 characters, and types outside `ELIGIBLE_TYPES` unless the slug is under a rescue prefix. Receipt reasons are documented under `facts_backstop_skipped` in the error registry. Pinned by `test/facts-eligibility.test.ts`, `test/persistence-facts-backstop.test.ts`. #6259: a quarantined page (the gate's `quarantine` marker) is ineligible with reason `quarantined`, which the page-write receipt reports as `facts_backstop.skipped` (registered in `facts_backstop_skipped`).
- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Model: `resolveFactsExtractionModel(engine)` returns the model and the setting that chose it (`facts.extraction_model`, then the `resolveModelDetailed` chain on the `reasoning` tier); when nothing chose one and the tier's key-aware default resolved through Anthropic, `FACTS_EXTRACTION_MEASURED_DEFAULTS` substitutes `anthropic:claude-haiku-5-5` (source `measured_default`; the facts-absorb quality gate, gbrain-evals `docs/benchmarks/2026-10-08-facts-extraction-model.md`), and `gbrain models` reports that row through the same resolver. `getFactsExtractionModel` is its string wrapper. Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer can mint `entity_slug='null'` through the resolver's fallback slugify. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. Pinned by `test/facts-extract-structured-output.test.ts`.
diff --git a/docs/operations/conversation-backfill-outcomes.md b/docs/operations/conversation-backfill-outcomes.md
index cf65c57c06..ce6a9f4517 100644
--- a/docs/operations/conversation-backfill-outcomes.md
+++ b/docs/operations/conversation-backfill-outcomes.md
@@ -118,6 +118,25 @@ This distinction is load-bearing. Treating a provider outage as a successful
zero-fact response would make a transient failure durable and permanently hide
the page from later runs.
+### Bounded windows (#6267)
+
+Every eligible turn reaches the extractor. A gap-separated group with at
+least two messages is eligible; inside it, windows close at 30 messages or
+when the rendered text (header included) would exceed 6,500 characters, and
+the next turn opens a new window. A turn that cannot fit alone is split at
+sentence boundaries with its speaker and timestamp repeated on every piece.
+Nothing is clipped: an unrepresentable header fails the page before any
+model call or prior-fact cleanup, and a window rendered over budget is a
+bug that surfaces as a page failure, never as a silent cut. A dense page
+therefore takes more extractor calls than before, under the same cost cap.
+
+Pages stamped complete by an earlier release saw clipped input, and their
+outcome stays valid because the page did not change. To re-extract them
+run `gbrain extract-conversation-facts --source <id> --slug <slug> --force`
+(or `--force` without `--slug` for the whole source, after a `--dry-run`
+preview of the window count); this spends model calls, so it is the
+operator's decision.
+
## Non-extractable authority
A non-extractable marker is written only when all of the following are true:
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 64bee91aa8..248f49d2c2 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -7,7 +7,7 @@ src/cli/main.ts 3007 ratchet moved from src/cli.ts at 3214 (cold start: src/cli.
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 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.ts
src/commands/embed.ts 2236 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)
-src/commands/extract-conversation-facts.ts 2185 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()
+src/commands/extract-conversation-facts.ts 2075 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)
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 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)
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 79d3780049..ff0341a50e 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -132,20 +132,8 @@ export { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE };
// Tunables (exported for tests).
// ---------------------------------------------------------------------------
-/** Maximum gap between adjacent messages before we cut a new segment. */
-export const DEFAULT_SEGMENT_GAP_MINUTES = 30;
-
-/**
- * Hard cap on messages per segment, regardless of timing.
- * Tuned down from PR's 50 → 30 (Eng-v2 T5): combined with the 6500-char
- * SEGMENT_TEXT_CHAR_LIMIT, this keeps headroom under extract.ts's
- * MAX_TURN_TEXT_CHARS = 8000 so tail facts in dense Slack/email
- * segments don't vanish silently.
- */
-export const DEFAULT_SEGMENT_MAX_MESSAGES = 30;
-
-/** Minimum messages required for a segment to be worth extracting. */
-export const MIN_SEGMENT_MESSAGES = 2;
+// Segment gap/cap/budget tunables and the windowing itself live in
+// src/core/facts/conversation-windows.ts (#6267) and are re-exported below.
// #4136 — labels that are common DOCUMENT section headings, never lost
// speakers. Gate the DECLINE only (a miss here is warn-noise on healthy
@@ -169,14 +157,6 @@ function isSpeakerShapedHeadingLabel(label: string): boolean {
/** Delay between extractor calls so we don't burst the chat provider. */
export const DEFAULT_INTER_CALL_SLEEP_MS = 200;
-/**
- * Cap on character length of the rendered segment passed to the extractor.
- * Tuned down from PR's 7500 → 6500 (Eng-v2 T5) to leave headroom for the
- * topical/temporal header (~500 chars typical, up to ~1500 with a long
- * participant list) under extract.ts's MAX_TURN_TEXT_CHARS = 8000.
- */
-export const SEGMENT_TEXT_CHAR_LIMIT = 6500;
-
/**
* Hard cap on per-page body bytes (compiled_truth + timeline). Pages
* exceeding the cap are skipped to bound worker memory (Eng A2). A
@@ -222,19 +202,15 @@ export const PER_SEGMENT_SOURCE_PREFIX = 'cli:extract-conversation-facts';
// Public types.
// ---------------------------------------------------------------------------
-export interface ConversationMessage {
- speaker: string;
- /** ISO 8601 timestamp parsed from the rendered message line. */
- timestamp: string;
- text: string;
-}
-
-export interface ConversationSegment {
- messages: ConversationMessage[];
- startIso: string;
- endIso: string;
- participants: string[];
-}
+export type { ConversationMessage, ConversationSegment, SplitSegmentsOpts } from '../core/facts/conversation-types.ts';
+export {
+ DEFAULT_SEGMENT_GAP_MINUTES, DEFAULT_SEGMENT_MAX_MESSAGES, MIN_SEGMENT_MESSAGES, SEGMENT_TEXT_CHAR_LIMIT,
+ MAX_PAGE_SEGMENT_GAP_MINUTES, splitIntoSegments, renderSegmentForExtraction,
+} from '../core/facts/conversation-windows.ts';
+import type { ConversationMessage } from '../core/facts/conversation-types.ts';
+import {
+ DEFAULT_SEGMENT_GAP_MINUTES, MAX_PAGE_SEGMENT_GAP_MINUTES, splitIntoSegments, renderSegmentForExtraction,
+} from '../core/facts/conversation-windows.ts';
/**
* Core function opts. Strict — `sourceId` is always required (Eng-v2 A1).
@@ -425,19 +401,9 @@ export function parseConversationMessages(
}
// ---------------------------------------------------------------------------
-// Segment splitting.
+// Segment gap override (windowing: src/core/facts/conversation-windows.ts).
// ---------------------------------------------------------------------------
-export interface SplitSegmentsOpts {
- gapMinutes?: number;
- maxMessages?: number;
- /** Drop messages with timestamp <= this ISO before splitting. */
- sinceIso?: string;
-}
-
-/** Upper bound for a page's `conversation_segment_gap_minutes` (one week). */
-export const MAX_PAGE_SEGMENT_GAP_MINUTES = 10_080;
-
/**
* A page's own segmentation gap: frontmatter `conversation_segment_gap_minutes`,
* set by a collector that knows its message cadence. Absent means the global
@@ -458,59 +424,6 @@ export function pageSegmentGapMinutes(page: Pick<Page, 'slug' | 'frontmatter'>):
return undefined;
}
-export function splitIntoSegments(
- messages: ConversationMessage[],
- opts: SplitSegmentsOpts = {},
-): ConversationSegment[] {
- const gapMs = (opts.gapMinutes ?? DEFAULT_SEGMENT_GAP_MINUTES) * 60_000;
- const maxMessages = opts.maxMessages ?? DEFAULT_SEGMENT_MAX_MESSAGES;
- const sinceMs = opts.sinceIso ? Date.parse(opts.sinceIso) : NaN;
-
- const filtered = Number.isFinite(sinceMs)
- ? messages.filter((m) => Date.parse(m.timestamp) > sinceMs)
- : messages.slice();
-
- const out: ConversationSegment[] = [];
- let cur: ConversationMessage[] = [];
- let lastTs: number | null = null;
-
- const flush = () => {
- if (cur.length < MIN_SEGMENT_MESSAGES) {
- cur = [];
- return;
- }
- const seen = new Set<string>();
- const participants: string[] = [];
- for (const m of cur) {
- if (!seen.has(m.speaker)) {
- seen.add(m.speaker);
- participants.push(m.speaker);
- }
- }
- out.push({
- messages: cur,
- startIso: cur[0].timestamp,
- endIso: cur[cur.length - 1].timestamp,
- participants,
- });
- cur = [];
- };
-
- for (const m of filtered) {
- const ts = Date.parse(m.timestamp);
- if (!Number.isFinite(ts)) continue;
- if (lastTs !== null && ts - lastTs > gapMs) flush();
- cur.push(m);
- lastTs = ts;
- if (cur.length >= maxMessages) {
- flush();
- lastTs = null;
- }
- }
- flush();
- return out;
-}
-
// ---------------------------------------------------------------------------
// Segment rendering with topical/temporal header.
// ---------------------------------------------------------------------------
@@ -540,26 +453,6 @@ export function segmentObservationDate(page: Pick<Page, 'slug' | 'frontmatter' |
return explicit ? observationDateFrom(startIso) : resolveObservationDate({ slug: page.slug, frontmatter: page.frontmatter });
}
-export function renderSegmentForExtraction(
- pageTitle: string,
- segment: ConversationSegment,
-): string {
- const header = [
- `Page: ${pageTitle}`,
- `Conversation between ${segment.participants.join(' and ')} from ${segment.startIso} to ${segment.endIso}`,
- '---',
- ].join('\n');
- const body = segment.messages
- .map((m) => `${m.speaker} (${m.timestamp}): ${m.text}`)
- .join('\n');
- const full = `${header}\n${body}`;
- if (full.length <= SEGMENT_TEXT_CHAR_LIMIT) return full;
- // Truncate from the end of the body, keeping the header intact so the
- // extractor still sees the topical anchor.
- const slack = SEGMENT_TEXT_CHAR_LIMIT - header.length - 16;
- return `${header}\n${body.slice(0, Math.max(0, slack))}\n…(truncated)`;
-}
-
// ---------------------------------------------------------------------------
// Fingerprint — sourceId-only (Eng-v2 A3). Widening types config does NOT
// invalidate prior completion state.
@@ -1046,8 +939,8 @@ async function processPage(
// a frontmatter conversation_segment_gap_minutes still wins.
const gapMinutes = pageSegmentGapMinutes(page) ??
(parseResult.matched_pattern_id === 'email-thread-heading' ? MAX_PAGE_SEGMENT_GAP_MINUTES : undefined);
- const allSegments = splitIntoSegments(messages, { gapMinutes });
- const segments = splitIntoSegments(messages, { gapMinutes, sinceIso });
+ const allSegments = splitIntoSegments(messages, { gapMinutes, pageTitle: page.title || page.slug });
+ const segments = splitIntoSegments(messages, { gapMinutes, sinceIso, pageTitle: page.title || page.slug });
if (segments.length === 0) {
state.result.pages_skipped++;
if (!declinedUnrecognizedSpeaker && !skip) {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d739eb8b2c..83f3674f7a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -440,6 +440,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// Fix wave 15 G3 (GBRA-79). `since` is provisional (0.60.176.0); the integrator restamps it at the merge slot.
{ since: '0.60.176.0', text: '`gbrain extract-conversation-facts` now walks a source\'s pages by slug (a keyset) instead of OFFSET over `updated_at`, so a page is listed, extracted and frozen once per run even while other writers touch pages that share one timestamp; a page the run sees twice is counted as `pages_skipped_duplicate_listing` with no second model call. A batch request the writer refused as malformed (`invalid_params`, the shape a page listed twice produced) is no longer a permanent block: its stored entries are resubmitted on the next run with zero model calls, up to 3 failed requests per page version, and one failed request counts once however many times it listed the page. `list_pages` sorted by `updated_desc` (the default) now breaks timestamp ties by slug, source and id, so ties page deterministically; offset paging is still unstable under writes that change `updated_at`.' },
{ since: '0.60.176.0', text: '`gbrain projections drain` (and the migration drain) no longer loops on one queue row whose revision does not match its page: the row is re-keyed to the page\'s current revision and rebuilt in the same pass, or deleted when the page is already projected or belongs to a dead source incarnation, always as a compare-and-set on the exact row listed so a newer queued row survives. A page whose content changes while it is being rebuilt appears once under `failed` with a `revision_conflict:` reason and stays queued for the next run; `--json` may now list such rows where the command used to hang.' },
+ { since: '0.60.176.0', text: '`gbrain extract-conversation-facts` now sends every eligible turn of a conversation page to the extractor in bounded windows: a window closes at 30 messages or when its rendered text, header included, would exceed 6,500 characters, and the next turn opens a new window instead of being cut off; a turn too long for one window is split at sentence boundaries with its speaker and timestamp repeated; the 31st reply of a 31-turn group is extracted as its own window instead of being dropped. A dense page therefore takes more extractor calls than before, under the same cost cap. Pages already stamped complete from clipped input are not re-extracted automatically; to recompute them run `gbrain extract-conversation-facts --source <id> --force` (narrowed to one page with its slug option, or the whole source after a `--dry-run` preview of the window count), which spends model calls.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index c29736007e..7886cae6b1 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -59,7 +59,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
- 'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
+ 'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--slug', '--source'],
'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'feedback': ['--brain', '--help', '--json', '--page', '--source'],
diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts
index b5defc05f4..930e9d486e 100644
--- a/src/core/cycle/synthesize-concepts.ts
+++ b/src/core/cycle/synthesize-concepts.ts
@@ -607,8 +607,7 @@ export async function runPhaseSynthesizeConcepts(
source_id: opts.sourceId ?? 'default',
cost_delta: estimatedSpendUsd,
round_completed_delta: failures.length === 0 && publicationDeferred.length === 0 && publicationHeld.length === 0 ? 1 : 0,
- halt_delta: failures.length > 0 ? 1 : 0,
- halt_reason: 'item_error',
+ halt_delta: failures.length > 0 ? 1 : 0, halt_reason: 'item_error',
});
}
diff --git a/src/core/facts/conversation-types.ts b/src/core/facts/conversation-types.ts
index ff8b86ce2c..2856a7082a 100644
--- a/src/core/facts/conversation-types.ts
+++ b/src/core/facts/conversation-types.ts
@@ -113,3 +113,31 @@ export function conversationFactsEligibleSql(alias: string, typesParam: string,
return `${alias}.type = ANY(${typesParam}::text[]) AND ${marker} NOT IN (${list(FLAG_FALSE)})` +
(strict ? ` AND (${alias}.type = 'conversation' OR ${marker} IN (${list(FLAG_TRUE)}))` : '');
}
+
+/** One parsed conversation turn (or one piece of a turn split for the window budget). */
+export interface ConversationMessage {
+ speaker: string;
+ /** ISO 8601 timestamp parsed from the rendered message line. */
+ timestamp: string;
+ text: string;
+}
+
+/** One bounded extraction window: whole turns (or pieces) from one eligible gap group. */
+export interface ConversationSegment {
+ messages: ConversationMessage[];
+ startIso: string;
+ endIso: string;
+ participants: string[];
+}
+
+/** Options for `splitIntoSegments` (src/core/facts/conversation-windows.ts). */
+export interface SplitSegmentsOpts {
+ gapMinutes?: number;
+ maxMessages?: number;
+ /** Drop messages with timestamp <= this ISO before splitting. */
+ sinceIso?: string;
+ /** Rendered-character budget per window, header included. Default SEGMENT_TEXT_CHAR_LIMIT. */
+ maxChars?: number;
+ /** Page title rendered into every window header; counted against `maxChars`. */
+ pageTitle?: string;
+}
diff --git a/src/core/facts/conversation-windows.ts b/src/core/facts/conversation-windows.ts
new file mode 100644
index 0000000000..0faef3c9a4
--- /dev/null
+++ b/src/core/facts/conversation-windows.ts
@@ -0,0 +1,220 @@
+/**
+ * Conversation windowing for `extract-conversation-facts` (#6267, wave 15 P2.5).
+ *
+ * eligible gap group → bounded windows (message cap + rendered-char budget)
+ *
+ * Before this module a dense time segment was rendered and then clipped at
+ * SEGMENT_TEXT_CHAR_LIMIT with an `…(truncated)` marker, and the 31st reply
+ * of a 31-turn group was dropped as a too-short segment, while the page was
+ * still stamped complete. Here every eligible turn lands in exactly one
+ * window and every rendered window fits the budget, header included.
+ *
+ * Eligibility is decided per gap-separated group BEFORE windowing: a group
+ * needs MIN_SEGMENT_MESSAGES original messages, so an original singleton
+ * stays ineligible and splitting one oversized turn never makes a page
+ * eligible. Inside an eligible group a window closes when the next message
+ * would exceed the message cap or the rendered budget, and that message
+ * opens a new bounded window; a trailing single reply of an eligible group
+ * is a legitimate one-message window, never glued across a gap and never
+ * appended over the budget. A turn that cannot fit alone is split at
+ * sentence boundaries (then word, then code-point boundaries) and each
+ * piece keeps the `speaker (timestamp): ` prefix. A header that leaves no
+ * room for text refuses before any window exists, so the caller fails the
+ * page before it cleans up prior facts.
+ *
+ * Lives in `src/core/facts/` so core consumers never import from
+ * `src/commands/` (the command re-exports these names for its callers).
+ */
+import type { ConversationMessage, ConversationSegment, SplitSegmentsOpts } from './conversation-types.ts';
+
+/** Maximum gap between adjacent messages before we cut a new segment. */
+export const DEFAULT_SEGMENT_GAP_MINUTES = 30;
+
+/**
+ * Hard cap on messages per window, regardless of timing.
+ * Tuned down from PR's 50 → 30 (Eng-v2 T5): combined with the 6500-char
+ * SEGMENT_TEXT_CHAR_LIMIT, this keeps headroom under extract.ts's
+ * MAX_TURN_TEXT_CHARS = 8000 so tail facts in dense Slack/email
+ * segments don't vanish silently.
+ */
+export const DEFAULT_SEGMENT_MAX_MESSAGES = 30;
+
+/** Minimum original messages a gap group needs to be worth extracting. */
+export const MIN_SEGMENT_MESSAGES = 2;
+
+/**
+ * Budget on the rendered window passed to the extractor, header included.
+ * Tuned down from PR's 7500 → 6500 (Eng-v2 T5) to leave headroom for the
+ * topical/temporal header under extract.ts's MAX_TURN_TEXT_CHARS = 8000.
+ * Since #6267 this is a window boundary, never a clip.
+ */
+export const SEGMENT_TEXT_CHAR_LIMIT = 6500;
+
+/** Upper bound for a page's `conversation_segment_gap_minutes` (one week). */
+export const MAX_PAGE_SEGMENT_GAP_MINUTES = 10_080;
+
+/** Smallest text a split piece may carry, so a tight header still makes progress. */
+const MIN_PIECE_CHARS = 32;
+
+export function renderConversationLine(m: ConversationMessage): string {
+ return `${m.speaker} (${m.timestamp}): ${m.text}`;
+}
+
+export function renderConversationHeader(pageTitle: string, participants: readonly string[], startIso: string, endIso: string): string {
+ return [
+ `Page: ${pageTitle}`,
+ `Conversation between ${participants.join(' and ')} from ${startIso} to ${endIso}`,
+ '---',
+ ].join('\n');
+}
+
+function participantsOf(messages: readonly ConversationMessage[]): string[] {
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const m of messages) {
+ if (seen.has(m.speaker)) continue;
+ seen.add(m.speaker);
+ out.push(m.speaker);
+ }
+ return out;
+}
+
+function segmentOf(messages: ConversationMessage[]): ConversationSegment {
+ return {
+ messages,
+ startIso: messages[0].timestamp,
+ endIso: messages[messages.length - 1].timestamp,
+ participants: participantsOf(messages),
+ };
+}
+
+function renderedLength(pageTitle: string, messages: readonly ConversationMessage[]): number {
+ const header = renderConversationHeader(pageTitle, participantsOf(messages), messages[0].timestamp, messages[messages.length - 1].timestamp);
+ let n = header.length;
+ for (const m of messages) n += 1 + renderConversationLine(m).length;
+ return n;
+}
+
+/**
+ * Cut `text` into consecutive substrings of at most `budget` UTF-16 units
+ * each, preferring a sentence end, then a whitespace gap, and never inside
+ * a surrogate pair. `pieces.join('')` is exactly `text`.
+ */
+export function splitTurnText(text: string, budget: number): string[] {
+ const pieces: string[] = [];
+ let rest = text;
+ while (rest.length > budget) {
+ const head = rest.slice(0, budget);
+ let cut = -1;
+ const sentence = /[.!?…。!?][)"'”’»]*\s+/g;
+ for (let m = sentence.exec(head); m; m = sentence.exec(head)) cut = m.index + m[0].length;
+ if (cut < MIN_PIECE_CHARS) {
+ const word = /\s+/g;
+ for (let m = word.exec(head); m; m = word.exec(head)) cut = m.index + m[0].length;
+ }
+ if (cut < MIN_PIECE_CHARS) cut = budget;
+ const code = head.charCodeAt(cut - 1);
+ if (code >= 0xd800 && code <= 0xdbff) cut--;
+ pieces.push(rest.slice(0, cut));
+ rest = rest.slice(cut);
+ }
+ if (rest.length > 0 || pieces.length === 0) pieces.push(rest);
+ return pieces;
+}
+
+/**
+ * Bounded windows over one eligible gap group. Every message lands in
+ * exactly one window; a message whose own line overflows the budget is
+ * replaced by its pieces (same speaker and timestamp) before packing.
+ */
+function windowGroup(group: ConversationMessage[], pageTitle: string, maxMessages: number, maxChars: number): ConversationSegment[] {
+ const out: ConversationSegment[] = [];
+ let cur: ConversationMessage[] = [];
+ const close = () => {
+ if (cur.length > 0) out.push(segmentOf(cur));
+ cur = [];
+ };
+ for (const m of group) {
+ const parts = renderedLength(pageTitle, [m]) <= maxChars ? [m] : splitOversizedTurn(m, pageTitle, maxChars);
+ for (const part of parts) {
+ if (cur.length >= maxMessages || (cur.length > 0 && renderedLength(pageTitle, [...cur, part]) > maxChars)) close();
+ cur.push(part);
+ }
+ }
+ close();
+ return out;
+}
+
+function splitOversizedTurn(m: ConversationMessage, pageTitle: string, maxChars: number): ConversationMessage[] {
+ const fixed = renderedLength(pageTitle, [{ ...m, text: '' }]);
+ const budget = maxChars - fixed;
+ if (budget < MIN_PIECE_CHARS) {
+ throw new Error(
+ `conversation window header leaves no room for text: the page title, speaker "${m.speaker}" and timestamps render to ${fixed} of ${maxChars} characters; ` +
+ 'shorten the page title or the speaker label, then rerun extraction for this page',
+ );
+ }
+ return splitTurnText(m.text, budget).map((text) => ({ ...m, text }));
+}
+
+/**
+ * Split parsed messages into bounded extraction windows.
+ *
+ * 1. Drop messages at or before `sinceIso` and unparseable timestamps.
+ * 2. Cut gap groups on `gapMinutes`; a group with fewer than
+ * MIN_SEGMENT_MESSAGES messages is ineligible and dropped whole.
+ * 3. Window each eligible group under `maxMessages` and `maxChars`
+ * (the rendered budget, header included, for `pageTitle`).
+ */
+export function splitIntoSegments(
+ messages: ConversationMessage[],
+ opts: SplitSegmentsOpts = {},
+): ConversationSegment[] {
+ const gapMs = (opts.gapMinutes ?? DEFAULT_SEGMENT_GAP_MINUTES) * 60_000;
+ const maxMessages = opts.maxMessages ?? DEFAULT_SEGMENT_MAX_MESSAGES;
+ const maxChars = opts.maxChars ?? SEGMENT_TEXT_CHAR_LIMIT;
+ const pageTitle = opts.pageTitle ?? '';
+ const sinceMs = opts.sinceIso ? Date.parse(opts.sinceIso) : NaN;
+
+ const groups: ConversationMessage[][] = [];
+ let cur: ConversationMessage[] = [];
+ let lastTs: number | null = null;
+ for (const m of messages) {
+ const ts = Date.parse(m.timestamp);
+ if (!Number.isFinite(ts)) continue;
+ if (Number.isFinite(sinceMs) && ts <= sinceMs) continue;
+ if (lastTs !== null && ts - lastTs > gapMs) {
+ groups.push(cur);
+ cur = [];
+ }
+ cur.push(m);
+ lastTs = ts;
+ }
+ groups.push(cur);
+
+ return groups
+ .filter((g) => g.length >= MIN_SEGMENT_MESSAGES)
+ .flatMap((g) => windowGroup(g, pageTitle, maxMessages, maxChars));
+}
+
+/**
+ * Render one window with its topical/temporal header. Windows from
+ * `splitIntoSegments` always fit; a hand-built segment that does not is
+ * refused instead of clipped, so an extractor never certifies text it did
+ * not see.
+ */
+export function renderSegmentForExtraction(
+ pageTitle: string,
+ segment: ConversationSegment,
+ maxChars: number = SEGMENT_TEXT_CHAR_LIMIT,
+): string {
+ const header = renderConversationHeader(pageTitle, segment.participants, segment.startIso, segment.endIso);
+ const full = `${header}\n${segment.messages.map(renderConversationLine).join('\n')}`;
+ if (full.length > maxChars) {
+ throw new Error(
+ `conversation window ${segment.startIso}..${segment.endIso} renders to ${full.length} characters, over the ${maxChars} budget; ` +
+ 'windows must come from splitIntoSegments, which bounds them',
+ );
+ }
+ return full;
+}
diff --git a/test/conversation-windows-6267.test.ts b/test/conversation-windows-6267.test.ts
new file mode 100644
index 0000000000..133055f103
--- /dev/null
+++ b/test/conversation-windows-6267.test.ts
@@ -0,0 +1,249 @@
+/**
+ * Wave 15 P2.5 (PR #6267, [R17] [R24]): `extract-conversation-facts` must
+ * deliver every eligible turn to the extractor in bounded windows instead of
+ * clipping a dense segment at 6,500 rendered characters or dropping the 31st
+ * reply of a 31-turn group.
+ *
+ * eligible gap group → bounded windows (message cap + rendered-char budget)
+ *
+ * Eligibility is decided per gap-separated group before windowing, so an
+ * original singleton stays ineligible, a gap-separated tail is never glued to
+ * the previous window and a trailing reply that cannot fit opens a new
+ * bounded window. Oversized turns split at sentence boundaries with the
+ * speaker prefix repeated; a header that leaves no room refuses before any
+ * window exists. Pages already stamped complete are not re-extracted.
+ *
+ * Contributed by @jordanschwartz-js (PR #6267 reproduced the clip and wrote
+ * the first coverage cases); this file is the superseding design's tests.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ DEFAULT_SEGMENT_MAX_MESSAGES,
+ MIN_SEGMENT_MESSAGES,
+ SEGMENT_TEXT_CHAR_LIMIT,
+ parseConversationMessages,
+ renderSegmentForExtraction,
+ runExtractConversationFactsCore,
+ splitIntoSegments,
+ type ConversationMessage,
+ type ConversationSegment,
+} from '../src/commands/extract-conversation-facts.ts';
+
+const TITLE = 'imessage: Alice Example';
+
+function at(minute: number, speaker: string, text: string): ConversationMessage {
+ const base = Date.UTC(2024, 2, 15, 9, 0, 0);
+ return { speaker, timestamp: new Date(base + minute * 60_000).toISOString().replace('.000Z', 'Z'), text };
+}
+
+function turns(count: number, textFor: (i: number) => string, startMinute = 0): ConversationMessage[] {
+ return Array.from({ length: count }, (_, i) => at(startMinute + i, i % 2 === 0 ? 'Alice Example' : 'Bob Demo', textFor(i)));
+}
+
+function rendered(segments: ConversationSegment[], title = TITLE): string[] {
+ return segments.map((seg) => renderSegmentForExtraction(title, seg));
+}
+
+/** Each original turn's text appears in exactly one window, in order. */
+function expectEveryTurnOnce(messages: ConversationMessage[], windows: string[]): void {
+ for (const m of messages) {
+ const line = `${m.speaker} (${m.timestamp}): ${m.text}`;
+ const hits = windows.filter((w) => w.includes(line));
+ expect(hits).toHaveLength(1);
+ }
+}
+
+describe('conversation windows (#6267): eligibility before windowing', () => {
+ test('40 dense turns (~9,000 rendered chars): every turn lands in exactly one window and no window exceeds the budget', () => {
+ const messages = turns(40, (i) => `turn ${String(i).padStart(2, '0')} ${'x'.repeat(200)} end-${i}`);
+ const segments = splitIntoSegments(messages, { pageTitle: TITLE });
+ const windows = rendered(segments);
+ expect(segments.reduce((n, s) => n + s.messages.length, 0)).toBe(40);
+ for (const w of windows) {
+ expect(w.length).toBeLessThanOrEqual(SEGMENT_TEXT_CHAR_LIMIT);
+ expect(w).not.toContain('…(truncated)');
+ }
+ for (const s of segments) expect(s.messages.length).toBeLessThanOrEqual(DEFAULT_SEGMENT_MAX_MESSAGES);
+ expectEveryTurnOnce(messages, windows);
+ expect(windows.length).toBeGreaterThanOrEqual(2);
+ });
+
+ test('31 messages in one eligible group: the 31st reply is kept as its own bounded window, not dropped', () => {
+ const messages = turns(31, (i) => `short ${i}`);
+ const segments = splitIntoSegments(messages, { pageTitle: TITLE });
+ expect(segments.reduce((n, s) => n + s.messages.length, 0)).toBe(31);
+ expect(segments.map((s) => s.messages.length)).toEqual([30, 1]);
+ expect(segments[1].messages[0].text).toBe('short 30');
+ expect(segments[1].startIso).toBe(messages[30].timestamp);
+ expectEveryTurnOnce(messages, rendered(segments));
+ });
+
+ test('an original singleton stays ineligible, alone and after a gap', () => {
+ expect(splitIntoSegments([at(0, 'Alice Example', 'only one')], { pageTitle: TITLE })).toHaveLength(0);
+ const long = at(0, 'Alice Example', `${'A long single turn. '.repeat(600)}`);
+ expect(long.text.length).toBeGreaterThan(SEGMENT_TEXT_CHAR_LIMIT);
+ // Splitting one oversized turn must not make a singleton conversation eligible.
+ expect(splitIntoSegments([long], { pageTitle: TITLE })).toHaveLength(0);
+ const withTail = [...turns(2, (i) => `pair ${i}`), at(200, 'Alice Example', 'lonely tail')];
+ const segments = splitIntoSegments(withTail, { pageTitle: TITLE });
+ expect(segments).toHaveLength(1);
+ expect(segments[0].messages.map((m) => m.text)).toEqual(['pair 0', 'pair 1']);
+ expect(MIN_SEGMENT_MESSAGES).toBe(2);
+ });
+
+ test('a gap-separated tail is never glued to the previous window', () => {
+ const head = turns(30, (i) => `head ${i}`);
+ const tail = turns(2, (i) => `tail ${i}`, 29 + 90);
+ const segments = splitIntoSegments([...head, ...tail], { pageTitle: TITLE });
+ expect(segments.map((s) => s.messages.length)).toEqual([30, 2]);
+ expect(segments[1].startIso).toBe(tail[0].timestamp);
+ for (const s of segments) {
+ expect(Date.parse(s.endIso) - Date.parse(s.startIso)).toBeLessThan(90 * 60_000);
+ }
+ const lonely = splitIntoSegments([...head, at(29 + 90, 'Bob Demo', 'lonely')], { pageTitle: TITLE });
+ expect(lonely.reduce((n, s) => n + s.messages.length, 0)).toBe(30);
+ });
+
+ test('a full window plus a long final reply: the reply opens new bounded windows split at sentence boundaries with the speaker prefix repeated', () => {
+ const head = turns(30, (i) => `head ${i}`);
+ const sentences = Array.from({ length: 200 }, (_, i) => `Sentence ${i} says 日本語 and 🎉 then stops here. `);
+ const reply = at(30, 'Bob Demo', sentences.join('').trimEnd());
+ expect(reply.text.length).toBeGreaterThan(SEGMENT_TEXT_CHAR_LIMIT);
+ const segments = splitIntoSegments([...head, reply], { pageTitle: TITLE });
+ expect(segments[0].messages).toHaveLength(30);
+ const pieces = segments.slice(1).flatMap((s) => s.messages);
+ expect(pieces.length).toBeGreaterThanOrEqual(2);
+ for (const p of pieces) {
+ expect(p.speaker).toBe('Bob Demo');
+ expect(p.timestamp).toBe(reply.timestamp);
+ expect(p.text.length).toBeGreaterThan(0);
+ expect(p.text.isWellFormed()).toBe(true);
+ }
+ expect(pieces.map((p) => p.text).join('')).toBe(reply.text);
+ // Every cut sits after a sentence end.
+ for (const p of pieces.slice(0, -1)) expect(p.text.trimEnd().endsWith('.')).toBe(true);
+ for (const w of rendered(segments)) {
+ expect(w.length).toBeLessThanOrEqual(SEGMENT_TEXT_CHAR_LIMIT);
+ expect(w).not.toContain('…(truncated)');
+ }
+ const prefix = `Bob Demo (${reply.timestamp}): `;
+ for (const w of rendered(segments).slice(1)) expect(w.split(prefix).length - 1).toBeGreaterThanOrEqual(1);
+ expect(segments.reduce((n, s) => n + s.messages.length, 0)).toBe(30 + pieces.length);
+ });
+
+ test('a single sentence longer than the budget is cut on code-point boundaries and reassembles exactly', () => {
+ const run = '🙂é字'.repeat(4_000);
+ const messages = [at(0, 'Alice Example', 'hi'), at(1, 'Bob Demo', run)];
+ const segments = splitIntoSegments(messages, { pageTitle: TITLE });
+ const pieces = segments.flatMap((s) => s.messages).filter((m) => m.speaker === 'Bob Demo');
+ expect(pieces.length).toBeGreaterThan(1);
+ for (const p of pieces) expect(p.text.isWellFormed()).toBe(true);
+ expect(pieces.map((p) => p.text).join('')).toBe(run);
+ for (const w of rendered(segments)) expect(w.length).toBeLessThanOrEqual(SEGMENT_TEXT_CHAR_LIMIT);
+ });
+
+ test('a header that leaves no room for text refuses before any window is built', () => {
+ const messages = turns(3, (i) => `turn ${i}`);
+ const title = 'T'.repeat(SEGMENT_TEXT_CHAR_LIMIT);
+ expect(() => splitIntoSegments(messages, { pageTitle: title })).toThrow(/header/);
+ });
+
+ test('renderSegmentForExtraction refuses an oversized hand-built window instead of clipping it', () => {
+ const messages = turns(40, (i) => `turn ${i} ${'y'.repeat(200)}`);
+ const seg: ConversationSegment = {
+ messages,
+ startIso: messages[0].timestamp,
+ endIso: messages[39].timestamp,
+ participants: ['Alice Example', 'Bob Demo'],
+ };
+ expect(() => renderSegmentForExtraction(TITLE, seg)).toThrow(/window/);
+ });
+
+ test('the rendering of a window that fits is unchanged (no extractor-version bump)', () => {
+ const messages = turns(2, (i) => `hello ${i}`);
+ const [seg] = splitIntoSegments(messages, { pageTitle: TITLE });
+ expect(renderSegmentForExtraction(TITLE, seg)).toBe([
+ `Page: ${TITLE}`,
+ `Conversation between Alice Example and Bob Demo from ${messages[0].timestamp} to ${messages[1].timestamp}`,
+ '---',
+ `Alice Example (${messages[0].timestamp}): hello 0`,
+ `Bob Demo (${messages[1].timestamp}): hello 1`,
+ ].join('\n'));
+ });
+
+ test('legacy options still apply: maxMessages, gapMinutes and sinceIso', () => {
+ const lines = Array.from({ length: 7 }, (_, i) => `**Alice Example** (2024-03-15 9:0${i} AM): msg ${i}`);
+ const parsed = parseConversationMessages(lines.join('\n'));
+ const capped = splitIntoSegments(parsed, { maxMessages: 3, pageTitle: TITLE });
+ expect(capped.map((s) => s.messages.length)).toEqual([3, 3, 1]);
+ const since = splitIntoSegments(parsed, { sinceIso: '2024-03-15T09:04:30Z', pageTitle: TITLE });
+ expect(since.flatMap((s) => s.messages.map((m) => m.text))).toEqual(['msg 5', 'msg 6']);
+ const gapped = splitIntoSegments(parsed, { gapMinutes: 0.5, pageTitle: TITLE });
+ expect(gapped).toHaveLength(0);
+ });
+});
+
+describe('conversation windows (#6267): command path on PGLite', () => {
+ let engine: PGLiteEngine;
+ const dense = Array.from({ length: 40 }, (_, i) => {
+ const mm = String(i).padStart(2, '0');
+ const who = i % 2 === 0 ? 'Alice Example' : 'Bob Demo';
+ return `**${who}** (2024-03-15 9:${mm} AM): dense turn ${mm} ${'z'.repeat(200)} tail-${mm}`;
+ }).join('\n');
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => { await engine.disconnect(); });
+
+ test('a dense page delivers every turn once, the preview counts every window, and the completed page is not re-extracted', async () => {
+ const slug = 'conversations/dense-example';
+ await engine.putPage(slug, { type: 'conversation', title: TITLE, compiled_truth: dense, timeline: '', frontmatter: { date: '2024-03-15' } }, { sourceId: 'default' });
+ const preview = await runExtractConversationFactsCore(engine, { sourceId: 'default', slug, dryRun: true, sleepMs: 0, extractor: async () => [] });
+ expect(preview.pages_processed).toBe(1);
+ const seen: string[] = [];
+ const result = await runExtractConversationFactsCore(engine, {
+ sourceId: 'default', slug, sleepMs: 0,
+ extractor: async (input) => { seen.push(input.turnText); return []; },
+ });
+ expect(result.pages_processed).toBe(1);
+ expect(result.pages_failed).toBe(0);
+ expect(seen.length).toBe(preview.segments_processed);
+ expect(seen.length).toBeGreaterThanOrEqual(2);
+ for (const w of seen) {
+ expect(w.length).toBeLessThanOrEqual(SEGMENT_TEXT_CHAR_LIMIT);
+ expect(w).not.toContain('…(truncated)');
+ }
+ for (let i = 0; i < 40; i++) {
+ const mm = String(i).padStart(2, '0');
+ expect(seen.filter((w) => w.includes(`tail-${mm}`))).toHaveLength(1);
+ }
+ let again = 0;
+ const replay = await runExtractConversationFactsCore(engine, { sourceId: 'default', slug, sleepMs: 0, extractor: async () => { again++; return []; } });
+ expect(replay.pages_skipped_completed).toBe(1);
+ expect(again).toBe(0);
+ });
+
+ test('a segment-limited run never stamps unseen text complete; the next run reaches the tail', async () => {
+ const slug = 'conversations/dense-limited-example';
+ await engine.putPage(slug, { type: 'conversation', title: TITLE, compiled_truth: dense, timeline: '', frontmatter: { date: '2024-03-15' } }, { sourceId: 'default' });
+ const first: string[] = [];
+ const limited = await runExtractConversationFactsCore(engine, {
+ sourceId: 'default', slug, sleepMs: 0, segmentLimit: 1,
+ extractor: async (input) => { first.push(input.turnText); return []; },
+ });
+ expect(limited.segments_processed).toBe(1);
+ expect(first.some((w) => w.includes('tail-39'))).toBe(false);
+ const rest: string[] = [];
+ const resumed = await runExtractConversationFactsCore(engine, {
+ sourceId: 'default', slug, sleepMs: 0,
+ extractor: async (input) => { rest.push(input.turnText); return []; },
+ });
+ expect(resumed.pages_skipped_completed).toBe(0);
+ expect(resumed.pages_processed).toBe(1);
+ expect(rest.some((w) => w.includes('tail-39'))).toBe(true);
+ });
+});