Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(large-pages): incremental conversation facts on segmented pages (Wave B PR 4 lane 4b)

garrytan623ddbfbf081
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index d1a0bf67ec..99d5a5a0b1 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -7,7 +7,7 @@ src/cli/main.ts 3016 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SEL
src/commands/autopilot.ts 1662 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); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)
src/commands/doctor.ts 688 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
-src/commands/extract-conversation-facts.ts 2044 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left
+src/commands/extract-conversation-facts.ts 1889 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left; lowered Wave B PR 4 lane 4b: per-window extraction, outcome rows and the version token peeled to core/facts/conversation-window-extract.ts, segmented pages routed to core/facts/conversation-incremental.ts
src/commands/extract.ts 2677 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); 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; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured
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 937 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts)
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index c315df6c79..1b297d95c9 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -31,7 +31,6 @@ src/commands/enrich.ts enrichOneLocked field SEGW
src/commands/export.ts runExport call:serializeMarkdown SEGW
src/commands/export.ts runExport field STREAM
src/commands/export.ts runExport sql STREAM
-src/commands/extract-conversation-facts.ts regularPageVersionToken field STREAM
src/commands/extract-mentions-explain.ts explainMention field STREAM
src/commands/extract-mentions-explain.ts explainMention sql STREAM
src/commands/extract-mentions-explain.ts pageNames sql STREAM
@@ -212,6 +211,7 @@ src/core/facts-fence.ts factsFenceSections field SEGW
src/core/facts-fence.ts factsFenceView field INLINE inline arm; a segmented page reads its fences from its marker segments (segmentedFactsFenceView)
src/core/facts/backstop.ts runFactsBackstop field STREAM
src/core/facts/backstop.ts runPipeline field STREAM
+src/core/facts/conversation-window-extract.ts regularPageVersionToken field STREAM
src/core/facts/drain.ts estimateBacklogUsd sql META
src/core/facts/eligibility.ts isFactsBackstopEligible field LEAD
src/core/facts/file-body-guard.ts fileBodyMatchesStored field SEGW a segmented page reads NULL inline columns, never matches, and the caller holds it (nothing written)
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 989009600b..92c976a26f 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -67,9 +67,7 @@
import { extractExitCode, extractRunStatus, recordFailedPage } from '../core/facts/conversation-run-status.ts';
import type { BrainEngine, NewFact } from '../core/engine.ts';
import type { Page } from '../core/types.ts';
-import { observationDateFrom, resolveObservationDate, type ObservationDate } from '../core/ai/date-grounding.ts';
import {
- extractFactsFromTurnWithOutcome,
isFactsExtractionEnabled,
type ExtractFailureReason,
type ExtractInput,
@@ -103,16 +101,18 @@ import { assertFactsEmbeddingDimMatchesConfig } from '../core/embedding-dim-chec
import { writeReceipt, shortRunId } from '../core/extract/receipt-writer.ts';
import { upsertExtractRollup, classifyRunStop } from '../core/extract/rollup-writer.ts';
import { ALLOWED_TYPES, ALLOWED_TYPE_ALIASES, isConversationFactsEligiblePage, pageTypesForAllowed, requireParseableConversationFlag, type AllowedType } from '../core/facts/conversation-types.ts';
-import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE, stampExtractorVersion } from '../core/facts/audit-sources.ts';
+import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE } from '../core/facts/audit-sources.ts';
import { resolveDefaultVisibility, type FactVisibility } from '../core/facts/visibility.ts';
import {
emptySaveTimeResolutionCounts,
formatSaveTimeResolutionCounts,
mergeSaveTimeResolutionCounts,
- resolveExtractedEntitiesForSave,
} from '../core/entities/resolve-on-save.ts';
-import { CONVERSATION_ENTITY_HINTS_CAP, conversationEntityHints } from '../core/facts/conversation-entity-hints.ts';
-import { inferConversationSubjects } from '../core/facts/conversation-subject-infer.ts';
+import { conversationEntityHints } from '../core/facts/conversation-entity-hints.ts';
+import { extractConversationWindow, nonExtractableAuditFact, outcomeSession, regularPageVersionToken, terminalAuditFact } from '../core/facts/conversation-window-extract.ts';
+export { segmentObservationDate } from '../core/facts/conversation-window-extract.ts';
+import { processSegmentedConversationPage } from '../core/facts/conversation-incremental.ts';
+import { isSegmentedPage } from '../core/page-body/page-shape.ts';
// Re-exported verbatim so existing importers (this file's own helpers below
// and this file's tests) keep working unchanged; doctor.ts, jobs.ts,
@@ -430,35 +430,6 @@ export function pageSegmentGapMinutes(page: Pick<Page, 'slug' | 'frontmatter'>):
return undefined;
}
-// ---------------------------------------------------------------------------
-// Segment rendering with topical/temporal header.
-// ---------------------------------------------------------------------------
-
-/**
- * Observation date of a conversation segment (date-grounding.ts): the
- * segment's own timestamp when it came from the transcript itself or the
- * page's frontmatter date — never the synthetic epoch fallback, and never a
- * timestamp the parser derived from effective_date (which may be an event
- * date). Otherwise the page's observation date, or null (unknown).
- */
-/**
- * A conversation fact's valid_from: a validated event date the extractor
- * stated (date-grounding variant) wins; else the segment start, except the
- * epoch fallback (no trustworthy date → the insert's now() default).
- */
-function segmentValidFrom(extracted: Date | undefined, startIso: string | undefined): { valid_from?: Date } {
- if (extracted) return { valid_from: extracted };
- return startIso && !startIso.startsWith('1970-') ? { valid_from: new Date(startIso) } : {};
-}
-
-export function segmentObservationDate(page: Pick<Page, 'slug' | 'frontmatter' | 'effective_date'>, startIso: string | undefined): ObservationDate | null {
- const day = startIso?.slice(0, 10);
- const context = deriveDateContext({ page: page as Page });
- const explicit = !!day && !day.startsWith('1970-')
- && (context.source === 'explicit' || context.source === 'frontmatter_date' || day !== context.fallbackDate);
- return explicit ? observationDateFrom(startIso) : resolveObservationDate({ slug: page.slug, frontmatter: page.frontmatter });
-}
-
// ---------------------------------------------------------------------------
// Fingerprint — sourceId-only (Eng-v2 A3). Widening types config does NOT
// invalidate prior completion state.
@@ -730,25 +701,6 @@ function hasRawTranscriptSidecar(page: Page): boolean {
return typeof raw === 'string' && raw.trim().length > 0;
}
-function regularPageVersionToken(page: Page): string {
- // content_hash covers title, type, compiled_truth, timeline, and frontmatter.
- // Unlike JavaScript Date, it cannot collapse distinct PostgreSQL updates that
- // happen within the same millisecond. effective_date is parser input too.
- const hash = page.content_hash ?? createHash('sha256')
- .update(JSON.stringify({
- title: page.title,
- type: page.type,
- compiled_truth: page.compiled_truth,
- timeline: page.timeline || '',
- frontmatter: page.frontmatter || {},
- }))
- .digest('hex');
- const effectiveDate = page.effective_date
- ? new Date(page.effective_date).toISOString().slice(0, 10)
- : 'none';
- return `page-${hash}-${effectiveDate}`;
-}
-
function snapshotVersionToken(page: Page, input: { body: string; sidecar?: true }): string {
if (!hasRawTranscriptSidecar(page)) return regularPageVersionToken(page);
// Sidecar contents can change without touching pages.updated_at. Hash the exact parser input plus parser-relevant page metadata so those
@@ -780,10 +732,6 @@ async function preparePageSnapshot(
}
}
-function outcomeSession(source: string, slug: string, versionToken: string): string {
- return `${source}:${slug}:${versionToken}`;
-}
-
/**
* Find v2 outcomes bound to the exact parser input snapshot. Legacy outcome
* rows deliberately do not match and are replayed once under the strict v2
@@ -1021,80 +969,15 @@ async function processPage(
if (state.signal?.aborted) throw new Error('aborted');
const text = renderSegmentForExtraction(page.title || page.slug, seg);
- const sessionId = `${PER_SEGMENT_SOURCE_PREFIX}:${page.slug}`;
-
- // BrainBench (decision 15) may inject a deterministic extractor; when it
- // does, use it (returns facts directly — the hermetic gold path). The
- // DEFAULT production path is master's fail-hard-with-reason contract: a
- // per-segment extraction failure aborts the page rather than silently
- // dropping facts.
- let extracted: ExtractedFact[];
- const input: ExtractInput = { turnText: text, sessionId, source: PER_SEGMENT_SOURCE_PREFIX, engine: state.engine, abortSignal: state.signal,
- entityHints, entityHintsCap: CONVERSATION_ENTITY_HINTS_CAP };
- if (state.extractor) {
- extracted = await state.extractor(input);
- } else {
- const extraction = await extractFactsFromTurnWithOutcome({ ...input, observationDate: segmentObservationDate(page, seg.startIso) });
- if (!extraction.ok) {
- // #3669 — rethrow BudgetExhausted UNWRAPPED. Wrapping it in a plain
- // Error strips the BUDGET_EXHAUSTED tag, so the worker pool's D13
- // must-abort check never fires and every remaining page burns a
- // reserve_denied attempt instead of the run halting with a
- // budget_exhausted receipt (core catch → halted receipt → return).
- if (extraction.error instanceof BudgetExhausted) throw extraction.error;
- const detail = extraction.error instanceof Error
- ? `: ${extraction.error.message}`
- : '';
- throw Object.assign(new Error(
- `segment ${seg.startIso}..${seg.endIso} extraction failed (${extraction.reason})${detail}`,
- ), { extractionReason: extraction.reason });
- }
- extracted = extraction.facts;
- }
-
+ const window = await extractConversationWindow(state, page, seg, text, rowNum, entityHints);
state.result.segments_processed++;
segmentsThisPage++;
- state.result.facts_extracted += extracted.length;
-
- // This bulk path bypasses writeSingleFact and writes through insertFacts.
- // Canonicalize every extractor-provided entity via the shipped resolver
- // (alias_exact / prefix / fuzzy / slugify) while source scope is known.
- const segmentResolution = await resolveExtractedEntitiesForSave(
- state.engine,
- state.sourceId,
- extracted,
- (raw, message) => {
- process.stderr.write(
- `[extract-conversation-facts] ${page.slug} segment ${seg.startIso}..${seg.endIso} ` +
- `entity resolution failed for ${JSON.stringify(raw)}: ${message}; preserving fact without an entity target\n`,
- );
- },
- );
- if (extracted.length > 0) {
- // Eng-v2 C1 / E11: page-global row_num stays unique across segments.
- // entity_slug is already canonical here — resolveExtractedEntitiesForSave
- // (above) ran every fact through the shipped resolver cascade (#3729/#4052),
- // so master's per-row resolveEntitySlug mapper (#4567's independent fix for
- // the same issue) is superseded rather than layered on top.
- const rows = await inferConversationSubjects(state.engine, state.sourceId, state.factVisibility, extracted.map((fact, i) => ({ // #6764
- ...fact, visibility: state.factVisibility,
- row_num: rowNum + i,
- source_markdown_slug: page.slug,
- source: PER_SEGMENT_SOURCE_PREFIX,
- source_session: sessionId,
- // Preserve the conversation's valid time instead of defaulting every
- // extracted fact to extraction time. Epoch-anchored parses have no
- // trustworthy date, so they retain the existing now() fallback.
- ...segmentValidFrom(fact.valid_from, seg.startIso),
- context:
- fact.context ?? `from ${page.slug} segment ${seg.startIso}..${seg.endIso}`,
- })));
- pageRows.push(...rows);
- }
- rowNum += extracted.length;
- mergeSaveTimeResolutionCounts(pageResolution, segmentResolution);
- state.result.fallback_slugify_count += segmentResolution.fallback_slugify_count;
- state.result.resolution_errors += segmentResolution.resolution_errors;
+ state.result.facts_extracted += window.extracted;
+ pageRows.push(...window.rows);
+ rowNum += window.extracted;
+ mergeSaveTimeResolutionCounts(pageResolution, window.resolution);
+ state.result.fallback_slugify_count += window.resolution.fallback_slugify_count;
+ state.result.resolution_errors += window.resolution.resolution_errors;
newestEnd = seg.endIso;
if (state.sleepMs > 0) await sleep(state.sleepMs);
@@ -1156,49 +1039,6 @@ async function processPage(
return { newEndIso: newestEnd };
}
-function terminalAuditFact(
- slug: string,
- rowNum: number,
- versionToken: string,
-): NewFact & { row_num: number; source_markdown_slug: string } {
- return {
- fact: 'EXTRACTION_COMPLETE',
- kind: 'fact',
- entity_slug: null,
- source: TERMINAL_AUDIT_SOURCE,
- source_session: outcomeSession(TERMINAL_AUDIT_SOURCE, slug, versionToken),
- confidence: 1.0,
- notability: 'low',
- context: stampExtractorVersion(null),
- row_num: rowNum,
- source_markdown_slug: slug,
- };
-}
-
-function nonExtractableAuditFact(
- slug: string,
- rowNum: number,
- versionToken: string,
- reason: string,
-): NewFact & { row_num: number; source_markdown_slug: string } {
- return {
- fact: 'EXTRACTION_NOT_APPLICABLE',
- kind: 'fact',
- entity_slug: null,
- source: NON_EXTRACTABLE_AUDIT_SOURCE,
- source_session: outcomeSession(
- NON_EXTRACTABLE_AUDIT_SOURCE,
- slug,
- versionToken,
- ),
- confidence: 1.0,
- notability: 'low',
- context: stampExtractorVersion(`scanned, not extractable: ${reason}`),
- row_num: rowNum,
- source_markdown_slug: slug,
- };
-}
-
/** A result with every counter at zero, the starting point of a run or an aggregate. */
export function emptyExtractConversationFactsResult(): ExtractConversationFactsResult {
return {
@@ -1360,6 +1200,11 @@ export async function runExtractConversationFactsCore(
// which page snapshot it describes. Clear it and replay safely;
// delete-orphans-first makes that replay deterministic.
state.cpMap.delete(cpMapKey(sourceId, currentPage.slug));
+ if (isSegmentedPage(currentPage) && !state.managed && !hasRawTranscriptSidecar(currentPage)) {
+ const { newestEnd } = await processSegmentedConversationPage(state, currentPage, { gapMinutes: pageSegmentGapMinutes(currentPage) ?? null, sinceIso: opts.sinceIso });
+ if (newestEnd) state.cpMap.set(cpMapKey(sourceId, currentPage.slug), newestEnd);
+ return { newEndIso: newestEnd };
+ }
const snapshot = await preparePageSnapshot(engine, currentPage);
return processPage(state, snapshot, opts.sinceIso);
},
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index f3dbaeb083..55aa501c0a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1022,6 +1022,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #7125 and #7117 (GBRA-145). `since` is restamped at the merge slot.
{ since: '0.60.327.0', text: 'Fact extraction no longer rewrites the facts it stores: the prompt-injection filter used to delete words such as "System" before a parenthesis, so "Business System (ABS)" was saved as "Business [redacted](ABS)". Injection phrases are now neutralized only where stored facts are rendered into a model prompt (standing questions, turn context, proactive briefs). `gbrain doctor --only facts_redaction_marker` counts facts damaged earlier; `gbrain repair redacted-facts` previews what a source page can prove and changes nothing until you apply the printed `--apply --expect <hash>` command.' },
{ since: '0.60.327.0', text: 'The embed sweep that finds chunks whose text changed after they were embedded now runs in 5,000-chunk batches, keeps its place between runs (at most 60 seconds per run) and starts a new pass once a day (`embed.content_drift.pass_interval_hours`, default 24); before, one statement covered the whole brain and a large brain cancelled it on every run. `gbrain doctor --only content_drift_sweep` shows each pass and any error.' },
+ // PR 4 (Wave B incremental derivation, transcripts)
+ // PR 4 4b
+ { since: 'TBD', text: 'Appending to a long conversation now re-extracts facts only for the new messages.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
new file mode 100644
index 0000000000..7eed7773a9
--- /dev/null
+++ b/src/core/facts/conversation-incremental.ts
@@ -0,0 +1,221 @@
+/**
+ * Incremental conversation facts for a segmented page (wave-b spec 8.1, 8.2 "Conversation facts", 8.3; PR 4 lane 4b).
+ *
+ * Windows are packed inside one occurrence (segments cut at message lines and day headers; a gap group never spans a
+ * cut). Each window's facts carry its anchor in facts.source_window (occurrence, ordinal, rendered-text sha). Per
+ * occurrence, a page_segment_derivations row (kind conversation_facts) records the segment sha, a context hash (the
+ * occurrence's conversation entry state plus every page-level input the windows depend on: title, gap setting, date
+ * context, extraction model, --since) and the window keys it produced. A run then:
+ * - extracts only the windows of new, rewritten or context-changed occurrences, newest first, each one reserved
+ * against the page's spend cap (reservePageSpend, facts:<model>) before the call;
+ * - keeps every fact whose window is still live (its row and id are untouched);
+ * - clears the facts of windows no live occurrence produces any more (retired occurrences, rewritten tails), and the
+ * page's unanchored facts from older full-pass runs once every live occurrence is settled;
+ * - reads only the text of the occurrences it extracts (one segment at a time), never the whole body.
+ * A title or gap change re-extracts every window (documented cost); a no-op rewrite extracts nothing. An occurrence a
+ * run stops inside (--segment-limit, the spend cap) is stored as partial with the windows it finished, and the next
+ * run resumes after them. Unmanaged brains only: a managed brain keeps the receipted whole-page publication.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Page } from '../types.ts';
+import { deriveDateContext, parseConversation } from '../conversation-parser/parse.ts';
+import { writeDerivedFacts } from '../persistence/derived-facts.ts';
+import { reservationCostUsd } from '../budget/reservation-cost.ts';
+import { reservePageSpend, spendGrant } from '../page-embedding-budget.ts';
+import { setExtractionReceipt } from '../extraction-watermark.ts';
+import { planSegmentDerivations, segmentDerivationContextHash, sourceWindowFor, sourceWindowKey, type SegmentDerivationInput,
+ type SegmentDerivationRow, type SourceWindow } from '../page-body/derivations.ts';
+import { readConversationOccurrences, readOccurrenceText, type ConversationOccurrence } from '../page-body/segment-conversation.ts';
+import type { SegmentedBody } from '../page-body/read-range.ts';
+import { emptySaveTimeResolutionCounts, mergeSaveTimeResolutionCounts } from '../entities/resolve-on-save.ts';
+import { conversationEntityHints } from './conversation-entity-hints.ts';
+import { publishConversationFacts, type ConversationFactRow } from './conversation-publication.ts';
+import { recordFailedPage } from './conversation-run-status.ts';
+import type { ConversationSegment } from './conversation-types.ts';
+import { MAX_PAGE_SEGMENT_GAP_MINUTES, renderSegmentForExtraction, splitIntoSegments } from './conversation-windows.ts';
+import { extractConversationWindow, nonExtractableAuditFact, regularPageVersionToken, terminalAuditFact, type ConversationWindowRun } from './conversation-window-extract.ts';
+import { getFactsExtractionMaxTokens, resolveFactsExtractionModel } from './extract.ts';
+
+const KIND = 'conversation_facts';
+/** Bump when the windowing or the row output changes shape: every occurrence is extracted again once. */
+export const CONVERSATION_FACTS_DERIVATION_VERSION = 1;
+/** Rough characters per token for a reservation estimate, and the system prompt and header overhead per call. */
+const CHARS_PER_TOKEN = 4;
+const PROMPT_OVERHEAD_TOKENS = 1500;
+/** Per-1M-token rates for a model without a price: the reservation must still bound the spend. */
+const UNPRICED_CHAT_RATE = { input: 15, output: 75 };
+
+/** The run counters this pass moves (a subset of ExtractConversationFactsResult). */
+export interface SegmentedConversationCounters {
+ pages_considered: number; pages_processed: number; pages_skipped: number; pages_skipped_insufficient_turns: number;
+ pages_marked_non_extractable: number; pages_failed: number; segments_processed: number; facts_extracted: number;
+ facts_inserted: number; orphan_facts_cleaned: number; fallback_slugify_count: number; resolution_errors: number;
+ failed_pages: Array<{ slug: string; error: string }>;
+}
+
+export interface SegmentedConversationRun extends ConversationWindowRun {
+ result: SegmentedConversationCounters;
+ dryRun: boolean;
+ sleepMs: number;
+ /** At most this many windows per page per run (0: no limit). */
+ segmentLimit: number;
+}
+
+/** One window of an occurrence: what the extractor reads and its anchor. */
+interface OccurrenceWindow { seg: ConversationSegment; text: string; window: SourceWindow }
+/** A window an occurrence row records: its ordinal, rendered-text sha and how many facts it produced. */
+interface WindowRecord { ordinal: number; sha: string; facts: number }
+
+/** The bounded output a conversation_facts row stores (window anchors and counts; never text). */
+function windowRecords(row: SegmentDerivationRow | undefined): WindowRecord[] {
+ const windows = (row?.output as { windows?: unknown } | null)?.windows;
+ return Array.isArray(windows) ? windows as WindowRecord[] : [];
+}
+
+const keyOf = (occurrenceId: number, w: WindowRecord) => sourceWindowKey({ occurrence_id: occurrenceId, window_ordinal: w.ordinal, window_text_sha: w.sha });
+
+/** Every page-level input the windows of an occurrence depend on (the context hash's \`page\` part). */
+async function conversationContext(engine: BrainEngine, page: Page, gapMinutes: number | null, sinceIso: string | undefined) {
+ const dates = deriveDateContext({ page });
+ const model = (await resolveFactsExtractionModel(engine)).model;
+ return { model, inputs: { title: page.title || page.slug, gap_minutes: gapMinutes, date: dates.fallbackDate, timezone: dates.timezone ?? null, model, since: sinceIso ?? null } };
+}
+
+/** The windows of one occurrence: its own text parsed alone (with the date context its entry state carries in) and packed under the window caps. */
+async function occurrenceWindows(engine: BrainEngine, body: SegmentedBody, occurrence: ConversationOccurrence, page: Page,
+ opts: { gapMinutes: number | null; sinceIso?: string }): Promise<OccurrenceWindow[]> {
+ const text = await readOccurrenceText(engine, body, occurrence.row);
+ const fallbackDate = occurrence.conversation?.fallbackDate ?? undefined;
+ const parsed = parseConversation(text, { page, ...(fallbackDate ? { fallbackDate } : {}) });
+ const gapMinutes = opts.gapMinutes ?? (parsed.matched_pattern_id === 'email-thread-heading' ? MAX_PAGE_SEGMENT_GAP_MINUTES : undefined);
+ const pageTitle = page.title || page.slug;
+ return splitIntoSegments(parsed.messages, { gapMinutes, sinceIso: opts.sinceIso, pageTitle }).map((seg, ordinal) => {
+ const rendered = renderSegmentForExtraction(pageTitle, seg);
+ return { seg, text: rendered, window: sourceWindowFor(occurrence.row.occurrenceId, ordinal, rendered) };
+ });
+}
+
+/** What one extractor call may cost at most: the prompt estimate plus the full output ceiling. */
+function windowEstimateUsd(model: string, text: string, maxTokens: number): number {
+ const input = Math.ceil(text.length / CHARS_PER_TOKEN) + PROMPT_OVERHEAD_TOKENS;
+ return reservationCostUsd(model, 'chat', input, maxTokens) ?? (input * UNPRICED_CHAT_RATE.input + maxTokens * UNPRICED_CHAT_RATE.output) / 1_000_000;
+}
+
+/**
+ * One segmented page's conversation facts, incrementally (module doc). \`gapMinutes\` is the page's own
+ * conversation_segment_gap_minutes (null: the default). Returns the end of the newest window it extracted.
+ */
+export async function processSegmentedConversationPage(run: SegmentedConversationRun, page: Page,
+ opts: { gapMinutes: number | null; sinceIso?: string }): Promise<{ newestEnd: string | null }> {
+ const { engine, sourceId, result } = run;
+ result.pages_considered++;
+ const versionToken = regularPageVersionToken(page);
+ const { model, inputs } = await conversationContext(engine, page, opts.gapMinutes, opts.sinceIso);
+ const { body, occurrences } = await readConversationOccurrences(engine, page.id);
+ const live = occurrences.map(o => ({ occurrenceId: o.row.occurrenceId, sha256: o.row.sha256,
+ contextHash: segmentDerivationContextHash(KIND, { entryState: { region: o.row.region, conversation: o.conversation }, page: inputs }) }));
+ const prior = await engine.readSegmentDerivations(page.id, { kind: KIND });
+ const plan = planSegmentDerivations(KIND, CONVERSATION_FACTS_DERIVATION_VERSION, live, prior);
+ const priorRow = new Map(prior.map(row => [row.occurrenceId, row]));
+ const todo = new Map(plan.todo.map(segment => [segment.occurrenceId, segment]));
+ // Windows of retired occurrences by (context, rendered-text sha): a rewritten tail re-cut under a new occurrence id
+ // brings most of its windows back verbatim, and those keep their facts, re-anchored, instead of a new call.
+ const retiredWindows = new Map<string, { occurrenceId: number; record: WindowRecord }>();
+ for (const row of plan.retired) {
+ if (row.version !== CONVERSATION_FACTS_DERIVATION_VERSION) continue;
+ for (const record of windowRecords(row)) retiredWindows.set(`${Buffer.from(row.contextHash).toString('hex')}:${record.sha}`, { occurrenceId: row.occurrenceId, record });
+ }
+ const moves: Array<{ from: string; to: SourceWindow }> = [];
+
+ const maxTokens = await getFactsExtractionMaxTokens(engine);
+ const entityHints = todo.size && !run.dryRun ? await conversationEntityHints(engine, sourceId, page.slug, run.factVisibility) : undefined;
+ const resolution = emptySaveTimeResolutionCounts();
+ const rows: ConversationFactRow[] = [];
+ const windows: SourceWindow[] = [];
+ const derived = new Map<number, SegmentDerivationInput>();
+ let extractedWindows = 0;
+ const extractedKeys = new Set<string>();
+ let stop: 'segment_limit' | 'cap_reached' | null = null;
+ let newestEnd: string | null = null;
+ // Newest occurrences first, and newest windows first inside each, so a cap or a limit spends on the newest messages.
+ for (const occurrence of [...occurrences].reverse()) {
+ const segment = todo.get(occurrence.row.occurrenceId);
+ if (!segment || stop) continue;
+ // A window the occurrence's stored row already extracted under the same context (a partial run, or a tail rewrite
+ // that left it intact) keeps its facts: same ordinal and rendered-text sha.
+ const old = priorRow.get(segment.occurrenceId);
+ const reusable = old && old.version === CONVERSATION_FACTS_DERIVATION_VERSION && Buffer.from(old.contextHash).equals(Buffer.from(segment.contextHash));
+ const done = new Map((reusable ? windowRecords(old) : []).map(w => [w.ordinal, w]));
+ const all = await occurrenceWindows(engine, body, occurrence, page, opts);
+ for (const w of [...all].reverse()) {
+ const record = done.get(w.window.window_ordinal);
+ if (record?.sha === w.window.window_text_sha) continue;
+ const moved = retiredWindows.get(`${Buffer.from(segment.contextHash).toString('hex')}:${w.window.window_text_sha}`);
+ if (moved) {
+ retiredWindows.delete(`${Buffer.from(segment.contextHash).toString('hex')}:${w.window.window_text_sha}`);
+ moves.push({ from: keyOf(moved.occurrenceId, moved.record), to: w.window });
+ done.set(w.window.window_ordinal, { ordinal: w.window.window_ordinal, sha: w.window.window_text_sha, facts: moved.record.facts });
+ continue;
+ }
+ if (run.segmentLimit > 0 && extractedWindows >= run.segmentLimit) { stop = 'segment_limit'; break; }
+ if (run.signal?.aborted) throw new Error('aborted');
+ if (run.dryRun) { extractedWindows++; continue; }
+ const decision = await reservePageSpend(engine, page, `facts:${model}`, windowEstimateUsd(model, w.text, maxTokens));
+ if (decision.kind === 'refused') { stop = 'cap_reached'; break; }
+ const out = await spendGrant(decision.kind === 'grant' ? decision.grant : undefined,
+ () => extractConversationWindow(run, page, w.seg, w.text, 0, entityHints));
+ extractedWindows++;
+ result.segments_processed++;
+ result.facts_extracted += out.extracted;
+ mergeSaveTimeResolutionCounts(resolution, out.resolution);
+ for (const row of out.rows) { rows.push(row); windows.push(w.window); }
+ done.set(w.window.window_ordinal, { ordinal: w.window.window_ordinal, sha: w.window.window_text_sha, facts: out.extracted });
+ extractedKeys.add(sourceWindowKey(w.window));
+ if (!newestEnd || w.seg.endIso > newestEnd) newestEnd = w.seg.endIso;
+ if (run.sleepMs > 0) await new Promise(resolve => setTimeout(resolve, run.sleepMs));
+ }
+ const finished = all.every(w => done.get(w.window.window_ordinal)?.sha === w.window.window_text_sha);
+ const kept = all.flatMap(w => { const r = done.get(w.window.window_ordinal); return r?.sha === w.window.window_text_sha ? [r] : []; });
+ derived.set(segment.occurrenceId, { pageId: page.id, kind: KIND, occurrenceId: segment.occurrenceId, version: CONVERSATION_FACTS_DERIVATION_VERSION,
+ segmentSha256: segment.sha256, contextHash: segment.contextHash, state: finished ? 'done' : 'partial', output: { windows: kept },
+ receipt: finished ? null : { kind: 'unread_windows', pipeline: KIND, reason: stop, windows_read: kept.length, windows_total: all.length } });
+ }
+ result.fallback_slugify_count += resolution.fallback_slugify_count;
+ result.resolution_errors += resolution.resolution_errors;
+ if (run.dryRun) {
+ result.pages_processed++;
+ return { newestEnd: null };
+ }
+
+ // Window keys whose facts stay: every live occurrence's newest row (this run's, else the stored one), minus the
+ // windows extracted again this run (their earlier facts give way to the new ones).
+ const liveIds = live.map(segment => segment.occurrenceId);
+ const liveKeys = liveIds.flatMap(id => windowRecords((derived.get(id) ?? priorRow.get(id)) as SegmentDerivationRow | undefined).map(w => keyOf(id, w)));
+ const keep = liveKeys.filter(key => !extractedKeys.has(key));
+ const settled = liveIds.every(id => derived.has(id) ? derived.get(id)!.state === 'done' : !todo.has(id));
+ const current = await engine.getPage(page.slug, { sourceId });
+ const unchanged = !!current && current.id === page.id && regularPageVersionToken(current) === versionToken;
+ const outcome = !settled || !unchanged ? null : liveKeys.length
+ ? terminalAuditFact(page.slug, 0, versionToken) : nonExtractableAuditFact(page.slug, 0, versionToken, 'fewer than two eligible messages');
+ const published = await writeDerivedFacts(engine, sourceId, page.slug, async db => {
+ const out = await publishConversationFacts(db, sourceId, page.slug, outcome ? [...rows, outcome] : rows,
+ { scope: 'window', segments: { windows, moves, keep: unchanged ? keep : [...keep, ...plan.retired.flatMap(row => windowRecords(row).map(w => keyOf(row.occurrenceId, w)))], retireUnanchored: settled && unchanged } });
+ if (derived.size) await db.upsertSegmentDerivations([...derived.values()]);
+ if (unchanged) await db.retireSegmentDerivations(page.id, liveIds, { kind: KIND });
+ return out;
+ });
+ await setExtractionReceipt(engine, page.id, KIND, null);
+ result.facts_inserted += published.facts_inserted;
+ result.orphan_facts_cleaned += published.deleted;
+ if (!unchanged) {
+ process.stderr.write(`[extract-conversation-facts] ${page.slug} changed during extraction; its finished windows were kept, the rest wait for the next run\n`);
+ result.pages_failed++;
+ recordFailedPage(result, page.slug, 'the page changed during extraction; left unfinished for replay');
+ return { newestEnd: null };
+ }
+ if (outcome && !liveKeys.length) { result.pages_skipped++; result.pages_skipped_insufficient_turns++; result.pages_marked_non_extractable++; }
+ else result.pages_processed++;
+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: ${published.facts_inserted} facts inserted across ${extractedWindows} new window(s) `
+ + `(${plan.todo.length} of ${live.length} occurrence(s) to extract, ${plan.retired.length} retired)${stop ? `; stopped: ${stop}` : ''}\n`);
+ return { newestEnd };
+}
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index afb2382221..3bb768c1b9 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -80,6 +80,7 @@ import { recordReextractMemo } from './conversation-memo.ts';
import { recordTaintEdges } from '../trust/taint.ts';
import { applyGateDecision, derivedGateConfig, derivedGateInput } from '../trust/derived-gate.ts';
import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';
+import type { SourceWindow } from '../page-body/derivations.ts';
export const CONVERSATION_FACTS_INTENT = 'managed_maintenance_conversation_facts';
export const CONVERSATION_FACTS_PROTOCOL = 1;
@@ -413,6 +414,41 @@ async function mergedEntities(tx: BrainEngine, sourceId: string, slugs: string[]
type UnnumberedFact = Omit<ConversationFactRow, 'row_num' | 'source_markdown_slug'>;
+/**
+ * A segmented page's incremental publication (wave-b spec 8.2, PR 4): `windows[i]` anchors `rows[i]` (facts.source_window;
+ * null for an outcome row). Nothing is replaced wholesale: the page's extractor facts whose window key is not in `keep`
+ * (windows of retired or rewritten occurrences) are cleared, and so are its unanchored facts (older full-pass runs)
+ * when `retireUnanchored` (every live occurrence is settled); every other fact keeps its row and id.
+ */
+export interface ConversationSegmentsPublication {
+ windows: ReadonlyArray<SourceWindow | null>;
+ /** Facts re-anchored, not re-extracted: the same rendered window under the same context now lives in another occurrence. */
+ moves: ReadonlyArray<{ from: string; to: SourceWindow }>;
+ keep: readonly string[];
+ retireUnanchored: boolean;
+}
+
+const STAMP_BATCH_ROWS = 1000;
+const WINDOW_KEY_SQL = `(f.source_window->>'occurrence_id') || ':' || (f.source_window->>'window_ordinal') || ':' || (f.source_window->>'window_text_sha')`;
+
+/** Re-anchors the page's extractor facts of each `from` window key to its `to` window (ids unchanged), in bounded batches. */
+async function moveSourceWindows(tx: BrainEngine, sourceId: string, slug: string, moves: ConversationSegmentsPublication['moves']): Promise<void> {
+ for (let i = 0; i < moves.length; i += STAMP_BATCH_ROWS) {
+ await tx.executeRaw(`UPDATE facts f SET source_window = r.w FROM jsonb_to_recordset($3::text::jsonb) AS r(k text, w jsonb)
+ WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' AND ${WINDOW_KEY_SQL} = r.k`,
+ [sourceId, slug, JSON.stringify(moves.slice(i, i + STAMP_BATCH_ROWS).map(m => ({ k: m.from, w: m.to })))]);
+ }
+}
+
+/** Anchors freshly inserted facts to their windows, in bounded batches; one JSON bind per batch, so JSONB stays an object. */
+async function stampSourceWindows(tx: BrainEngine, ids: readonly number[], windows: ReadonlyArray<SourceWindow | null>): Promise<void> {
+ const pairs = ids.flatMap((id, i) => windows[i] ? [{ id, w: windows[i] }] : []);
+ for (let i = 0; i < pairs.length; i += STAMP_BATCH_ROWS) {
+ await tx.executeRaw(`UPDATE facts f SET source_window = r.w FROM jsonb_to_recordset($1::text::jsonb) AS r(id bigint, w jsonb) WHERE f.id = r.id`,
+ [JSON.stringify(pairs.slice(i, i + STAMP_BATCH_ROWS))]);
+ }
+}
+
/**
* One page's extractor rows published under its lock, shared by the managed
* apply and the unmanaged writer. Fact rows pass the write gate at the page's
@@ -425,23 +461,27 @@ type UnnumberedFact = Omit<ConversationFactRow, 'row_num' | 'source_markdown_slu
* the prior ones, and a partial run's facts are not published over them.
*/
export async function publishConversationFacts(tx: BrainEngine, sourceId: string, slug: string, rows: UnnumberedFact[],
- opts: { scope: ConversationScope; requestId?: string }): Promise<{ deleted: number; facts_inserted: number }> {
+ opts: { scope: ConversationScope; requestId?: string; segments?: ConversationSegmentsPublication }): Promise<{ deleted: number; facts_inserted: number }> {
const derivation = await conversationDerivation(tx, sourceId, slug);
const cfg = await derivedGateConfig(tx);
- const gated = rows.map(row => ({ row, decision: OUTCOME_SOURCES.has(row.source) ? null : decideFactWrite(row,
+ const gated = rows.map((row, index) => ({ row, index, decision: OUTCOME_SOURCES.has(row.source) ? null : decideFactWrite(row,
{ sourceId, slug, payload: { ...row, embedding: null }, input: derivedGateInput(derivation.trust, opts.requestId), cfg }) }));
for (const { decision } of gated) if (decision && decision.action !== 'insert') await applyGateDecision(tx, decision, { table: 'facts', sourceId }, async () => null);
const kept = gated.filter(({ decision }) => decision?.action !== 'hold' && decision?.action !== 'reject');
const [active] = await tx.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2
AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' AND f.expired_at IS NULL AND NOT (f.source = ANY($3::text[]))`, [sourceId, slug, [...AUDIT_ROW_SOURCES]]);
- const retire = !Number(active?.n ?? 0) || (opts.scope === 'full' && kept.length === rows.length && kept.some(({ row }) => !OUTCOME_SOURCES.has(row.source)));
- const published = retire || opts.scope === 'window' ? kept : kept.filter(({ row }) => OUTCOME_SOURCES.has(row.source));
+ const segments = opts.segments;
+ const retire = !segments && (!Number(active?.n ?? 0) || (opts.scope === 'full' && kept.length === rows.length && kept.some(({ row }) => !OUTCOME_SOURCES.has(row.source))));
+ const published = retire || opts.scope === 'window' || segments ? kept : kept.filter(({ row }) => OUTCOME_SOURCES.has(row.source));
const { deleted, ids } = await withWriteTrust(tx, derivation.trust, async () => {
if (retire) return replaceConversationFacts(tx, sourceId, slug, published.map(({ row }) => row));
+ if (segments) await moveSourceWindows(tx, sourceId, slug, segments.moves);
+ const retiredWindows = segments ? await clearConversationFacts(tx, sourceId, slug, segments) : 0;
const outcomes = published.some(({ row }) => OUTCOME_SOURCES.has(row.source)) ? await tx.executeRaw<{ id: number }>(`DELETE FROM facts
WHERE source_id=$1 AND source_markdown_slug=$2 AND source = ANY($3::text[]) RETURNING id`, [sourceId, slug, [...AUDIT_ROW_SOURCES]]) : [];
- return { deleted: outcomes.length, ...await insertConversationFacts(tx, sourceId, slug, published.map(({ row }) => row)) };
+ return { deleted: retiredWindows + outcomes.length, ...await insertConversationFacts(tx, sourceId, slug, published.map(({ row }) => row)) };
});
+ if (segments) await stampSourceWindows(tx, ids, published.map(({ index }) => segments.windows[index] ?? null));
for (const [i, id] of ids.entries()) {
await recordTaintEdges(tx, { table: 'facts', id, sourceId }, derivation.inputs);
const decision = published[i]?.decision;
@@ -498,17 +538,20 @@ export async function countConversationFacts(db: BrainEngine, sourceId: string,
return Number(row?.count ?? 0);
}
-export async function clearConversationFacts(db: BrainEngine, sourceId: string, slug: string): Promise<number> {
- const page = `f.source_id=$1 AND f.source_markdown_slug=$2 AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%'`;
+export async function clearConversationFacts(db: BrainEngine, sourceId: string, slug: string,
+ windows?: Pick<ConversationSegmentsPublication, 'keep' | 'retireUnanchored'>): Promise<number> {
+ const page = `f.source_id=$1 AND f.source_markdown_slug=$2 AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%'` + (windows
+ ? ` AND NOT (f.source = ANY($3::text[])) AND (CASE WHEN f.source_window IS NULL THEN $4::boolean ELSE NOT (${WINDOW_KEY_SQL} = ANY($5::text[])) END)` : '');
+ const params = windows ? [sourceId, slug, [...AUDIT_ROW_SOURCES], windows.retireUnanchored, [...windows.keep]] : [sourceId, slug];
const referenced = 'EXISTS (SELECT 1 FROM open_loops o WHERE o.fact_id=f.id) OR EXISTS (SELECT 1 FROM facts g WHERE g.superseded_by=f.id)';
- await db.executeRaw(`DELETE FROM facts f WHERE ${page} AND f.expired_at IS NOT NULL AND ${RELINKED_DERIVED_ROW} AND NOT (${referenced})`, [sourceId, slug]);
+ await db.executeRaw(`DELETE FROM facts f WHERE ${page} AND f.expired_at IS NOT NULL AND ${RELINKED_DERIVED_ROW} AND NOT (${referenced})`, params);
const [relinked] = await db.executeRaw<{ count: string }>(`WITH up AS (UPDATE facts f SET expired_at=now()
- WHERE ${page} AND f.expired_at IS NULL AND ${RELINKED_DERIVED_ROW} RETURNING 1) SELECT COUNT(*)::text AS count FROM up`, [sourceId, slug]);
+ WHERE ${page} AND f.expired_at IS NULL AND ${RELINKED_DERIVED_ROW} RETURNING 1) SELECT COUNT(*)::text AS count FROM up`, params);
const [expired] = await db.executeRaw<{ count: string }>(`WITH up AS (UPDATE facts f SET expired_at=now()
- WHERE ${page} AND f.expired_at IS NULL AND (${referenced}) RETURNING 1) SELECT COUNT(*)::text AS count FROM up`, [sourceId, slug]);
+ WHERE ${page} AND f.expired_at IS NULL AND (${referenced}) RETURNING 1) SELECT COUNT(*)::text AS count FROM up`, params);
const [deleted] = await db.executeRaw<{ count: string }>(`WITH del AS (DELETE FROM facts f
WHERE ${page} AND NOT (${referenced}) AND COALESCE(f.context,'') NOT LIKE '%${LABEL_RETIRED_MARKER}%' AND NOT (${RELINKED_DERIVED_ROW}) RETURNING 1)
- SELECT COUNT(*)::text AS count FROM del`, [sourceId, slug]);
+ SELECT COUNT(*)::text AS count FROM del`, params);
return Number(relinked?.count ?? 0) + Number(expired?.count ?? 0) + Number(deleted?.count ?? 0);
}
diff --git a/src/core/facts/conversation-window-extract.ts b/src/core/facts/conversation-window-extract.ts
new file mode 100644
index 0000000000..b17b750373
--- /dev/null
+++ b/src/core/facts/conversation-window-extract.ts
@@ -0,0 +1,156 @@
+/**
+ * One conversation window through the extractor (extract-conversation-facts, #6267 windows): the model call (or the
+ * injected extractor), save-time entity resolution and subject inference, and the fact rows the page publishes. Shared
+ * by the command's whole-page pass and the segmented page's per-occurrence pass (conversation-incremental.ts), with the
+ * page outcome rows both publish and the parser-input version token they bind to.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine, NewFact } from '../engine.ts';
+import type { Page } from '../types.ts';
+import { observationDateFrom, resolveObservationDate, type ObservationDate } from '../ai/date-grounding.ts';
+import { BudgetExhausted } from '../budget/budget-tracker.ts';
+import { deriveDateContext } from '../conversation-parser/parse.ts';
+import { resolveExtractedEntitiesForSave, type SaveTimeResolutionCounts } from '../entities/resolve-on-save.ts';
+import { NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUDIT_SOURCE, stampExtractorVersion } from './audit-sources.ts';
+import { CONVERSATION_ENTITY_HINTS_CAP } from './conversation-entity-hints.ts';
+import { CONVERSATION_FACTS_SOURCE_PREFIX, type ConversationFactRow } from './conversation-publication.ts';
+import { inferConversationSubjects } from './conversation-subject-infer.ts';
+import type { ConversationSegment } from './conversation-types.ts';
+import { extractFactsFromTurnWithOutcome, type ExtractInput, type ExtractedFact } from './extract.ts';
+import type { FactVisibility } from './visibility.ts';
+
+/** What one window's extraction needs from the run. */
+export interface ConversationWindowRun {
+ engine: BrainEngine;
+ sourceId: string;
+ factVisibility: FactVisibility;
+ signal: AbortSignal | undefined;
+ /** Injected per-segment extractor (BrainBench decision 15); undefined runs the production fail-hard extractor. */
+ extractor?: (input: ExtractInput) => Promise<ExtractedFact[]>;
+}
+
+/**
+ * A conversation fact's valid_from: a validated event date the extractor
+ * stated (date-grounding variant) wins; else the segment start, except the
+ * epoch fallback (no trustworthy date → the insert's now() default).
+ */
+function segmentValidFrom(extracted: Date | undefined, startIso: string | undefined): { valid_from?: Date } {
+ if (extracted) return { valid_from: extracted };
+ return startIso && !startIso.startsWith('1970-') ? { valid_from: new Date(startIso) } : {};
+}
+
+/**
+ * Observation date of a conversation segment (date-grounding.ts): the
+ * segment's own timestamp when it came from the transcript itself or the
+ * page's frontmatter date — never the synthetic epoch fallback, and never a
+ * timestamp the parser derived from effective_date (which may be an event
+ * date). Otherwise the page's observation date, or null (unknown).
+ */
+export function segmentObservationDate(page: Pick<Page, 'slug' | 'frontmatter' | 'effective_date'>, startIso: string | undefined): ObservationDate | null {
+ const day = startIso?.slice(0, 10);
+ const context = deriveDateContext({ page: page as Page });
+ const explicit = !!day && !day.startsWith('1970-')
+ && (context.source === 'explicit' || context.source === 'frontmatter_date' || day !== context.fallbackDate);
+ return explicit ? observationDateFrom(startIso) : resolveObservationDate({ slug: page.slug, frontmatter: page.frontmatter });
+}
+
+/**
+ * Extract one rendered window. The production path is fail-hard with a reason: a failed window aborts the page rather
+ * than dropping facts, and BudgetExhausted is rethrown unwrapped (#3669) so the run halts with a budget receipt.
+ * Rows are numbered from `rowNum`; publication renumbers them under the page lock.
+ */
+export async function extractConversationWindow(run: ConversationWindowRun, page: Page, seg: ConversationSegment, text: string, rowNum: number,
+ entityHints: ExtractInput['entityHints']): Promise<{ extracted: number; rows: ConversationFactRow[]; resolution: SaveTimeResolutionCounts }> {
+ const sessionId = `${CONVERSATION_FACTS_SOURCE_PREFIX}:${page.slug}`;
+ let extracted: ExtractedFact[];
+ const input: ExtractInput = { turnText: text, sessionId, source: CONVERSATION_FACTS_SOURCE_PREFIX, engine: run.engine, abortSignal: run.signal,
+ entityHints, entityHintsCap: CONVERSATION_ENTITY_HINTS_CAP };
+ if (run.extractor) {
+ extracted = await run.extractor(input);
+ } else {
+ const extraction = await extractFactsFromTurnWithOutcome({ ...input, observationDate: segmentObservationDate(page, seg.startIso) });
+ if (!extraction.ok) {
+ if (extraction.error instanceof BudgetExhausted) throw extraction.error;
+ const detail = extraction.error instanceof Error ? `: ${extraction.error.message}` : '';
+ throw Object.assign(new Error(`segment ${seg.startIso}..${seg.endIso} extraction failed (${extraction.reason})${detail}`),
+ { extractionReason: extraction.reason });
+ }
+ extracted = extraction.facts;
+ }
+ // This bulk path bypasses writeSingleFact and writes through insertFacts: every extractor-provided entity goes
+ // through the shipped resolver (alias_exact / prefix / fuzzy / slugify) while source scope is known.
+ const resolution = await resolveExtractedEntitiesForSave(run.engine, run.sourceId, extracted, (raw, message) => {
+ process.stderr.write(`[extract-conversation-facts] ${page.slug} segment ${seg.startIso}..${seg.endIso} `
+ + `entity resolution failed for ${JSON.stringify(raw)}: ${message}; preserving fact without an entity target\n`);
+ });
+ if (extracted.length === 0) return { extracted: 0, rows: [], resolution };
+ const rows = await inferConversationSubjects(run.engine, run.sourceId, run.factVisibility, extracted.map((fact, i) => ({ // #6764
+ ...fact, visibility: run.factVisibility,
+ row_num: rowNum + i,
+ source_markdown_slug: page.slug,
+ source: CONVERSATION_FACTS_SOURCE_PREFIX,
+ source_session: sessionId,
+ ...segmentValidFrom(fact.valid_from, seg.startIso),
+ context: fact.context ?? `from ${page.slug} segment ${seg.startIso}..${seg.endIso}`,
+ })));
+ return { extracted: extracted.length, rows, resolution };
+}
+
+/**
+ * The parser-input version token of a page read from its own body. content_hash covers title, type, compiled_truth,
+ * timeline, and frontmatter; unlike JavaScript Date, it cannot collapse distinct PostgreSQL updates within one
+ * millisecond. effective_date is parser input too.
+ */
+export function regularPageVersionToken(page: Page): string {
+ const hash = page.content_hash ?? createHash('sha256')
+ .update(JSON.stringify({
+ title: page.title,
+ type: page.type,
+ compiled_truth: page.compiled_truth,
+ timeline: page.timeline || '',
+ frontmatter: page.frontmatter || {},
+ }))
+ .digest('hex');
+ const effectiveDate = page.effective_date
+ ? new Date(page.effective_date).toISOString().slice(0, 10)
+ : 'none';
+ return `page-${hash}-${effectiveDate}`;
+}
+
+export function outcomeSession(source: string, slug: string, versionToken: string): string {
+ return `${source}:${slug}:${versionToken}`;
+}
+
+type OutcomeRow = NewFact & { row_num: number; source_markdown_slug: string };
+
+/** The page outcome of a complete extraction, bound to the parser-input version it read. */
+export function terminalAuditFact(slug: string, rowNum: number, versionToken: string): OutcomeRow {
+ return {
+ fact: 'EXTRACTION_COMPLETE',
+ kind: 'fact',
+ entity_slug: null,
+ source: TERMINAL_AUDIT_SOURCE,
+ source_session: outcomeSession(TERMINAL_AUDIT_SOURCE, slug, versionToken),
+ confidence: 1.0,
+ notability: 'low',
+ context: stampExtractorVersion(null),
+ row_num: rowNum,
+ source_markdown_slug: slug,
+ };
+}
+
+/** The durable not-extractable outcome: stops repeated scans of a page version with nothing to extract. */
+export function nonExtractableAuditFact(slug: string, rowNum: number, versionToken: string, reason: string): OutcomeRow {
+ return {
+ fact: 'EXTRACTION_NOT_APPLICABLE',
+ kind: 'fact',
+ entity_slug: null,
+ source: NON_EXTRACTABLE_AUDIT_SOURCE,
+ source_session: outcomeSession(NON_EXTRACTABLE_AUDIT_SOURCE, slug, versionToken),
+ confidence: 1.0,
+ notability: 'low',
+ context: stampExtractorVersion(`scanned, not extractable: ${reason}`),
+ row_num: rowNum,
+ source_markdown_slug: slug,
+ };
+}
diff --git a/src/core/page-body/segment-conversation.ts b/src/core/page-body/segment-conversation.ts
index 31e9f2f76e..5c08a53912 100644
--- a/src/core/page-body/segment-conversation.ts
+++ b/src/core/page-body/segment-conversation.ts
@@ -17,7 +17,7 @@
import type { BrainEngine } from '../engine.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import { readEntryState } from './entry-state.ts';
-import { openSegmentedBody, readBodyRange } from './read-range.ts';
+import { openSegmentedBody, readBodyRange, type BodyRow, type SegmentedBody } from './read-range.ts';
import { readGarbageCollector, segmentedPassWork } from './segment-blocks.ts';
import type { BodyRegion } from './types.ts';
@@ -78,3 +78,33 @@ export async function readSegmentedConversationInput(engine: BrainEngine, page:
const text = !truth ? timeline : !timeline ? truth : `${truth}\n\n${timeline}`;
return window ? { body: text, window } : { body: text };
}
+
+/** A live occurrence of a segmented page with the conversation context its entry state carries in (entry-state.ts). */
+export interface ConversationOccurrence { row: BodyRow; conversation: EntryStateConversation | null }
+type EntryStateConversation = { pattern: string | null; fallbackDate: string | null; lastDate: string | null; open: boolean };
+
+/**
+ * The live occurrences of a segmented page in parser-input order (truth, then timeline, as readSummaryBody joins them)
+ * with each one's conversation entry state: manifest metadata only, no segment text.
+ */
+export async function readConversationOccurrences(engine: BrainEngine, pageId: number): Promise<{ body: SegmentedBody; occurrences: ConversationOccurrence[] }> {
+ const body = await openSegmentedBody(engine, { pageId });
+ const states = new Map((await engine.executeRaw<{ seq: number; conversation: unknown }>(`SELECT seq, entry_state->'conversation' AS conversation
+ FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULL AND gen_from<=$2 AND (gen_to IS NULL OR gen_to>$2)`, [body.pageId, body.generation]))
+ .map(row => [Number(row.seq), (typeof row.conversation === 'string' ? JSON.parse(row.conversation) : row.conversation) as EntryStateConversation | null]));
+ const rows = [...body.rows.filter(row => row.region === 'truth'), ...body.rows.filter(row => row.region === 'timeline')];
+ return { body, occurrences: rows.map(row => ({ row, conversation: states.get(row.seq) ?? null })) };
+}
+
+/** One occurrence's trusted stored text: reads exactly its segment's bytes. */
+export async function readOccurrenceText(engine: BrainEngine, body: SegmentedBody, row: BodyRow): Promise<string> {
+ const collect = readGarbageCollector();
+ const parts: Buffer[] = [];
+ for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'stored', start: row.byteStart, end: row.byteStart + row.byteLen,
+ audience: 'trusted', region: row.region, body })) {
+ parts.push(piece.bytes);
+ segmentedPassWork.bytes += piece.bytes.length;
+ collect(piece.bytes.length);
+ }
+ return Buffer.concat(parts).toString('utf8');
+}
diff --git a/test/e2e/conversation-facts-incremental-postgres.test.ts b/test/e2e/conversation-facts-incremental-postgres.test.ts
new file mode 100644
index 0000000000..2fef346981
--- /dev/null
+++ b/test/e2e/conversation-facts-incremental-postgres.test.ts
@@ -0,0 +1,16 @@
+/**
+ * Incremental conversation facts on a segmented page, Postgres arm (wave-b spec 8.2, PR 4 lane 4b), including the
+ * facts.source_window double-encoding check (jsonb_typeof = 'object') PGLite can't catch. Cases:
+ * test/helpers/conversation-facts-incremental-cases.ts. PGLite arm: test/large-pages/conversation-facts-incremental.test.ts.
+ */
+import { afterAll, beforeAll, describe } from 'bun:test';
+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
+import { defineConversationFactsIncrementalCases } from '../helpers/conversation-facts-incremental-cases.ts';
+import { hasDatabase } from './helpers.ts';
+
+(hasDatabase() ? describe : describe.skip)('conversation facts incremental [postgres]', () => {
+ let brain: AppendBrain;
+ beforeAll(async () => { brain = await openAppendBrain('postgres'); }, 120_000);
+ afterAll(async () => { await brain.close(); }, 120_000);
+ defineConversationFactsIncrementalCases({ getBrain: () => brain });
+});
diff --git a/test/helpers/conversation-facts-incremental-cases.ts b/test/helpers/conversation-facts-incremental-cases.ts
new file mode 100644
index 0000000000..1542ed6058
--- /dev/null
+++ b/test/helpers/conversation-facts-incremental-cases.ts
@@ -0,0 +1,202 @@
+/**
+ * Incremental conversation facts on a segmented page (wave-b spec 8.2 "Conversation facts", PR 4 lane 4b), shared by
+ * the PGLite arm (test/large-pages/conversation-facts-incremental.test.ts) and the Postgres arm
+ * (test/e2e/conversation-facts-incremental-postgres.test.ts). A fake extractor counts calls by window text; no model
+ * is called. Spend is metered (reservePageSpend) but the fake call costs nothing.
+ *
+ * 1. Protects: an import extracts each window once and anchors every fact (facts.source_window, a JSONB object); an
+ * append (by a remote writer) extracts only windows no earlier run extracted, keeps the facts (same ids) of every
+ * window still live and deletes only the facts of windows that no longer exist; a title change re-extracts every
+ * window and a no-op extracts nothing; the per-page cap stops the run before a call, newest windows first, and a
+ * later run resumes without repeating a window; unanchored facts of an earlier full-pass run stay until every live
+ * occurrence is settled, then go.
+ * 2. Fails when: a run replays the whole page (the pre-PR-4 full pass), a fact loses its anchor or is double-encoded,
+ * an untouched window's fact is replaced, a retired window's fact survives, or a refused reservation still calls.
+ */
+import { expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { runExtractConversationFactsCore } from '../../src/commands/extract-conversation-facts.ts';
+import { parseSourceWindow, sourceWindowKey, type SourceWindow } from '../../src/core/page-body/derivations.ts';
+import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';
+import type { AppendBrain } from './append-brain.ts';
+
+const SPEAKERS = ['Alice Example', 'Bob Example', 'Carol Example'];
+const WORDS = ['launch', 'pricing', 'budget', 'roadmap', 'hiring', 'review', 'contract', 'latency', 'onboarding', 'forecast', 'retention', 'deploy'];
+const SOURCE = 'cli:extract-conversation-facts';
+
+const clock = (minutes: number) => { const h = 9 + Math.floor(minutes / 60); return `${h > 12 ? h - 12 : h}:${String(minutes % 60).padStart(2, '0')} ${h >= 12 ? 'PM' : 'AM'}`; };
+const dateOf = (day: number) => new Date(Date.UTC(2025, 0, 1) + day * 86_400_000).toISOString().slice(0, 10);
+
+/** Timed turns two minutes apart: one gap group per day. Deterministic per seed. */
+function turns(day: number, from: number, count: number, seed: number): string {
+ let s = seed * 7919 + day * 104_729 + from;
+ const next = () => { s = (s * 1103515245 + 12345) & 0x7fffffff; return s / 0x7fffffff; };
+ const out: string[] = [];
+ for (let t = from; t < from + count; t++) {
+ const words = Array.from({ length: 10 + Math.floor(next() * 30) }, () => WORDS[Math.floor(next() * WORDS.length)]);
+ out.push(`**${SPEAKERS[t % 3]}** (${clock(2 * t)}): ${words.join(' ')}.`);
+ }
+ return out.join('\n\n');
+}
+
+/** \`days\` dated days of 50 turns each, from day \`first\`. */
+export function chatDays(first: number, days: number, seed: number): string {
+ return Array.from({ length: days }, (_, i) => `## ${dateOf(first + i)}
+
+${turns(first + i, 0, 50, seed)}`).join('\n\n');
+}
+
+export const chatPage = (title: string, body: string) => `---
+type: conversation
+title: ${title}
+date: 2025-01-01
+---
+
+${body}
+`;
+const sha = (text: string) => createHash('sha256').update(text).digest('hex');
+
+interface FactRow { id: number; key: string; type: string }
+
+/** The page's live extractor facts (audit rows aside) with their window keys and the stored JSONB type. */
+async function factsOf(engine: BrainEngine, slug: string): Promise<FactRow[]> {
+ const rows = await engine.executeRaw<{ id: number; w: unknown; t: string | null }>(
+ `SELECT id, source_window AS w, jsonb_typeof(source_window) AS t FROM facts WHERE source_id='default' AND source_markdown_slug=$1 AND source=$2 AND expired_at IS NULL ORDER BY id`,
+ [slug, SOURCE]);
+ return rows.map(row => {
+ const window = parseSourceWindow(row.w) as SourceWindow | null;
+ return { id: Number(row.id), key: window ? sourceWindowKey(window) : 'unanchored', type: String(row.t) };
+ });
+}
+
+/** Window keys every live occurrence's derivation row records, and the rows' states and receipts. */
+async function derivations(engine: BrainEngine, slug: string) {
+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]);
+ const pageId = Number(page!.id);
+ const rows = await engine.readSegmentDerivations(pageId, { kind: 'conversation_facts' });
+ const live = await engine.readManifest(pageId);
+ const keys = rows.flatMap(row => ((row.output as { windows?: Array<{ ordinal: number; sha: string }> })?.windows ?? [])
+ .map(w => sourceWindowKey({ occurrence_id: row.occurrenceId, window_ordinal: w.ordinal, window_text_sha: w.sha })));
+ return { pageId, rows, keys, live: live.map(row => row.occurrenceId), states: rows.map(row => row.state), receipts: rows.map(row => row.receipt) };
+}
+
+/** One extraction run with a fake extractor; \`calls\` lists every window text it was handed, in call order. */
+async function extract(engine: BrainEngine, slug: string, opts: { force?: boolean } = {}) {
+ const calls: string[] = [];
+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [slug], sleepMs: 0, force: opts.force,
+ extractor: async input => {
+ calls.push(input.turnText);
+ return [{ fact: `Alice Example noted window ${sha(input.turnText).slice(0, 12)}`, kind: 'fact', entity_slug: null, source: SOURCE }];
+ } });
+ return { calls, result };
+}
+
+export function defineConversationFactsIncrementalCases(opts: { getBrain: () => AppendBrain }): void {
+ const slug = `notes/chat-incremental-${randomUUID().slice(0, 8)}`;
+ const BODY = chatDays(0, 100, 1);
+ const seen = new Set<string>();
+ let before: FactRow[] = [];
+
+ test('an import extracts every window exactly once and anchors every fact to its window', async () => {
+ const { engine, seed } = opts.getBrain();
+ await engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ await seed(slug, chatPage('Chat A', BODY));
+ const { calls, result } = await extract(engine, slug);
+ const facts = await factsOf(engine, slug);
+ const stored = await derivations(engine, slug);
+ expect(stored.live.length).toBeGreaterThan(2);
+ expect(calls.length).toBeGreaterThan(100);
+ expect({ distinct: new Set(calls).size, facts: facts.length, keys: stored.keys.length, processed: result.pages_processed })
+ .toEqual({ distinct: calls.length, facts: calls.length, keys: calls.length, processed: 1 });
+ expect(facts.filter(f => f.key === 'unanchored' || f.type !== 'object')).toEqual([]);
+ expect(new Set(facts.map(f => f.key))).toEqual(new Set(stored.keys));
+ expect(new Set(facts.map(f => f.key.split(':')[2]))).toEqual(new Set(calls.map(sha)));
+ expect({ rows: stored.rows.map(r => r.occurrenceId).sort(), states: [...new Set(stored.states)] })
+ .toEqual({ rows: [...stored.live].sort(), states: ['done'] });
+ for (const text of calls) seen.add(text);
+ before = facts;
+ }, 600_000);
+
+ test('an append by a remote writer extracts only the new windows, keeps every live window\'s fact and deletes the retired windows\' facts', async () => {
+ const brain = opts.getBrain();
+ const keysBefore = new Set((await derivations(brain.engine, slug)).keys);
+ // Twenty more turns on the last day (they join its last gap group) and three new days.
+ const appended = `${turns(99, 50, 20, 1)}
+
+${chatDays(100, 3, 1)}`;
+ expect(await brain.call('append_page', { slug, text: appended, request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });
+ const { calls } = await extract(brain.engine, slug);
+ const after = await derivations(brain.engine, slug);
+ const facts = await factsOf(brain.engine, slug);
+ const shasBefore = new Set([...keysBefore].map(key => key.split(':')[2]));
+ const fresh = after.keys.filter(key => !shasBefore.has(key.split(':')[2]));
+ expect(calls.filter(text => seen.has(text))).toEqual([]);
+ expect(calls.length).toBe(fresh.length);
+ expect(new Set(calls.map(sha))).toEqual(new Set(fresh.map(key => key.split(':')[2])));
+ expect(calls.length).toBeGreaterThanOrEqual(3);
+ expect(calls.length * 10).toBeLessThan(seen.size);
+ // A window still rendered verbatim keeps its fact (same id; a rewritten tail re-anchors it to its new occurrence);
+ // a window that no longer exists (the last window the appended turns joined) loses it.
+ const liveShas = new Set(after.keys.map(key => key.split(':')[2]));
+ const byId = new Map(facts.map(f => [f.id, f]));
+ const kept = before.filter(f => liveShas.has(f.key.split(':')[2]));
+ const retired = before.filter(f => !liveShas.has(f.key.split(':')[2]));
+ expect({ keptLost: kept.filter(f => byId.get(f.id)?.key.split(':')[2] !== f.key.split(':')[2]), retiredKept: retired.filter(f => byId.has(f.id)) })
+ .toEqual({ keptLost: [], retiredKept: [] });
+ expect(retired.length).toBeGreaterThanOrEqual(1);
+ expect(kept.length + retired.length).toBe(before.length);
+ expect({ facts: facts.length, anchored: facts.filter(f => f.type === 'object').length }).toEqual({ facts: after.keys.length, anchored: after.keys.length });
+ for (const text of calls) seen.add(text);
+ before = facts;
+ }, 600_000);
+
+ test('a title change re-extracts every window; a no-op rewrite and a forced rerun extract nothing', async () => {
+ const brain = opts.getBrain();
+ const body = (await brain.body(slug)).truth;
+ await brain.seed(slug, chatPage('Chat A', body));
+ const noop = await extract(brain.engine, slug);
+ const forced = await extract(brain.engine, slug, { force: true });
+ expect({ noop: noop.calls.length, forced: forced.calls.length, facts: (await factsOf(brain.engine, slug)).map(f => f.id) })
+ .toEqual({ noop: 0, forced: 0, facts: before.map(f => f.id) });
+ await brain.seed(slug, chatPage('Chat B', body));
+ const { calls } = await extract(brain.engine, slug);
+ const after = await derivations(brain.engine, slug);
+ const facts = await factsOf(brain.engine, slug);
+ const ids = new Set(before.map(f => f.id));
+ expect({ calls: calls.length, distinct: new Set(calls).size, facts: facts.length, survivors: facts.filter(f => ids.has(f.id)).length,
+ repeats: calls.filter(text => seen.has(text)).length })
+ .toEqual({ calls: after.keys.length, distinct: after.keys.length, facts: after.keys.length, survivors: 0, repeats: 0 });
+ expect(calls.every(text => text.startsWith('Page: Chat B\n'))).toBe(true);
+ }, 600_000);
+
+ test('the per-page cap refuses before the call, spends on the newest windows first, and a later run resumes without repeats', async () => {
+ const { engine, seed } = opts.getBrain();
+ const capped = `notes/chat-capped-${randomUUID().slice(0, 8)}`;
+ await engine.setConfig('facts.extraction_model', 'anthropic:claude-sonnet-4-6');
+ await seed(capped, chatPage('Chat C', chatDays(200, 100, 3)));
+ // A fact from an earlier full-pass run: no window anchor.
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, source, source_markdown_slug, row_num, confidence)
+ VALUES ('default', NULL, 'Bob Example owns the forecast', 'fact', 'private', 'medium', $2, $1, 5000, 0.9)`, [capped, SOURCE]);
+ const unanchored = async () => (await factsOf(engine, capped)).filter(f => f.key === 'unanchored').length;
+ await engine.setConfig(PAGE_EMBED_CAP_KEY, '0.3');
+ const first = await extract(engine, capped);
+ const partial = await derivations(engine, capped);
+ const [ledger] = await engine.executeRaw<{ spent: number }>('SELECT spent_usd AS spent FROM page_embedding_budget WHERE page_id=$1', [partial.pageId]);
+ expect(first.calls.length).toBeGreaterThanOrEqual(1);
+ expect(Number(ledger!.spent)).toBeLessThanOrEqual(0.3);
+ expect(Number(ledger!.spent)).toBeGreaterThan(0);
+ expect(partial.receipts.filter(Boolean)).toEqual([expect.objectContaining({ kind: 'unread_windows', reason: 'cap_reached' })]);
+ expect(await unanchored()).toBe(1);
+ // The newest windows: the last day's turns are in the first call.
+ expect(first.calls[0]).toContain(`${dateOf(299)}`);
+ await engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ const second = await extract(engine, capped);
+ const done = await derivations(engine, capped);
+ expect({ repeats: second.calls.filter(text => first.calls.includes(text)).length, total: first.calls.length + second.calls.length,
+ states: [...new Set(done.states)], facts: (await factsOf(engine, capped)).length, unanchored: await unanchored() })
+ .toEqual({ repeats: 0, total: done.keys.length, states: ['done'], facts: done.keys.length, unanchored: 0 });
+ expect(first.calls.length).toBeLessThan(done.keys.length);
+ await engine.setConfig('facts.extraction_model', '');
+ }, 600_000);
+}
diff --git a/test/large-pages/conversation-facts-incremental.test.ts b/test/large-pages/conversation-facts-incremental.test.ts
new file mode 100644
index 0000000000..af6c398f6a
--- /dev/null
+++ b/test/large-pages/conversation-facts-incremental.test.ts
@@ -0,0 +1,16 @@
+/**
+ * Incremental conversation facts on a segmented page, PGLite arm (wave-b spec 8.2, PR 4 lane 4b). Cases:
+ * test/helpers/conversation-facts-incremental-cases.ts. Postgres arm: test/e2e/conversation-facts-incremental-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe } from 'bun:test';
+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
+import { defineConversationFactsIncrementalCases } from '../helpers/conversation-facts-incremental-cases.ts';
+
+let brain: AppendBrain;
+
+beforeAll(async () => { brain = await openAppendBrain('pglite'); }, 120_000);
+afterAll(async () => { await brain.close(); }, 120_000);
+
+describe('conversation facts incremental [pglite]', () => {
+ defineConversationFactsIncrementalCases({ getBrain: () => brain });
+});
diff --git a/test/large-pages/segmented-conversation-facts.test.ts b/test/large-pages/segmented-conversation-facts.test.ts
index 147f184f2a..759551d2b3 100644
--- a/test/large-pages/segmented-conversation-facts.test.ts
+++ b/test/large-pages/segmented-conversation-facts.test.ts
@@ -1,29 +1,31 @@
/**
* Wave B PR 2 lane 2e2 (spec 8, full-pass mode): conversation facts read a
- * segmented page through ranged reads.
+ * segmented page through ranged reads. PR 4 lane 4b (spec 8.2) replaced the
+ * page's single parser input with per-occurrence windows
+ * (core/facts/conversation-incremental.ts; its append, retirement and spend
+ * cases live in conversation-facts-incremental.test.ts).
*
* 1. Protects:
* - a segmented conversation within the window cap gives the parser the
- * inline page's input, and extract-conversation-facts hands the
- * extractor the same windows;
+ * inline page's input (readConversationInput), and extract-conversation-facts
+ * hands the extractor exactly the windows each occurrence's own text
+ * yields: the inline page's rendered messages, cut at segment boundaries;
* - over the cap, readSegmentedConversationInput reads only the newest
* whole segments that fit, the window is the suffix of the summary body,
* it carries the day-header date in force there, and its parse is the
* suffix of the whole body's parse (the same speakers, texts and times);
- * - a page over the single-string ceiling with no conversation facts is
- * extracted from its newest window with a `tail_window` receipt
- * (`window_rule: no_prior_facts`) instead of skipped, reading at most
- * the window's bytes;
- * - one that already has conversation facts is skipped as in Wave A
- * (`skipped_too_large`, `window_rule: prior_facts_kept`): no extraction,
- * every fact, including those outside the window, is kept, and the
- * window is never read (no segment text fetched, 0 segment bytes).
+ * - a page over the single-string ceiling is extracted per occurrence,
+ * newest windows first, reading only the segment it extracts (at most
+ * SEGMENT_MAX_BYTES under --segment-limit 2), its partial-input receipt
+ * on the occurrence's derivation row instead of page_extraction_state;
+ * - such a run keeps the page's unanchored conversation facts (from
+ * earlier full-pass runs) untouched: a partial run never clears them.
* 2. Fails when: a segmented page reads its throwing body getters, the window
* is not the body's suffix or starts inside a forced run, its date context
- * is lost, a read exceeds the window, a window run clears facts it
- * cannot see, or a skipped page reads its window first.
+ * is lost, a window spans a segment cut, a read exceeds the segment, or a
+ * partial run clears facts it cannot see.
* 3. Why existing coverage misses it: conversation-facts tests use inline pages.
- * Seams: `segmentedPassWork.bytes` counts bytes read; a readSegmentTexts spy wraps the engine method.
+ * Seams: `segmentedPassWork.bytes` counts bytes read.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
@@ -40,6 +42,8 @@ import { CONVERSATION_WINDOW_BYTES, readSegmentedConversationInput } from '../..
import { segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';
import { materializedPage } from '../../src/core/persistence/segmented-apply.ts';
import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
+import { renderSegmentForExtraction, splitIntoSegments } from '../../src/core/facts/conversation-windows.ts';
import { withoutBody } from '../../src/core/page-body/page-shape.ts';
import type { Page } from '../../src/core/types.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
@@ -107,6 +111,7 @@ const receiptOf = async (engine: BrainEngine, pageId: number) => (await engine.e
/** Every extractor input of one run over `slug`, with the run's counts. */
async function extraction(engine: BrainEngine, slug: string) {
await engine.executeRaw('DELETE FROM facts WHERE source_markdown_slug=$1', [slug]);
+ await engine.executeRaw("DELETE FROM page_segment_derivations WHERE page_id IN (SELECT id FROM pages WHERE source_id='default' AND slug=$1)", [slug]);
const inputs: unknown[] = [];
const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [slug], sleepMs: 0, force: true,
extractor: async input => {
@@ -118,7 +123,7 @@ async function extraction(engine: BrainEngine, slug: string) {
}
describe('conversation facts over a segmented page (full-pass mode)', () => {
- test('within the cap: the parser input and the extractor windows match the inline page', async () => {
+ test('within the cap: the parser input matches the inline page; the extractor windows are the inline windows cut at the segment boundaries', async () => {
for (const engine of engines) {
const seg = await stored(engine, 'conversations/chat-segmented');
expect(seg.body_storage).toBe('segmented');
@@ -133,7 +138,29 @@ describe('conversation facts over a segmented page (full-pass mode)', () => {
const a = await extraction(engine, 'conversations/chat-inline');
const b = await extraction(engine, 'conversations/chat-segmented');
expect(a.inputs.length).toBeGreaterThan(10);
- expect(b).toEqual(a);
+ // PR 4 (wave-b spec 8.2): a segmented page's windows are packed inside one occurrence and never span a cut.
+ // Exactly the windows each occurrence's own text yields, read here from the materialized body.
+ const manifest = await engine.readManifest(seg.id);
+ const truth = Buffer.from((await materializedPage(engine, seg)).compiled_truth, 'utf8');
+ const pageArg = { ...withoutBody(seg), compiled_truth: '', timeline: '' } as Page;
+ const expected = manifest.flatMap(row => {
+ const fallbackDate = (row.entryState as { conversation?: { fallbackDate?: string | null } }).conversation?.fallbackDate ?? undefined;
+ const text = truth.subarray(row.byteStart, row.byteStart + row.byteLen).toString('utf8');
+ const messages = parseConversation(text, { page: pageArg, ...(fallbackDate ? { fallbackDate } : {}) }).messages;
+ return splitIntoSegments(messages, { pageTitle: 'Chat' }).map(window => renderSegmentForExtraction('Chat', window));
+ });
+ const texts = (r: typeof b) => r.inputs.map(input => (input as { turnText: string }).turnText);
+ expect(manifest.length).toBeGreaterThan(2);
+ expect([...texts(b)].sort()).toEqual([...expected].sort());
+ // The same rendered messages as the inline page, less only the turns a cut leaves alone in their gap group.
+ const lines = (r: typeof b) => texts(r).flatMap(text => text.split('\n---\n')[1]!.split('\n'));
+ const inlineLines = new Map<string, number>();
+ for (const line of lines(a)) inlineLines.set(line, (inlineLines.get(line) ?? 0) + 1);
+ for (const line of lines(b)) { expect(inlineLines.get(line) ?? 0).toBeGreaterThan(0); inlineLines.set(line, inlineLines.get(line)! - 1); }
+ expect(lines(a).length - lines(b).length).toBeLessThanOrEqual(2 * (manifest.length - 1));
+ const fixed = (r: typeof b) => r.inputs.map(input => ({ ...(input as Record<string, unknown>), turnText: undefined }));
+ expect(new Set(fixed(b).map(input => JSON.stringify(input)))).toEqual(new Set([JSON.stringify(fixed(a)[0])]));
+ expect({ processed: b.processed, segments: b.segments, tooLarge: b.tooLarge }).toEqual({ processed: 1, segments: expected.length, tooLarge: 0 });
}
}, 600_000);
@@ -173,68 +200,57 @@ describe('conversation facts over a segmented page (full-pass mode)', () => {
}
}, 300_000);
- test('a page over the single-string ceiling with no conversation facts is extracted from its newest window with a tail_window receipt, reading at most the window', async () => {
+ test('a page over the single-string ceiling is extracted per occurrence, newest windows first, reading only the occurrence it extracts', async () => {
for (const engine of engines) {
await engine.setConfig('pages.segmented_storage', 'on');
const file = join(dir, 'huge.md');
- writeFileSync(file, page('Huge', chat(PAGE_MAX_BYTES + 2 * 1024 * 1024, 11)));
+ const body = chat(PAGE_MAX_BYTES + 2 * 1024 * 1024, 11);
+ writeFileSync(file, page('Huge', body));
expect(await importFromFile(engine, file, 'conversations/huge.md', { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) }))
.toMatchObject({ status: 'imported' });
const huge = await stored(engine, 'conversations/huge');
expect(Number(huge.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);
const before = segmentedPassWork.bytes;
- let calls = 0;
- let last = '';
+ const texts: string[] = [];
const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: ['conversations/huge'], sleepMs: 0, segmentLimit: 2,
- extractor: async input => { calls++; last = input.turnText; return []; } });
- expect(result.pages_skipped_too_large).toBe(0);
- expect(calls).toBeGreaterThan(0);
- expect(last.length).toBeGreaterThan(0);
- // One snapshot read of the window, plus the version-token recheck.
- expect(segmentedPassWork.bytes - before).toBeLessThanOrEqual(2 * CONVERSATION_WINDOW_BYTES);
- expect(await receiptOf(engine, huge.id)).toMatchObject({ kind: 'tail_window', pipeline: 'conversation_facts', total_bytes: Number(huge.body_bytes),
- cap_bytes: CONVERSATION_WINDOW_BYTES, origin: 'page', window_rule: 'no_prior_facts' });
+ extractor: async input => { texts.push(input.turnText); return []; } });
+ expect({ tooLarge: result.pages_skipped_too_large, calls: texts.length }).toEqual({ tooLarge: 0, calls: 2 });
+ // One segment read (the newest occurrence's), never the 24 MiB window.
+ expect(segmentedPassWork.bytes - before).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);
+ expect(texts[0]).toContain([...body.matchAll(/^## (\d{4}-\d{2}-\d{2})$/gm)].at(-1)![1]);
+ // The partial-input receipt moved to the occurrence's derivation row.
+ expect(await receiptOf(engine, huge.id)).toBeUndefined();
+ const rows = await engine.readSegmentDerivations(huge.id, { kind: 'conversation_facts' });
+ expect(rows.map(row => ({ state: row.state, receipt: row.receipt }))).toEqual([{ state: 'partial',
+ receipt: expect.objectContaining({ kind: 'unread_windows', pipeline: 'conversation_facts', reason: 'segment_limit', windows_read: 2 }) }]);
}
}, 1_800_000);
- test('a page over the window that already has conversation facts keeps every one: skipped_too_large naming the rule, no extraction, nothing cleared, the window never read', async () => {
+ test('a page over the window keeps its unanchored conversation facts while a partial run extracts its newest windows', async () => {
const outcomes: unknown[] = [];
const expected: unknown[] = [];
for (const [index, engine] of engines.entries()) {
const huge = await stored(engine, 'conversations/huge');
- // Facts from the head, which the newest window cannot see.
+ await engine.executeRaw('DELETE FROM page_segment_derivations WHERE page_id=$1', [huge.id]);
+ // Facts from the head, which no window this run extracts can see.
for (const [rowNum, fact] of [[1000, 'Alice Example chose the launch budget'], [1001, 'Bob Example owns the roadmap review']] as const) {
await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, source, source_markdown_slug, row_num, confidence, context)
VALUES ('default', 'conversations/huge', $1, 'fact', 'private', 'medium', 'cli:extract-conversation-facts', 'conversations/huge', $2, 0.9,
'from conversations/huge segment 2025-01-01T09:00:00Z..2025-01-01T11:00:00Z')`, [fact, rowNum]);
}
const facts = () => engine.executeRaw<Record<string, unknown>>(`SELECT id, fact, source, row_num, context, expired_at FROM facts
- WHERE source_id='default' AND source_markdown_slug='conversations/huge' ORDER BY id`);
+ WHERE source_id='default' AND source_markdown_slug='conversations/huge' AND source_window IS NULL ORDER BY id`);
const before = await facts();
expect(before.filter(row => row.source === 'cli:extract-conversation-facts')).toHaveLength(2);
let calls = 0;
- // The window is never read: no segment text is fetched and no segment byte counted.
- const original = engine.readSegmentTexts.bind(engine);
- let segmentReads = 0;
- engine.readSegmentTexts = (async (sourceId: string, shas: Uint8Array[]) => { segmentReads += shas.length; return original(sourceId, shas); }) as BrainEngine['readSegmentTexts'];
const bytesBefore = segmentedPassWork.bytes;
- let result: Awaited<ReturnType<typeof runExtractConversationFactsCore>>;
- try {
- result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: ['conversations/huge'], sleepMs: 0, segmentLimit: 2, force: true,
- extractor: async () => { calls++; return [{ fact: 'Carol Example ships the forecast', kind: 'fact', entity_slug: null, source: 'cli:extract-conversation-facts' }]; } });
- } finally {
- // The spy is an own property; deleting it restores the prototype method.
- delete (engine as { readSegmentTexts?: unknown }).readSegmentTexts;
- }
- const bytesRead = segmentedPassWork.bytes - bytesBefore;
- const receipt = await receiptOf(engine, huge.id);
- outcomes.push({ engine: index, calls, segmentReads, bytesRead, skipped: result.pages_skipped_too_large, processed: result.pages_processed,
- factsKept: Bun.deepEquals(await facts(), before),
- receipt: { kind: receipt?.kind, processed_chars: receipt?.processed_chars, total_bytes: receipt?.total_bytes, cap_bytes: receipt?.cap_bytes,
- window_rule: receipt?.window_rule, prior_facts: receipt?.prior_facts } });
- expected.push({ engine: index, calls: 0, segmentReads: 0, bytesRead: 0, skipped: 1, processed: 0, factsKept: true,
- receipt: { kind: 'skipped_too_large', processed_chars: 0, total_bytes: Number(huge.body_bytes), cap_bytes: CONVERSATION_WINDOW_BYTES,
- window_rule: 'prior_facts_kept', prior_facts: 2 } });
+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: ['conversations/huge'], sleepMs: 0, segmentLimit: 2, force: true,
+ extractor: async () => { calls++; return [{ fact: `Carol Example ships the forecast ${calls}`, kind: 'fact', entity_slug: null, source: 'cli:extract-conversation-facts' }]; } });
+ const [anchored] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/huge'
+ AND source_window IS NOT NULL AND jsonb_typeof(source_window)='object'`);
+ outcomes.push({ engine: index, calls, readWithinSegment: segmentedPassWork.bytes - bytesBefore <= SEGMENT_MAX_BYTES, skipped: result.pages_skipped_too_large,
+ unanchoredKept: Bun.deepEquals(await facts(), before), anchored: Number(anchored!.n), receipt: await receiptOf(engine, huge.id) });
+ expected.push({ engine: index, calls: 2, readWithinSegment: true, skipped: 0, unanchoredKept: true, anchored: 2, receipt: undefined });
}
expect(outcomes).toEqual(expected);
}, 900_000);