Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(large-pages): PR 4 4b round 5: one deletion invariant for conversation facts, whole-page grammar detection, unpriced-model receipts
garrytan59106875f838
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 554d4ab62b..ea276f71a6 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 1889 ratchet grown v0.46.x per-providsrc/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 measuredsrc/commands/jobs.ts 667 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; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts)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)-src/core/ai/gateway.ts 4532 ratchet +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for; +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts)+src/core/ai/gateway.ts 4533 ratchet +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for; +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts); +1 PR 4 (Wave B incremental derivation, transcripts) 4b round 5: an embed inside a metered page step takes its providerRetries as maxRetries too, so the synopsis step books every attempt it reserved forsrc/commands/sync.ts 548 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor enginesrc/core/cycle.ts 3332 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left duesrc/core/cycle/synthesize.ts 3230 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites)diff --git a/src/commands/doctor/checks/derivation-pricing.ts b/src/commands/doctor/checks/derivation-pricing.tsnew file mode 100644index 0000000000..a0075c8096--- /dev/null+++ b/src/commands/doctor/checks/derivation-pricing.ts@@ -0,0 +1,50 @@+/**+ * derivation_unpriced_model (PR 4, Wave B incremental derivation): segmented pages whose paid derivation (facts,+ * conversation facts, atoms, synopsis) stopped or booked its whole reservation because the model has no price. An+ * unpriced model reserves a ceiling estimate (no default changes and no price is invented), so under the per-page cap it+ * gets about one window per page and every call books that ceiling. The receipts on page_segment_derivations say so+ * (reason or kind `unpriced_model`, with the model; unpricedModelReceipt); this check groups them by model and names+ * the fix: register the model's price in `pricing.overrides`; a model priced since is not reported. Reads the database only.+ */+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { loadPricingOverrides } from '../../../core/budget/budget-tracker.ts';+import { reservationCostUsd } from '../../../core/budget/reservation-cost.ts';++/** The command that registers `model`'s price in pricing.overrides (src/commands/pricing.ts merges it into the existing map). */+export const pricingCommand = (model: string) => ['gbrain', 'pricing', 'set', model, '--input', '<inputUsdPer1M>', '--output', '<outputUsdPer1M>', '--source', '<pricingPageUrl>'];++async function runDerivationUnpricedModelCheck(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const rows = await connectedEngine(ctx).executeRaw<{ model: string; pipelines: string[]; pages: number; samples: string[] }>(+ `SELECT d.receipt->>'model' AS model, array_agg(DISTINCT d.pipeline ORDER BY d.pipeline) AS pipelines, count(DISTINCT d.page_id)::int AS pages,+ (array_agg(DISTINCT p.source_id || ':' || p.slug))[1:3] AS samples+ FROM page_segment_derivations d JOIN pages p ON p.id = d.page_id AND p.deleted_at IS NULL+ WHERE (d.receipt->>'kind' = 'unpriced_model' OR d.receipt->>'reason' = 'unpriced_model') AND d.receipt->>'model' IS NOT NULL+ GROUP BY 1 ORDER BY 3 DESC, 1`);+ // A model priced since (pricing.overrides) no longer holds anything back: the next run meters it.+ const overrides = await loadPricingOverrides(connectedEngine(ctx));+ const models = rows.filter(r => reservationCostUsd(r.model, 'chat', 1, 1, overrides) === null).map(r => ({ model: r.model, pipelines: r.pipelines ?? [], pages: Number(r.pages), samples: r.samples ?? [], fix: pricingCommand(r.model).join(' ') }));+ if (!models.length) {+ checks.push({ name: 'derivation_unpriced_model', status: 'ok', message: 'No segmented page derivation is held back by a model without a price.', details: { models } });+ return checks;+ }+ const message = `Paid page derivations ran a model with no price, so each call reserved and booked a ceiling estimate and the per-page cap stopped them early: `+ + models.map(m => `${m.model} (${m.pipelines.join(', ')}; ${m.pages} page(s), e.g. ${m.samples.join(', ')}): ${m.fix}`).join('. ')+ + '. Each command writes the model\'s price to pricing.overrides; the next run meters at that price and resumes where it stopped.';+ checks.push({ name: 'derivation_unpriced_model', status: 'warn', message, details: { models },+ fix: agentFix(pricingCommand(models[0]!.model),+ `Registers ${models[0]!.model}'s price in pricing.overrides so its derivations reserve and book its real cost instead of the unpriced ceiling; the rates come from the provider's pricing page, so they are the user's to confirm.`,+ 'derivation_unpriced_model', { ask_user: true, inputs: [+ { name: 'inputUsdPer1M', how: 'the provider\'s published input price per million tokens, confirmed with the user' },+ { name: 'outputUsdPer1M', how: 'the provider\'s published output price per million tokens, confirmed with the user' },+ { name: 'pricingPageUrl', how: 'the provider pricing page the rates come from' }] }) });+ } catch (error) {+ checks.push(checkError('derivation_unpriced_model', 'read the derivation receipts', error, { details: { health: 'unknown' } }));+ }+ return checks;+}++export const derivationUnpricedModelEntry: DoctorEntry = { name: 'derivation_unpriced_model', emits: ['derivation_unpriced_model'], run: runDerivationUnpricedModelCheck };diff --git a/src/commands/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.tsindex 960d80e2ba..8d585fbfae 100644--- a/src/commands/doctor/checks/extraction-input.ts+++ b/src/commands/doctor/checks/extraction-input.ts@@ -17,8 +17,9 @@* a conversation window whose extraction failed run after run was skipped, and its* sample names the window). Both tables* are read; a page counts once per pipeline and receipt kind. A derivation receipt- * without a `kind` (the synopsis pass's tier fallback or refused reservation) is- * not an input-truncation receipt and is not counted.+ * without a `kind` (the synopsis pass's tier fallback or refused reservation), or of+ * kind `unpriced_model` (doctor derivation_unpriced_model), is not an input-truncation+ * receipt and is not counted.*/import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';@@ -39,7 +40,7 @@ const UNREAD_REMEDY = `the run stopped before every window of the page was readconst FAILED_WINDOWS = 'failed_windows';const FAILED_REMEDY = 'a conversation window failed to extract in run after run and is skipped, so the older windows still get extracted (the sample names the window, its receipt the last error); fix the cause, then gbrain extract-conversation-facts --slug <slug> --force tries it again';const NO_MESSAGES = 'no_messages';-const NO_MESSAGES_REMEDY = 'the last run parsed no message from parts of the page that had conversation windows (a changed transcript format, or a parser fault), so it kept their facts and settled nothing; check that the page still reads as a conversation, then gbrain extract-conversation-facts --slug <slug>';+const NO_MESSAGES_REMEDY = 'the page reads as a transcript format over its whole text, yet no message parsed under that format (a conversation parser fault), so the last run changed nothing and kept its facts; rerunning repeats this, so report it with gbrain doctor --json and the page\'s format (a page that is not a transcript settles as non-extractable instead)';const remedy = (g: ReceiptGroup): string | null => g.kind === UNREAD_WINDOWS ? UNREAD_REMEDY : g.kind === FAILED_WINDOWS ? FAILED_REMEDY: g.kind === NO_MESSAGES ? NO_MESSAGES_REMEDY : REMEDY[g.pipeline] ?? null;@@ -56,7 +57,7 @@ async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<CheUNION ALLSELECT d.page_id, d.pipeline, COALESCE(d.receipt->>'kind', 'unknown') AS kind, max(d.updated_at) AS updated_at,min(CASE WHEN d.receipt->>'kind' = '${FAILED_WINDOWS}' THEN ' window ' || (d.receipt->'windows'->0->>'ordinal') || ' of occurrence ' || d.occurrence_id END) AS detail- FROM page_segment_derivations d WHERE d.receipt->>'kind' IS NOT NULL GROUP BY 1, 2, 3)+ FROM page_segment_derivations d WHERE d.receipt->>'kind' IS NOT NULL AND d.receipt->>'kind' <> 'unpriced_model' GROUP BY 1, 2, 3)SELECT r.pipeline, r.kind, count(DISTINCT r.page_id)::int AS pages,(array_agg(p.source_id || ':' || p.slug || COALESCE(r.detail, '') ORDER BY r.updated_at DESC))[1:3] AS samplesFROM receipts r JOIN pages p ON p.id = r.page_id AND p.deleted_at IS NULLdiff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 567a6a7615..cd599736ca 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -135,6 +135,7 @@ import { managedSyncBlockedEntry } from './checks/managed-sync-blocked.ts';import { syncAdmissionEntry } from './checks/sync-admission.ts';import { atomHeldFailedEntry } from './checks/atom-holds.ts';import { extractionInputTruncatedEntry } from './checks/extraction-input.ts';+import { derivationUnpricedModelEntry } from './checks/derivation-pricing.ts'; // PR 4 (Wave B incremental derivation, transcripts)import {persistenceCapacityEntry,terminalFailuresEntry,@@ -260,6 +261,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [persistenceConsumersEntry,atomHeldFailedEntry,extractionInputTruncatedEntry,+ derivationUnpricedModelEntry,ghostPagesEntry,originTwinsEntry,renameIdentityDowngradesEntry,diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 45f61db566..ddfad53354 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -1766,6 +1766,7 @@ async function embedSubBatch(opts?: EmbedOpts,): Promise<{ embeddings: Float32Array[]; reportedTokens: number | null }> {try {+ const maxRetries = hasAIInvocationGuard() ? 0 : opts?.maxRetries ?? __budgetStore.getStore()?.providerRetries; // PR 4 (Wave B incremental derivation, transcripts): an embed in a metered page step makes only the attempts it reserved forconst callTransport = () => invokeAI({ operation: 'gateway.embed', kind: 'embedding', model: `${recipe.id}:${modelId}`,maxInputTokens: embedRequestMaxInputTokens(texts, recipe, modelId), maxOutputTokens: 0, estimatedInputTokens: Math.ceil(texts.reduce((n, text) => n + text.length, 0) / (recipe.touchpoints.embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN)) }, () => _embedTransport({model,@@ -1776,7 +1777,7 @@ async function embedSubBatch(// per-SDK-call scope). Composes with a caller signal (Fix 3's 6s query// deadline) — shorter wins.abortSignal: withDefaultTimeout(opts?.abortSignal, AI_EMBED_TIMEOUT_MS),- ...(hasAIInvocationGuard() ? { maxRetries: 0 } : opts?.maxRetries !== undefined ? { maxRetries: opts.maxRetries } : {}),+ ...(maxRetries !== undefined ? { maxRetries } : {}),}), sdkInvocationUsage, err => isTokenLimitError(err) || isUnbilledEmbeddingRejection(recipe.id, err) ? { inputTokens: 0, outputTokens: 0 } : null);// Carry the threaded input_type across the SDK boundary via// __embedInputTypeStore (the adapter strips it from providerOptions —diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex e9b73776a2..cfe6f38b5a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1063,8 +1063,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// PR 4 4b{ since: 'TBD', text: 'Appending to a long conversation now re-extracts facts only for the new messages.' },{ since: 'TBD', text: 'Atom extraction now covers very large pages, and after an append reads only the new text.' },- { since: 'TBD', text: 'Fact, atom and synopsis extraction on a large page now each have their own per-page spend cap, `derive.max_usd_per_page` (default $2 per kind over the page\'s lifetime; unlimited under `spend.posture tokenmax` when unset; `off` disables it), separate from `embed.max_usd_per_page`, which now counts embeddings only, so extraction never uses up a page\'s embedding budget and a new embedding model does not reset extraction spend. Each call reserves its worst case (every retry) and books what the provider reported; a call that failed after the provider answered is still booked, a call the provider may have billed (a timeout, an abort, a dropped connection, a server or gateway error, each retry the provider SDK made) books its worst case, and only one the provider refused outright (a rate limit, an auth or request error, with no usage reported) or a failed embedding books nothing; metered calls turn the SDK\'s hidden retries off. Doctor lists the pages a cap stopped.' },- { since: 'TBD', text: 'A conversation window whose fact extraction fails for a reason of its own (malformed or truncated output, a refusal, input too long) in three runs in a row is now skipped with a receipt, so the older windows of the page still get extracted, and the facts it had before stay; provider outages, auth errors and rate limits never count. `gbrain doctor` names the window and `gbrain extract-conversation-facts --slug <slug> --force` tries it again. A run that reads no message where a large conversation page had them (a changed format) keeps every fact and leaves a receipt doctor lists, instead of clearing the page.' },+ { since: 'TBD', text: 'Fact, atom and synopsis extraction on a large page now each have their own per-page spend cap, `derive.max_usd_per_page` (default $2 per kind over the page\'s lifetime; unlimited under `spend.posture tokenmax` when unset; `off` disables it), separate from `embed.max_usd_per_page`, which now counts embeddings only, so extraction never uses up a page\'s embedding budget and a new embedding model does not reset extraction spend. Each call reserves its worst case (every retry) and books what the provider reported; a call that failed after the provider answered is still booked, a call the provider may have billed (a timeout, an abort, a dropped connection, a server or gateway error, each retry the provider SDK made) books its worst case, and only one the provider refused outright (a rate limit, an auth or request error, with no usage reported) or a failed embedding books nothing; metered calls, the synopsis step\'s embedding included, turn the SDK\'s hidden retries off. Doctor lists the pages a cap stopped. A model with no price still reserves its ceiling estimate (about one window per page at the default cap; no default changed and no price is assumed), and its receipt now says `unpriced_model` with the model; doctor `derivation_unpriced_model` warns and names the fix, `gbrain pricing set <model> --input <usd> --output <usd>`, which writes `pricing.overrides`.' },+ { since: 'TBD', text: 'A conversation window whose fact extraction fails for a reason of its own (malformed or truncated output, a refusal, input too long) in three runs in a row is now skipped with a receipt, so the older windows of the page still get extracted, and the facts it had before stay; provider outages, auth errors and rate limits never count. `gbrain doctor` names the window and `gbrain extract-conversation-facts --slug <slug> --force` tries it again. Incremental runs on a large conversation page only add or replace facts window by window; facts are removed only when their exact window is extracted again or when a run finishes the whole page with no failed window, no cap, no window limit and no `--since`, which then clears the facts of windows no longer on the page. The page\'s chat format is detected over the whole page (not its first 64 KB) whenever it is not already known; a page that is no longer a transcript is marked non-extractable and its conversation facts are cleared, even under `--force`; only a page that reads as a transcript yet parses no message keeps every fact and leaves a receipt doctor lists.' },// PR 4 (Wave B incremental derivation, transcripts) — 4c, contextual synopsis per segment. `since` is restamped at the merge slot.{ since: 'TBD', text: 'With contextual retrieval set to `per_chunk_synopsis`, a page stored in segments now gets per-chunk synopses instead of staying on the title tier: each chunk\'s synopsis reads the page title, the first 8 KiB of the page and up to 32 KB of its own segment, so the contextual re-embed (`gbrain reindex --markdown` and the per-chunk synopsis backfill) re-synopsizes only the segments an append or edit rewrote and leaves every other chunk\'s vector as it is. The page\'s synopsis cap (`derive.max_usd_per_page`) bounds the synopsis calls: when it is reached, the rest of the page keeps its title-tier vectors (`budget_limited`) and nothing more is spent. A chunk whose synopsis the model refuses is embedded at the title tier. After `gbrain reindex --segmented --apply` re-chunks a page, the next pass synopsizes its new chunks. Pages read whole are unchanged.' },// PR 4 (Wave B incremental derivation, transcripts)diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex 448d7404ac..62880bc227 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -552,6 +552,7 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promilet embedded = 0;let fallbackKind: SynopsisFailureKind | null = null;+ let unpricedModel: string | null = null;for (const segment of plan.todo) {await using lease = await acquirePageEmbeddingLease(engine, page.id, { signal: args.abortSignal });if (lease.busy) return { kind: 'transient_error', cause: 'db', detail: pageEmbeddingLeaseUnavailable(page.id, false).message };@@ -577,8 +578,10 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promireturn classifyEmbedError(err, err instanceof Error ? err.message : String(err));}});+ unpricedModel = metered.unpricedModel ?? unpricedModel;if ('refused' in metered) {- await derivation(segment, 'partial', anchors, { reason: 'budget_limited', cap_usd: metered.refused.capUsd, estimate_usd: metered.refused.estimateUsd });+ await derivation(segment, 'partial', anchors, { reason: unpricedModel ? 'unpriced_model' : 'budget_limited', ...(unpricedModel ? { model: unpricedModel } : {}),+ cap_usd: metered.refused.capUsd, estimate_usd: metered.refused.estimateUsd });return { kind: 'skipped', reason: 'budget_limited' };}const built = metered.value;@@ -598,7 +601,8 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promiif (built.fallback) segmentFallback ??= built.fallback;anchors.push({ ...anchor, tier: built.tier });}- await derivation(segment, 'done', anchors, segmentFallback ? { fallback_kind: segmentFallback } : null);+ await derivation(segment, 'done', anchors, segmentFallback || unpricedModel+ ? { ...(unpricedModel ? { kind: 'unpriced_model', pipeline: 'synopsis', model: unpricedModel } : {}), ...(segmentFallback ? { fallback_kind: segmentFallback } : {}) } : null);fallbackKind ??= segmentFallback;}await engine.retireSegmentDerivations(page.id, live.map(s => s.occurrenceId), { kind: 'synopsis' });diff --git a/src/core/conversation-parser/normalize-block.ts b/src/core/conversation-parser/normalize-block.tsindex b5165cd0f2..d8ce7c9690 100644--- a/src/core/conversation-parser/normalize-block.ts+++ b/src/core/conversation-parser/normalize-block.ts@@ -53,42 +53,54 @@ function to24h(hour: number, ampm?: string): number {}/**- * Collapse block-format messages into canonical single-line `**Name** (HH:MM):- * body` lines. Returns `body` unchanged when no block header is present.+ * normalizeBlockConversation one line at a time: `emit` gets each collapsed message line once the message ends (the next+ * header, or `end()`); `headers` counts the block headers seen. Lines before the first header are dropped.*/-export function normalizeBlockConversation(body: string): string {- if (!looksLikeBlockConversation(body)) return body;-- const lines = body.split('\n');- const out: string[] = [];+export function blockNormalizer(emit: (line: string) => void): { line(line: string): void; end(): void; readonly headers: number } {let current: { name: string; time: string } | null = null;let bodyParts: string[] = [];+ let headers = 0;const flush = () => {if (current) {const text = bodyParts.join(' ').replace(/\s+/g, ' ').trim();- out.push(`**${current.name}** (${current.time}): ${text}`);+ emit(`**${current.name}** (${current.time}): ${text}`);}current = null;bodyParts = [];};- for (const line of lines) {- const m = BLOCK_HEADER.exec(line);- if (m) {- flush();- const hour = to24h(parseInt(m[2], 10), m[4]);- const time = `${String(hour).padStart(2, '0')}:${m[3]}`;- current = { name: m[1].trim(), time };- } else if (current) {- // Body line of the current message. Drop blank lines; keep the rest.- const trimmed = line.trim();- if (trimmed) bodyParts.push(trimmed);- }- // Lines before the first header (page title, leading blanks) are dropped —- // they never matched a pattern anyway.- }- flush();+ return {+ get headers() { return headers; },+ line(line: string) {+ const m = BLOCK_HEADER.exec(line);+ if (m) {+ flush();+ headers++;+ const hour = to24h(parseInt(m[2], 10), m[4]);+ const time = `${String(hour).padStart(2, '0')}:${m[3]}`;+ current = { name: m[1].trim(), time };+ } else if (current) {+ // Body line of the current message. Drop blank lines; keep the rest.+ const trimmed = line.trim();+ if (trimmed) bodyParts.push(trimmed);+ }+ // Lines before the first header (page title, leading blanks) are dropped —+ // they never matched a pattern anyway.+ },+ end: flush,+ };+}+/**+ * Collapse block-format messages into canonical single-line `**Name** (HH:MM):+ * body` lines. Returns `body` unchanged when no block header is present.+ */+export function normalizeBlockConversation(body: string): string {+ if (!looksLikeBlockConversation(body)) return body;+ const out: string[] = [];+ const normalizer = blockNormalizer(line => out.push(line));+ for (const line of body.split('\n')) normalizer.line(line);+ normalizer.end();return out.length > 0 ? out.join('\n') : body;}diff --git a/src/core/conversation-parser/parse.ts b/src/core/conversation-parser/parse.tsindex 9c5f00ae99..eb85498432 100644--- a/src/core/conversation-parser/parse.ts+++ b/src/core/conversation-parser/parse.ts@@ -28,7 +28,7 @@ import {BUILTIN_PATTERNS,cleanSpeaker,} from './builtins.ts';-import { normalizeBlockConversation } from './normalize-block.ts';+import { blockNormalizer, normalizeBlockConversation } from './normalize-block.ts';import type {DateContext,MatchedMessage,@@ -518,7 +518,8 @@ function getNonBlankLines(body: string, headCap?: number): string[] {return headCap !== undefined ? all.slice(0, headCap) : all;}-function speakerObjectAnchorsAllowed(body: string, entry: PatternEntry): boolean[] {+/** speakerObjectAnchorsAllowed one line at a time: line(raw) says whether that line may anchor; `invalid` voids every line. */+function speakerObjectScanner(entry: PatternEntry): { line(raw: string): boolean; readonly invalid: boolean } {let fence: string | undefined;let inTranscript: boolean | undefined;let invalidRegion = false;@@ -549,45 +550,53 @@ function speakerObjectAnchorsAllowed(body: string, entry: PatternEntry): booleanelse if ('}])'.includes(char) && preambleClosers.length > 0 && preambleClosers.pop() !== char) malformedPreamble = true;}};- const allowed = body.split(/\r?\n/).map(raw => {- const line = raw.trim();- if (malformedPreamble || preambleQuote || preambleClosers.length > 0) {- if (entry.regex.test(line) || /^#{1,6}\s+Transcript\s*$/i.test(line)) invalidRegion = true;- if (!malformedPreamble) scanPreamble(line);- return false;- }- const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(raw);- if (fence) {- if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim()) fence = undefined;- return false;- }- if (marker) {- fence = marker[1];- return false;- }- if (!line || /^(?: {4}| *\t)/.test(raw)) return false;- if (/^#{1,6}\s+Transcript\s*$/i.test(line)) {- inTranscript = true;- return false;- }- if (/^#{1,4}\s+\d{4}-\d{2}-\d{2}\s*$/.test(line)) return inTranscript !== false;- if (/^#{1,6}\s/.test(line)) {- inTranscript = false;- scanPreamble(line);- return false;- }- const matches = entry.regex.test(line);- if (inTranscript === undefined) {- inTranscript = matches;- if (!matches) invalidRegion = true;- } else if (inTranscript && !matches) {- invalidRegion = true;- } else if (!inTranscript) {- scanPreamble(line);- }- return inTranscript && matches;- });- return invalidRegion ? allowed.fill(false) : allowed;+ return {+ get invalid() { return invalidRegion; },+ line: (raw: string): boolean => {+ const line = raw.trim();+ if (malformedPreamble || preambleQuote || preambleClosers.length > 0) {+ if (entry.regex.test(line) || /^#{1,6}\s+Transcript\s*$/i.test(line)) invalidRegion = true;+ if (!malformedPreamble) scanPreamble(line);+ return false;+ }+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(raw);+ if (fence) {+ if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim()) fence = undefined;+ return false;+ }+ if (marker) {+ fence = marker[1];+ return false;+ }+ if (!line || /^(?: {4}| *\t)/.test(raw)) return false;+ if (/^#{1,6}\s+Transcript\s*$/i.test(line)) {+ inTranscript = true;+ return false;+ }+ if (/^#{1,4}\s+\d{4}-\d{2}-\d{2}\s*$/.test(line)) return inTranscript !== false;+ if (/^#{1,6}\s/.test(line)) {+ inTranscript = false;+ scanPreamble(line);+ return false;+ }+ const matches = entry.regex.test(line);+ if (inTranscript === undefined) {+ inTranscript = matches;+ if (!matches) invalidRegion = true;+ } else if (inTranscript && !matches) {+ invalidRegion = true;+ } else if (!inTranscript) {+ scanPreamble(line);+ }+ return inTranscript && matches;+ },+ };+}++function speakerObjectAnchorsAllowed(body: string, entry: PatternEntry): boolean[] {+ const scanner = speakerObjectScanner(entry);+ const allowed = body.split(/\r?\n/).map(raw => scanner.line(raw));+ return scanner.invalid ? allowed.fill(false) : allowed;}function speakerObjectScoringLines(body: string, entry: PatternEntry, headCap?: number): string[] {@@ -610,46 +619,49 @@ function scoreFromLines(lines: readonly string[],entry: PatternEntry,): number {- if (lines.length === 0) return 0;- let anchored = 0;- let anchorCandidates = 0;- let firstLineAnchored = false;- let firstAnchorIndex = -1;+ const score = lineScore(entry);+ for (const line of lines) scoreLine(score, entry, line);+ return scoreValue(score, entry);+}++/** scoreFromLines' counters over the lines scored so far, so a body can be scored one line at a time. */+interface LineScore { lines: number; anchored: number; candidates: number; firstLineAnchored: boolean; firstAnchorIndex: number; speakers: Set<string> | undefined }++function lineScore(entry: PatternEntry): LineScore {// Only populated when score_continuations_min_distinct_speakers is set// (avoids a Set + exec() per line for every other pattern, which only// needs the boolean match `test()` already gave before this change).- const tracksDistinctSpeakers =- entry.score_continuations_min_distinct_speakers !== undefined;- const distinctSpeakers: Set<string> | undefined = tracksDistinctSpeakers- ? new Set()- : undefined;- for (let index = 0; index < lines.length; index++) {- const line = lines[index];- if (entry.quick_reject && !entry.quick_reject.test(line)) {- continue;- }- anchorCandidates++;- let isMatch: boolean;- if (distinctSpeakers) {- const m = entry.regex.exec(line);- isMatch = m !== null;- if (m) {- const speaker = m[entry.captures.speaker_group];- if (speaker) distinctSpeakers.add(speaker);- }- } else {- isMatch = entry.regex.test(line);- }- if (isMatch) {- anchored++;- if (index === 0) firstLineAnchored = true;- if (firstAnchorIndex === -1) firstAnchorIndex = index;+ return { lines: 0, anchored: 0, candidates: 0, firstLineAnchored: false, firstAnchorIndex: -1,+ speakers: entry.score_continuations_min_distinct_speakers !== undefined ? new Set() : undefined };+}++function scoreLine(score: LineScore, entry: PatternEntry, line: string): void {+ const index = score.lines++;+ if (entry.quick_reject && !entry.quick_reject.test(line)) return;+ score.candidates++;+ let isMatch: boolean;+ if (score.speakers) {+ const m = entry.regex.exec(line);+ isMatch = m !== null;+ if (m) {+ const speaker = m[entry.captures.speaker_group];+ if (speaker) score.speakers.add(speaker);}+ } else {+ isMatch = entry.regex.test(line);}+ if (isMatch) {+ score.anchored++;+ if (index === 0) score.firstLineAnchored = true;+ if (score.firstAnchorIndex === -1) score.firstAnchorIndex = index;+ }+}+function scoreValue(score: LineScore, entry: PatternEntry): number {+ if (score.lines === 0) return 0;const distinctSpeakersOk =entry.score_continuations_min_distinct_speakers === undefined ||- (distinctSpeakers?.size ?? 0) >=+ (score.speakers?.size ?? 0) >=entry.score_continuations_min_distinct_speakers;// Bounds how far into the body the FIRST anchor may appear before the// candidate-only density score activates. A genuine export's anchor@@ -659,23 +671,24 @@ function scoreFromLines(// both roles are present — sits far past this bound instead.const preambleOk =entry.score_continuations_max_preamble_lines === undefined ||- (firstAnchorIndex !== -1 &&- firstAnchorIndex <= entry.score_continuations_max_preamble_lines);+ (score.firstAnchorIndex !== -1 &&+ score.firstAnchorIndex <= entry.score_continuations_max_preamble_lines);if (entry.score_continuations_as_body &&entry.multi_line &&entry.quick_reject &&- anchorCandidates > 0 &&- (anchored >= 2 || firstLineAnchored) &&+ score.candidates > 0 &&+ (score.anchored >= 2 || score.firstLineAnchored) &&distinctSpeakersOk &&preambleOk) {- return anchored / anchorCandidates;+ return score.anchored / score.candidates;}- return anchored / lines.length;+ return score.anchored / score.lines;}+/*** Score how well a pattern matches the first N lines of a body (D18).* Returns 0..1 ratio of matched lines. Higher = more confident.@@ -744,6 +757,84 @@ export function pickHeadPattern(head: string): string | null {return top.entry.id;}+/**+ * parseConversation's pattern choice over a body fed in pieces (a segmented page's occurrences, in order), holding+ * counters instead of the body: the same block-format collapse (when any block header appears), head pass over the first+ * SCORING_HEAD_LINES non-blank lines, full-body re-score, acceptance floor and structure gate, over the built-in+ * patterns. `finish()` returns the pattern id parseConversation(body).matched_pattern_id would, or null.+ */+export function createPatternDetector(): { push(text: string): void; finish(): string | null } {+ const raw = scoringTrack();+ const block = scoringTrack();+ const normalizer = blockNormalizer(line => block.line(line));+ let partial = '';+ const line = (text: string) => {+ normalizer.line(text);+ raw.line(text.endsWith('\r') ? text.slice(0, -1) : text);+ };+ return {+ push(text: string) {+ const lines = (partial + text).split('\n');+ partial = lines.pop()!;+ for (const l of lines) line(l);+ },+ finish() {+ line(partial);+ partial = '';+ normalizer.end();+ return (normalizer.headers > 0 ? block : raw).finish();+ },+ };+}++/** One normalized body's scores, fed line by line (createPatternDetector). */+function scoringTrack(): { line(raw: string): void; finish(): string | null } {+ const speakerObject = BUILTIN_PATTERNS.find((p) => p.id === 'python-dict-utterance');+ const scanner = speakerObject ? speakerObjectScanner(speakerObject) : null;+ const head = BUILTIN_PATTERNS.map((entry) => lineScore(entry));+ const full = BUILTIN_PATTERNS.map((entry) => lineScore(entry));+ // The structure gate's input: each anchored message's speaker, until one repeats.+ const gates = BUILTIN_PATTERNS.map((entry) => (entry.repeat_speaker_min_turns === undefined ? null : { turns: 0, speakers: new Set<string>(), repeated: false }));+ let nonBlank = 0;+ return {+ line(raw: string) {+ const allowed = scanner ? scanner.line(raw) : true;+ const line = raw.trim();+ if (!line) return;+ nonBlank++;+ BUILTIN_PATTERNS.forEach((entry, i) => {+ const scored = entry === speakerObject && !allowed ? '' : line;+ if (nonBlank <= SCORING_HEAD_LINES) scoreLine(head[i]!, entry, scored);+ scoreLine(full[i]!, entry, scored);+ const gate = gates[i];+ if (!gate || gate.repeated || DAY_HEADER_RE.test(line) || (entry.quick_reject && !entry.quick_reject.test(line))) return;+ const m = entry.regex.exec(line);+ if (!m) return;+ gate.turns++;+ const speaker = cleanSpeaker(m[entry.captures.speaker_group] ?? '', entry.speaker_clean);+ if (gate.speakers.has(speaker)) { gate.repeated = true; gate.speakers.clear(); } else gate.speakers.add(speaker);+ });+ },+ finish() {+ const value = (scores: LineScore[], i: number) => (scanner?.invalid && BUILTIN_PATTERNS[i] === speakerObject ? 0 : scoreValue(scores[i]!, BUILTIN_PATTERNS[i]!));+ const ranked = (scores: LineScore[]) => sortScored(BUILTIN_PATTERNS.map((entry, i) => ({ entry, score: value(scores, i), priority: priorityOf(entry.id) })));+ let scored = ranked(head);+ let fullBodyScored = false;+ if (scored[0]!.score < SCORING_HEAD_TRIGGER_THRESHOLD) {+ scored = ranked(full);+ fullBodyScored = true;+ }+ const top = scored[0]!;+ const i = BUILTIN_PATTERNS.indexOf(top.entry);+ const score = top.entry.score_full_body && !fullBodyScored ? value(full, i) : top.score;+ if (score < SCORING_MIN_ACCEPTANCE) return null;+ const gate = gates[i];+ if (gate && !gate.repeated && gate.turns >= top.entry.repeat_speaker_min_turns!) return null;+ return top.entry.id;+ },+ };+}+/*** Whether `line` opens a message under built-in pattern `patternId`, as* applyPattern reads it (trimmed; quick_reject, then the anchor regex), anddiff --git a/src/core/cycle/extract-atoms-segments.ts b/src/core/cycle/extract-atoms-segments.tsindex 76f57a8a6a..66ff929a2f 100644--- a/src/core/cycle/extract-atoms-segments.ts+++ b/src/core/cycle/extract-atoms-segments.ts@@ -19,7 +19,7 @@ import { createHash } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import { loadPricingOverrides } from '../budget/budget-tracker.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';-import { estimateChatCallUsd, meterPaidCall } from '../page-embedding-budget.ts';+import { estimateChatCallUsd, meterPaidCall, unpricedModelReceipt } from '../page-embedding-budget.ts';import { planSegmentDerivations, segmentDerivationContextHash, type SegmentDerivationInput, type SegmentDerivationRow } from '../page-body/derivations.ts';import { readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';import { lineWindows } from '../facts/backstop-segments.ts';@@ -72,13 +72,14 @@ async function planPage(engine: BrainEngine, sourceId: string, page: AtomPageInpconst items: AtomPageInput[] = [];let unread = false;let stop: 'cap_reached' | null = null;+ let unpricedModel: string | null = null;let open = 0;const todo = new Map(plan.todo.map(segment => [segment.occurrenceId, segment]));const row = (state: OccurrenceState): SegmentDerivationInput => {const finished = state.done.size === state.total;return { pageId, kind: KIND, occurrenceId: state.occurrenceId, version: EXTRACT_ATOMS_DERIVATION_VERSION, segmentSha256: state.sha256,contextHash: state.contextHash, state: finished ? 'done' : 'partial', output: { windows: [...state.done.values()].sort((a, b) => a.ordinal - b.ordinal) },- receipt: finished || !stop ? null : { kind: 'unread_windows', pipeline: KIND, reason: stop, windows_read: state.done.size, windows_total: state.total } };+ receipt: unpricedModelReceipt(KIND, unpricedModel, stop, finished || !stop ? null : { windows_read: state.done.size, windows_total: state.total }) };};const settlePage = async (): Promise<string[]> => {const keep = new Set<string>();@@ -116,6 +117,7 @@ async function planPage(engine: BrainEngine, sourceId: string, page: AtomPageInpconst pricingOverrides = await loadPricingOverrides(engine);const metered = await meterPaidCall(engine, { id: pageId, body_storage: 'segmented' }, `atoms:${model}`,estimateChatCallUsd(model, text.length, maxOutputTokens, pricingOverrides), call, { pricingOverrides });+ unpricedModel = metered.unpricedModel ?? unpricedModel;if (!('refused' in metered)) return metered;stop = 'cap_reached';const unfinished = [...states.values()].filter(s => s.done.size < s.total);diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 5150b8d182..a372a1766c 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -130,6 +130,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['extract_health',// Large pages A7: page extractions that read only part of their input.'extraction_input_truncated',+ // PR 4 (Wave B incremental derivation, transcripts): segmented derivations held back by a model without a price.+ 'derivation_unpriced_model','facts_embedding_width_consistency','facts_extraction_health','facts_health',diff --git a/src/core/extraction-watermark.ts b/src/core/extraction-watermark.tsindex ef457308b5..533ef1b6ea 100644--- a/src/core/extraction-watermark.ts+++ b/src/core/extraction-watermark.ts@@ -36,7 +36,7 @@ export type HeadFallbackReason = 'no_watermark' | 'prefix_changed' | 'version_ch/** The durable receipt of an extraction that did not read all of its input. */export interface InputTruncated {- /** PR 4 (Wave B incremental derivation, transcripts): `no_messages`, a segmented conversation run parsed no message from occurrences that had windows and kept their facts. */+ /** PR 4 (Wave B incremental derivation, transcripts): `no_messages`, a segmented conversation page reads as a transcript format over its whole text yet no message parsed under it; the run changed nothing. */kind: 'head' | 'tail_window' | 'skipped_too_large' | 'no_messages';pipeline: ExtractionPipeline;/** Characters the extractor read (0 for a skipped page). */diff --git a/src/core/facts/backstop-segments.ts b/src/core/facts/backstop-segments.tsindex 048a432a22..de7d0af4f1 100644--- a/src/core/facts/backstop-segments.ts+++ b/src/core/facts/backstop-segments.ts@@ -15,7 +15,7 @@import { createHash } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import { loadPricingOverrides } from '../budget/budget-tracker.ts';-import { estimateFactsExtractionUsd, meterPaidCall } from '../page-embedding-budget.ts';+import { estimateFactsExtractionUsd, meterPaidCall, unpricedModelReceipt } from '../page-embedding-budget.ts';import { setExtractionReceipt } from '../extraction-watermark.ts';import { planSegmentDerivations, segmentDerivationContextHash, type SegmentDerivationInput, type SegmentDerivationRow } from '../page-body/derivations.ts';import { readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';@@ -86,12 +86,13 @@ export async function runSegmentedBackstop<R extends { inserted: number; skippedconst results: R[] = [];const touched: Array<{ segment: (typeof plan.todo)[number]; windows: string[]; done: Map<number, WindowRecord> }> = [];let stop: 'cap_reached' | 'skipped' | 'interrupted' | null = null;+ let unpricedModel: string | null = null;const rowsOf = (): SegmentDerivationInput[] => touched.map(({ segment, windows, done }) => {const kept = windows.flatMap((text, ordinal) => done.get(ordinal)?.sha === sha(text) ? [done.get(ordinal)!] : []);const finished = kept.length === windows.length;return { pageId: page.id, kind: KIND, occurrenceId: segment.occurrenceId, version: FACTS_BACKSTOP_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: windows.length } };+ receipt: unpricedModelReceipt(KIND, unpricedModel, stop, finished ? null : { windows_read: kept.length, windows_total: windows.length }) };});const todo = new Map(plan.todo.map(segment => [segment.occurrenceId, segment]));try {@@ -111,6 +112,7 @@ export async function runSegmentedBackstop<R extends { inserted: number; skippedif (run.signal?.aborted) { stop = 'skipped'; break; }const metered = await meterPaidCall(engine, page, `facts:${run.model}`, estimateFactsExtractionUsd(run.model, text.length, maxTokens, pricingOverrides),() => run.extract(text), { pricingOverrides });+ unpricedModel = metered.unpricedModel ?? unpricedModel;if ('refused' in metered) { stop = 'cap_reached'; break; }const result = metered.value;results.push(result);diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.tsindex 1b18eefc12..ccb39821f6 100644--- a/src/core/facts/conversation-incremental.ts+++ b/src/core/facts/conversation-incremental.ts@@ -2,58 +2,62 @@* Incremental conversation facts for a segmented page (wave-b spec 8.1, 8.2 "Conversation facts", 8.3; PR 4 lane 4b).** Windows run over message boundaries across occurrences (conversation-stream.ts), so a window can span a segment cut;- * each window belongs to the occurrence its first message starts in. Each window's facts carry its anchor in+ * each window belongs to the occurrence its first message starts in. Each window's facts carry its key in* facts.source_window (owner occurrence, ordinal, rendered-text sha). Per occurrence, a page_segment_derivations row* (kind conversation_facts) records the segment sha, a context hash (every page-level input the windows depend on:- * title, gap setting, date context, extraction model, effective fact visibility), the windows it owns (ordinal, sha,- * facts, the positions of its first and last message), its predecessor, whether its first message opens a gap group,- * the grammar the page was parsed under, and the failed attempts of windows not extracted yet. A run:+ * title, gap setting, date context, extraction model, effective fact visibility), the windows whose facts it holds+ * (ordinal, sha, facts), its predecessor, whether its first message opens a gap group, the page's grammar, and the+ * failed attempts of windows not extracted yet.+ *+ * Deletion invariant. A run deletes a conversation fact in exactly two ways:+ * (a) replacement: the fact's exact window key was extracted again in this run (or, for a move, the same rendered+ * window's standing facts were re-anchored onto it), and its old facts give way in the transaction that adds the+ * new ones;+ * (b) collection at a fully settled run: every current window holds its facts (extracted or reused), none is failed,+ * no cap or --segment-limit stopped the run, no --since filter applied and the page did not change underneath;+ * only then does every fact whose window key is not a current window's (and every unanchored fact of an older+ * full-pass run) go.+ * Every other run (interrupted, capped, limited, failed, --since, or with a failed window anywhere on the page) only+ * adds and replaces. A row claims exactly the window keys whose facts it holds: a window moved to another occurrence is+ * dropped from its old row in the transaction that re-anchors its facts. Purge and forget run separately and win.+ *+ * A run:* - finds the first occurrence that is new, rewritten, moved or context-changed and streams the windows from the* nearest earlier occurrence that opens a gap group (the windows before it cannot change), one segment at a time- * and in runs, newest run first (a run ends where the next occurrence certainly opens a gap group), so a stop- * reads only the runs it reached; a page nothing changed on reads nothing;+ * and in runs, newest run first, so a stop reads only the runs it reached; a page nothing changed on reads nothing;+ * - parses under the page's grammar: the one detectPagePattern picks over the whole page (the whole-page pass's+ * choice; one unpaid read, counted in conversationDetectionWork), pinned on the rows while the occurrences that+ * recorded it under the same context are mostly unchanged by bytes; a page with no grammar is not a conversation: it settles as+ * non-extractable and its conversation facts are collected; a pinned grammar under which nothing parses is detected+ * again; a detected grammar under which nothing parses leaves a no_messages receipt and changes nothing;* - reuses every window an earlier run extracted with the same rendered text under the same context (re-anchored* when it moved), so an append extracts only its new windows and the one it grew;- * - extracts the rest newest first, each call metered against the page's facts cap (meterPaidCall, facts:<model>,- * reserved for every attempt and booked at the provider-reported cost), and publishes the facts and rows every- * CONVERSATION_FACTS_CHECKPOINT_WINDOWS windows, when it stops (--segment-limit, the cap) and when a window throws- * or the run aborts, so finished windows are never paid for twice;+ * - extracts the rest newest first, each call metered against the page's facts cap (meterPaidCall), and publishes+ * every CONVERSATION_FACTS_CHECKPOINT_WINDOWS windows, when it stops and when a window throws or the run aborts;* - counts a window whose extraction fails for a reason of its own (malformed or truncated output, a refusal or- * content filter, a provider refusal of the window's own input such as a context-length error; never a transport,- * provider, auth, rate-limit, 5xx, timeout or abort failure) against it across runs; the run stops there, and once a- * window has failed WINDOW_FAILURE_LIMIT runs it is marked failed (facts 0, a failed_windows receipt doctor lists)- * and the run moves on to older windows; a failed window keeps the facts of the earlier windows it overlaps until it- * is extracted, and a --force run (retryFailed) tries it again;- * - parses under the grammar a current row recorded, else the one the page's head detects (as the whole-page pass- * picks it), never one recorded under another context or text; a stream that parses no message from occurrences- * that had windows clears nothing and settles nothing (a no_messages receipt, the page counted failed);- * - clears facts only when that is safe: an unsettled run clears the facts of windows it extracted again and of- * earlier windows whose messages (by position: occurrence, ordinal and piece of an oversized message, never by- * timestamp, which a transcript without per-message times shares across every message) a run of current windows- * covers, nothing else; a settled run (every live window- * extracted, no --since, the page unchanged) clears the facts of windows that left the page and the unanchored- * facts of older full-pass runs, and stamps the page complete.- * A --since run extracts only the windows after it and never settles the page. A title or gap change re-extracts every- * window (documented cost); a no-op rewrite extracts nothing. Unmanaged brains only: a managed brain keeps the- * receipted whole-page publication.+ * content filter, a provider refusal of the window's own input; never a transport, provider, auth, rate-limit, 5xx,+ * timeout or abort failure) against it across runs; the run stops there, and once a window has failed+ * WINDOW_FAILURE_LIMIT runs it is marked failed (a failed_windows receipt doctor lists) and the run moves on; the+ * page is then stamped done but never collected until a --force run (retryFailed) extracts it.+ * A title or gap change re-extracts every window (documented cost); a no-op rewrite extracts nothing. 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 } from '../conversation-parser/parse.ts';import { loadPricingOverrides, type PricingOverrides } from '../budget/budget-tracker.ts';import { providerItemRefusal } from '../ai/errors.ts';-import { truthLead } from '../page-body/segment-blocks.ts';import { writeDerivedFacts } from '../persistence/derived-facts.ts';-import { estimateFactsExtractionUsd, meterPaidCall } from '../page-embedding-budget.ts';+import { estimateFactsExtractionUsd, meterPaidCall, unpricedModelReceipt } 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 } from '../page-body/segment-conversation.ts';+import { conversationDetectionWork, readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.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 { countWindowFacts, publishConversationFacts, type ConversationFactRow } from './conversation-publication.ts';import { recordFailedPage } from './conversation-run-status.ts';-import { detectConversationPattern, startsConversationRun, streamConversationWindows, type MessagePosition } from './conversation-stream.ts';+import { detectPagePattern, startsConversationRun, streamConversationWindows } from './conversation-stream.ts';import type { ConversationSegment } from './conversation-types.ts';import { renderSegmentForExtraction } from './conversation-windows.ts';import { extractConversationWindow, nonExtractableAuditFact, regularPageVersionToken, terminalAuditFact, type ConversationWindowRun } from './conversation-window-extract.ts';@@ -62,14 +66,13 @@ import type { FactVisibility } from './visibility.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 = 2;+export const CONVERSATION_FACTS_DERIVATION_VERSION = 3;/** Windows extracted between two publications of a page's facts and rows. */export const CONVERSATION_FACTS_CHECKPOINT_WINDOWS = 8;/*** Runs in which one window's extraction may throw before it is marked failed and skipped. extract.ts already retries a- * truncated or malformed answer inside one run and the gateway retries transient provider errors, so a window that- * still throws in three separate runs fails for a reason of its own (its text, a deterministic provider refusal); three- * also rides out a transient outage spanning two runs, and bounds what a doomed window costs at three reservations.+ * truncated or malformed answer inside one run, so a window that still throws in three separate runs fails for a reason+ * of its own; three bounds what a doomed window costs at three reservations.*/export const WINDOW_FAILURE_LIMIT = 3;@@ -89,28 +92,21 @@ export interface SegmentedConversationRun extends ConversationWindowRun {segmentLimit: number;}-/** Characters of the page's head the grammar is detected from when no current row records it. */-const PATTERN_HEAD_CHARS = 64 * 1024;-/** Where a window's first and last message piece are: [occurrence id, ordinal, piece] twice (MessagePosition). */-type Span = [number, number, number, number, number, number];-/** A window an occurrence row records: ordinal, rendered-text sha, facts produced, its span, and why it failed when it did. */-interface WindowRecord { ordinal: number; sha: string; facts: number; span?: Span; failed?: WindowFailure }-/** Failed extraction attempts of one window (by rendered-text sha), the last error, and (once failed) the keys of the earlier windows whose facts it keeps. */-interface WindowFailure { attempts: number; error: string; keeps?: string[] }-/** An earlier window whose facts still stand though no current window holds it yet (an unsettled run left it): its key and span. */-interface StaleWindow { key: string; span?: Span }-interface RowOutput { windows: WindowRecord[]; starts_group?: boolean; prev?: number | null; pattern?: string | null; retries?: Array<{ sha: string } & WindowFailure>;- stale?: StaleWindow[] }+/** A window an occurrence row holds the facts of: ordinal, rendered-text sha, facts its key holds, and why it failed when it did. */+interface WindowRecord { ordinal: number; sha: string; facts: number; failed?: WindowFailure }+/** Failed extraction attempts of one window (by rendered-text sha) and the last error. */+interface WindowFailure { attempts: number; error: string }+interface RowOutput { windows: WindowRecord[]; starts_group?: boolean; prev?: number | null; pattern?: string | null; retries?: Array<{ sha: string } & WindowFailure> }/** One window of the stream: `reused` (an earlier run's facts stand), `todo`, `extracted` by this run, or `failed` past the limit. */-interface StreamWindow { owner: number; seg: ConversationSegment; text: string | null; window: SourceWindow; span: Span;+interface StreamWindow { owner: number; seg: ConversationSegment; text: string | null; window: SourceWindow;state: 'reused' | 'todo' | 'extracted' | 'failed'; facts: number; failed?: WindowFailure }type Stop = 'segment_limit' | 'cap_reached' | 'interrupted' | null;/** The bounded output a conversation_facts row stores (window anchors and counts; never text). */-function rowOutput(row: SegmentDerivationRow | undefined): RowOutput {+function rowOutput(row: SegmentDerivationInput | undefined): RowOutput {const output = row?.output as Partial<RowOutput> | null | undefined;return { windows: Array.isArray(output?.windows) ? output.windows : [], starts_group: output?.starts_group, prev: output?.prev,- pattern: output?.pattern ?? null, retries: Array.isArray(output?.retries) ? output.retries : [], stale: Array.isArray(output?.stale) ? output.stale : [] };+ pattern: output?.pattern ?? null, retries: Array.isArray(output?.retries) ? output.retries : [] };}const keyOf = (occurrenceId: number, w: WindowRecord) => sourceWindowKey({ occurrence_id: occurrenceId, window_ordinal: w.ordinal, window_text_sha: w.sha });@@ -123,46 +119,6 @@ async function conversationContext(engine: BrainEngine, page: Page, gapMinutes:return { model, inputs: { title: page.title || page.slug, gap_minutes: gapMinutes, date: dates.fallbackDate, timezone: dates.timezone ?? null, model, visibility } };}-/**- * Window keys of earlier windows whose first and last message positions fall inside one run of consecutive windows- * with facts standing (reused or extracted). A position orders by its occurrence's place on the page, then its- * ordinal; a window in an occurrence that left the page is never covered.- */-function coveredKeys(windows: readonly StreamWindow[], earlier: readonly StaleWindow[], place: ReadonlyMap<number, number>): string[] {- const runs: Array<[Point, Point]> = [];- let open: [Point, Point] | null = null;- for (const w of windows) {- if (w.state !== 'reused' && w.state !== 'extracted') { open = null; continue; }- const [start, end] = ends(w.span, place) as [Point, Point];- if (open) open[1] = end;- else runs.push(open = [start, end]);- }- return earlier.filter(e => {- const span = e.span ? ends(e.span, place) : null;- return span !== null && runs.some(([a, b]) => before(a, span[0]) && before(span[1], b));- }).map(e => e.key);-}--/** A message piece's place on the page: [occurrence place, ordinal, piece], ordered lexicographically. */-type Point = [number, number, number];-const before = (a: Point, b: Point) => a[0] !== b[0] ? a[0] < b[0] : a[1] !== b[1] ? a[1] < b[1] : a[2] <= b[2];-/** A span's first and last point, or null when either occurrence left the page. */-function ends(span: Span, place: ReadonlyMap<number, number>): [Point, Point] | null {- const first = place.get(span[0]);- const last = place.get(span[3]);- return first === undefined || last === undefined ? null : [[first, span[1], span[2]], [last, span[4], span[5]]];-}--/** Keys of earlier windows whose span overlaps `span` (a failed window keeps their facts). */-function overlappingKeys(span: Span, earlier: readonly StaleWindow[], place: ReadonlyMap<number, number>): string[] {- const mine = ends(span, place);- if (!mine) return [];- return earlier.filter(e => {- const theirs = e.span ? ends(e.span, place) : null;- return theirs !== null && before(theirs[0], mine[1]) && before(mine[0], theirs[1]);- }).map(e => e.key);-}-/** extract.ts failure reasons caused by the window itself (its output or its content), which repeat until it changes. */const WINDOW_SPECIFIC_REASONS: ReadonlySet<string> = new Set(['malformed_output', 'truncated_output', 'refusal', 'content_filter']);@@ -184,9 +140,9 @@ function windowFailure(error: unknown, signal: AbortSignal | undefined): boolean* 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; retryFailed?: boolean }): Promise<{ newestEnd: string | null }> {+ opts: { gapMinutes: number | null; sinceIso?: string; retryFailed?: boolean; redetect?: boolean }): Promise<{ newestEnd: string | null }> {const { engine, sourceId, result } = run;- result.pages_considered++;+ if (!opts.redetect) result.pages_considered++;const versionToken = regularPageVersionToken(page);const { model, inputs } = await conversationContext(engine, page, opts.gapMinutes, run.factVisibility);const contextHash = segmentDerivationContextHash(KIND, { entryState: null, page: inputs });@@ -197,6 +153,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatioconst plan = planSegmentDerivations(KIND, CONVERSATION_FACTS_DERIVATION_VERSION, live, prior);const priorRow = new Map(prior.map(row => [row.occurrenceId, row]));const current = new Set(plan.current.map(row => row.occurrenceId));+ const sameContext = (row: SegmentDerivationRow) => row.version === CONVERSATION_FACTS_DERIVATION_VERSION && hex(row.contextHash) === hex(contextHash);const prevOf = (i: number) => (i === 0 ? null : liveIds[i - 1]!);const intact = (i: number) => {const output = rowOutput(priorRow.get(liveIds[i]!));@@ -211,31 +168,39 @@ export async function processSegmentedConversationPage(run: SegmentedConversatioif (intact(i) && rowOutput(priorRow.get(liveIds[i]!)).starts_group === true) { from = i; break; }}const position = new Map(liveIds.map((id, i) => [id, i]));- // Earlier windows of the occurrences the stream covers (and of retired ones): reusable by rendered text under the same- // context, and candidates to clear once the current windows cover their messages.+ // The grammar: pinned while the occurrences whose rows recorded it under this context are, by bytes, mostly unchanged+ // (an append or an edit keeps it; a re-import does not), else detected over the whole page.+ const liveOccurrence = new Map(occurrences.map(o => [o.row.occurrenceId, o.row]));+ const recorded = prior.filter(row => sameContext(row) && liveOccurrence.has(row.occurrenceId) && rowOutput(row).pattern);+ const kept = recorded.filter(row => hex(liveOccurrence.get(row.occurrenceId)!.sha256) === hex(row.segmentSha256));+ const bytesOf = (rows: SegmentDerivationRow[]) => rows.reduce((n, row) => n + liveOccurrence.get(row.occurrenceId)!.byteLen, 0);+ let pattern = !opts.redetect && kept.length && 2 * bytesOf(kept) > bytesOf(recorded) ? rowOutput(kept[0]).pattern ?? null : null;+ const pinned = pattern !== null;+ const detectedBytes = conversationDetectionWork.bytes;+ if (!pattern && from < liveIds.length) pattern = await detectPagePattern(occurrences, i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }));+ if (!pattern && from < liveIds.length) {+ if (opts.sinceIso) { result.pages_skipped++; return { newestEnd: null }; }+ from = 0;+ }+ // Earlier windows of the occurrences the stream covers (and of retired ones), reusable by rendered text under the same context.const reusable = new Map<string, Array<{ occurrenceId: number; record: WindowRecord }>>();- const earlier: Array<StaleWindow & { occurrenceId: number }> = [];const failures = new Map<string, WindowFailure>();- // The page's grammar: the one a current row recorded (same text, version and context), else the head's (below).- let pattern: string | null = plan.current.map(row => rowOutput(row).pattern).find(Boolean) ?? null;for (const row of prior) {- if ((position.get(row.occurrenceId) ?? Infinity) < from) continue;- const same = row.version === CONVERSATION_FACTS_DERIVATION_VERSION && hex(row.contextHash) === hex(contextHash);+ if ((position.get(row.occurrenceId) ?? Infinity) < from || !sameContext(row)) continue;const output = rowOutput(row);- for (const stale of output.stale ?? []) earlier.push({ ...stale, occurrenceId: row.occurrenceId });for (const record of output.windows) {- earlier.push({ key: keyOf(row.occurrenceId, record), span: record.span, occurrenceId: row.occurrenceId });- if (same && !(record.failed && opts.retryFailed)) reusable.set(record.sha, [...(reusable.get(record.sha) ?? []), { occurrenceId: row.occurrenceId, record }]);+ if (!(record.failed && opts.retryFailed)) reusable.set(record.sha, [...(reusable.get(record.sha) ?? []), { occurrenceId: row.occurrenceId, record }]);}- if (same && !opts.retryFailed) for (const { sha, attempts, error } of output.retries ?? []) failures.set(sha, { attempts, error });+ if (!opts.retryFailed) for (const { sha, attempts, error } of output.retries ?? []) failures.set(sha, { attempts, error });}const windows: StreamWindow[] = [];const pendingMoves: Array<{ from: string; to: SourceWindow }> = [];- const reused = new Set<string>();+ /** Window keys moved off each occurrence's row since the last publication. */+ const movedOff = new Map<number, Set<string>>();+ const rowsNow = new Map<number, SegmentDerivationInput>(prior.map(row => [row.occurrenceId, row]));const startsGroup = new Map<number, boolean>();const ordinals = new Map<number, number>();const pageTitle = page.title || page.slug;- if (!pattern && from < liveIds.length) pattern = detectConversationPattern(await truthLead(engine, page.id, PATTERN_HEAD_CHARS), page);const streamOpts = { page, gapMinutes: opts.gapMinutes, sinceIso: opts.sinceIso, pattern };let parsedMessages = 0;const texts = new Map<number, string>();@@ -251,25 +216,27 @@ export async function processSegmentedConversationPage(run: SegmentedConversatiolet start = end - 1;while (start > from && !startsConversationRun(occurrences, start, await readText(start), await readText(start - 1), streamOpts)) start--;const runWindows: StreamWindow[] = [];- const spanOf = (first: MessagePosition, last: MessagePosition): Span => [liveIds[first.owner]!, first.n, first.piece, liveIds[last.owner]!, last.n, last.piece];const streamed = await streamConversationWindows(occurrences, start, end, streamOpts, readText, {- window(first, last, seg) {- const owner = liveIds[first.owner]!;+ window(index, seg) {+ const owner = liveIds[index]!;const ordinal = ordinals.get(owner) ?? 0;ordinals.set(owner, ordinal + 1);const text = renderSegmentForExtraction(pageTitle, seg);const window = sourceWindowFor(owner, ordinal, text);- const hit = reusable.get(window.window_text_sha)?.shift();- const span = spanOf(first, last);- if (!hit) { runWindows.push({ owner, seg, text, window, span, state: 'todo', facts: 0 }); return; }+ // The same window's own record first, else any record of the same text (the window moved).+ const candidates = reusable.get(window.window_text_sha) ?? [];+ const own = candidates.findIndex(c => c.occurrenceId === owner && c.record.ordinal === ordinal);+ const hit = candidates.splice(own < 0 ? 0 : own, 1)[0];+ if (!hit) { runWindows.push({ owner, seg, text, window, state: 'todo', facts: 0 }); return; }const was = keyOf(hit.occurrenceId, hit.record);- reused.add(was);- if (was !== sourceWindowKey(window)) pendingMoves.push({ from: was, to: window });- runWindows.push({ owner, seg, text: null, window, span, state: hit.record.failed ? 'failed' : 'reused', facts: hit.record.facts, failed: hit.record.failed });+ if (was !== sourceWindowKey(window)) {+ pendingMoves.push({ from: was, to: window });+ movedOff.set(hit.occurrenceId, new Set([...(movedOff.get(hit.occurrenceId) ?? []), was]));+ }+ runWindows.push({ owner, seg, text: null, window, state: hit.record.failed ? 'failed' : 'reused', facts: hit.record.facts, failed: hit.record.failed });},occurrence(index, starts) { startsGroup.set(liveIds[index]!, starts); },});- pattern = streamOpts.pattern = streamed.pattern;parsedMessages += streamed.messages;for (const i of [...texts.keys()]) if (i > start) texts.delete(i);windows.unshift(...runWindows);@@ -277,21 +244,19 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio};if (run.dryRun) {let todo = 0;- for (let end = liveIds.length; end > from;) { const next = await streamRun(end); todo += next.windows.filter(w => w.state === 'todo').length; end = next.start; }+ for (let end = liveIds.length; pattern && end > from;) { const next = await streamRun(end); todo += next.windows.filter(w => w.state === 'todo').length; end = next.start; }result.segments_processed += run.segmentLimit > 0 ? Math.min(todo, run.segmentLimit) : todo;result.pages_processed++;return { newestEnd: null };}const resolution = emptySaveTimeResolutionCounts();- let streamedFrom = liveIds.length;+ let streamedFrom = pattern ? liveIds.length : from;let stop: Stop = null;- let stopOwner: number | null = null;+ let unpricedModel: string | null = null;let newestEnd: string | null = null;let extracted = 0;let batch: { rows: ConversationFactRow[]; windows: SourceWindow[]; keys: string[] } = { rows: [], windows: [], keys: [] };- let cleared = new Set<string>();- let settledPage = false;/** Publish the facts extracted since the last publication and the rows of the streamed occurrences; `final` settles a finished page. */const publish = async (final: boolean) => {let unchanged = true;@@ -300,62 +265,61 @@ export async function processSegmentedConversationPage(run: SegmentedConversatiounchanged = !!now && now.id === page.id && regularPageVersionToken(now) === versionToken;}const settled = final && unchanged && stop === null && !opts.sinceIso && streamedFrom <= from;- const clear = settled ? [] : [...batch.keys, ...coveredKeys(windows, earlier.filter(e => !reused.has(e.key)), position).filter(key => !cleared.has(key))];- const gone = new Set([...cleared, ...clear]);const owned = new Map<number, StreamWindow[]>();for (const w of windows) owned.set(w.owner, [...(owned.get(w.owner) ?? []), w]);- // Rows of the occurrences this run finished or reached; an occurrence it never reached keeps its row (still unsettled).- const derived: SegmentDerivationInput[] = liveIds.slice(streamedFrom).flatMap((occurrenceId, k) => {+ // Rows of the occurrences this run streamed; an occurrence it never reached keeps its row.+ const derived: SegmentDerivationInput[] = liveIds.slice(streamedFrom).map((occurrenceId, k) => {const mine = owned.get(occurrenceId) ?? [];const records: WindowRecord[] = mine.filter(w => w.state !== 'todo').map(w => ({ ordinal: w.window.window_ordinal, sha: w.window.window_text_sha,- facts: w.facts, span: w.span, ...(w.failed && w.state === 'failed' ? { failed: w.failed } : {}) }));+ facts: w.facts, ...(w.failed && w.state === 'failed' ? { failed: w.failed } : {}) }));const retries = mine.flatMap(w => { const failure = w.state === 'todo' ? failures.get(w.window.window_text_sha) : undefined; return failure ? [{ sha: w.window.window_text_sha, ...failure }] : []; });const failed = records.filter(r => r.failed).map(r => ({ ordinal: r.ordinal, attempts: r.failed!.attempts, error: r.failed!.error }));const finished = records.length === mine.length;- const recorded = new Set(records.map(r => keyOf(occurrenceId, r)));- // Earlier windows of this occurrence whose facts this unsettled run neither replaced nor cleared stay on its row.- const stale = settled ? [] : earlier.filter(e => e.occurrenceId === occurrenceId && !reused.has(e.key) && !gone.has(e.key) && !recorded.has(e.key))- .map(({ key, span }) => ({ key, span }));- if (!finished && !records.length && !stale.length && occurrenceId !== stopOwner) return [];- return [{ pageId: page.id, kind: KIND, occurrenceId, version: CONVERSATION_FACTS_DERIVATION_VERSION, segmentSha256: live[streamedFrom + k]!.sha256,+ return { pageId: page.id, kind: KIND, occurrenceId, version: CONVERSATION_FACTS_DERIVATION_VERSION, segmentSha256: live[streamedFrom + k]!.sha256,contextHash, state: finished && !opts.sinceIso ? 'done' : 'partial',- output: { windows: records, starts_group: startsGroup.get(occurrenceId) ?? false, prev: prevOf(streamedFrom + k), pattern, ...(retries.length ? { retries } : {}), ...(stale.length ? { stale } : {}) },- receipt: !finished ? { kind: 'unread_windows', pipeline: KIND, reason: stop ?? 'in_progress', windows_read: records.length, windows_total: mine.length }- : failed.length ? { kind: 'failed_windows', pipeline: KIND, windows: failed } : null }];+ output: { windows: records, starts_group: startsGroup.get(occurrenceId) ?? false, prev: prevOf(streamedFrom + k), pattern, ...(retries.length ? { retries } : {}) },+ receipt: !finished ? unpricedModelReceipt(KIND, unpricedModel, stop ?? 'in_progress', { windows_read: records.length, windows_total: mine.length })+ : failed.length ? { kind: 'failed_windows', pipeline: KIND, windows: failed } : unpricedModelReceipt(KIND, unpricedModel, null, null) };+ });+ // A row whose window moved to another occurrence stops claiming it in the transaction that re-anchors its facts.+ const rewritten = new Set(derived.map(row => row.occurrenceId));+ const released: SegmentDerivationInput[] = [...movedOff].flatMap(([occurrenceId, keys]) => {+ const row = rowsNow.get(occurrenceId);+ if (!row || rewritten.has(occurrenceId)) return [];+ const output = rowOutput(row);+ return [{ ...row, output: { ...(row.output as object), windows: output.windows.filter(w => !keys.has(keyOf(occurrenceId, w))) } }];});- // A failed window keeps the facts of the earlier windows it overlaps (`keeps`) until it is extracted.- const settledWindows = [...liveIds.slice(0, from).flatMap(id => rowOutput(priorRow.get(id)).windows.map(w => ({ key: keyOf(id, w), failed: w.failed }))),- ...windows.map(w => ({ key: sourceWindowKey(w.window), failed: w.state === 'failed' ? w.failed : undefined }))];- const anyFailed = settledWindows.some(w => w.failed);- const keep = settled ? settledWindows.flatMap(w => [w.key, ...(w.failed?.keeps ?? [])]) : null;- const outcome = !settled ? null : keep!.length ? terminalAuditFact(page.slug, 0, versionToken)- : nonExtractableAuditFact(page.slug, 0, versionToken, 'fewer than two eligible messages');+ const settledWindows = [...liveIds.slice(0, from).flatMap(id => rowOutput(priorRow.get(id)).windows.map(w => ({ key: keyOf(id, w), failed: !!w.failed }))),+ ...windows.map(w => ({ key: sourceWindowKey(w.window), failed: w.state === 'failed' }))];+ const liveKeys = settled ? settledWindows.map(w => w.key) : null;+ const collect = settled && !settledWindows.some(w => w.failed);+ const outcome = !liveKeys ? null : liveKeys.length ? terminalAuditFact(page.slug, 0, versionToken)+ : nonExtractableAuditFact(page.slug, 0, versionToken, pattern ? 'fewer than two eligible messages' : 'no conversation messages found');const moves = [...pendingMoves];const out = await writeDerivedFacts(engine, sourceId, page.slug, async db => {const published = await publishConversationFacts(db, sourceId, page.slug, outcome ? [...batch.rows, outcome] : batch.rows,- { scope: 'window', segments: { windows: batch.windows, moves, keep, clear, retireUnanchored: settled && !anyFailed } });- if (derived.length) await db.upsertSegmentDerivations(derived);+ { scope: 'window', segments: { windows: batch.windows, moves, replace: batch.keys, live: collect ? liveKeys : null } });+ if (derived.length || released.length) await db.upsertSegmentDerivations([...derived, ...released]);if (settled) await db.retireSegmentDerivations(page.id, liveIds, { kind: KIND });return published;});pendingMoves.splice(0, moves.length);- cleared = new Set([...cleared, ...clear]);+ movedOff.clear();+ for (const row of [...derived, ...released]) rowsNow.set(row.occurrenceId, row);batch = { rows: [], windows: [], keys: [] };result.facts_inserted += out.facts_inserted;result.orphan_facts_cleaned += out.deleted;- settledPage = settled;- return { unchanged, settled, keep, outcome };+ return { unchanged, settled, liveKeys, outcome };};const maxTokens = await getFactsExtractionMaxTokens(engine);let paid: { pricingOverrides: PricingOverrides | undefined; entityHints: ExtractInput['entityHints'] } | null = null;try {// Newest runs first, and newest windows first inside each, so a cap or a limit spends on the newest messages.- for (let end = liveIds.length; end > from && !stop;) {+ for (let end = liveIds.length; pattern && end > from && !stop;) {const next = await streamRun(end);streamedFrom = end = next.start;for (const w of next.windows.filter(x => x.state === 'todo').reverse()) {- stopOwner = w.owner;if (run.segmentLimit > 0 && extracted >= run.segmentLimit) { stop = 'segment_limit'; break; }if (run.signal?.aborted) throw new Error('aborted');paid ??= { pricingOverrides: await loadPricingOverrides(engine), entityHints: await conversationEntityHints(engine, sourceId, page.slug, run.factVisibility) };@@ -372,11 +336,12 @@ export async function processSegmentedConversationPage(run: SegmentedConversatiofailures.set(sha, failure);if (failure.attempts < WINDOW_FAILURE_LIMIT) throw error;failures.delete(sha);- Object.assign(w, { state: 'failed', failed: { ...failure, keeps: overlappingKeys(w.span, earlier.filter(e => !reused.has(e.key)), position) }, text: null });- stopOwner = null;+ // A failed window keeps whatever facts its key still holds (an earlier context's), and its row claims them.+ Object.assign(w, { state: 'failed', failed: failure, facts: await countWindowFacts(engine, sourceId, page.slug, sourceWindowKey(w.window)), text: null });process.stderr.write(`[extract-conversation-facts] ${page.slug}: window ${w.window.window_ordinal} of occurrence ${w.owner} failed ${failure.attempts} runs (${failure.error}); skipped, gbrain doctor lists it, --force retries it\n`);continue;}+ unpricedModel = metered.unpricedModel ?? unpricedModel;if ('refused' in metered) { stop = 'cap_reached'; break; }const out = metered.value;w.state = 'extracted';@@ -389,7 +354,6 @@ export async function processSegmentedConversationPage(run: SegmentedConversatiofor (const row of out.rows) { batch.rows.push(row); batch.windows.push(w.window); }batch.keys.push(sourceWindowKey(w.window));if (!newestEnd || w.seg.endIso > newestEnd) newestEnd = w.seg.endIso;- stopOwner = null;if (batch.keys.length >= CONVERSATION_FACTS_CHECKPOINT_WINDOWS) await publish(false);if (run.sleepMs > 0) await new Promise(resolve => setTimeout(resolve, run.sleepMs));}@@ -405,16 +369,17 @@ export async function processSegmentedConversationPage(run: SegmentedConversatioresult.resolution_errors += resolution.resolution_errors;}- if (parsedMessages === 0 && earlier.length > 0) {- // Occurrences that had windows parsed into no message (a changed format the grammar no longer reads, a parser- // fault): clearing or settling would delete every fact they held. Nothing is published; the receipt says why.+ if (pattern && from < liveIds.length && parsedMessages === 0) {+ // A pinned grammar reads nothing here: detect the page's grammar again and start over under it.+ if (pinned) return processSegmentedConversationPage(run, page, { ...opts, redetect: true });+ // The grammar detected over the whole page reads no message from the page: a parser fault. Nothing is published.await setExtractionReceipt(engine, page.id, KIND, { kind: 'no_messages', pipeline: KIND, processed_chars: 0 });- process.stderr.write(`[extract-conversation-facts] ${page.slug}: no message parsed from occurrences that had ${earlier.length} window(s); its facts were kept, nothing settled\n`);+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: the page reads as ${pattern} but no message parsed under it; its facts were kept, nothing settled\n`);result.pages_failed++;- recordFailedPage(result, page.slug, 'no message parsed from occurrences that had windows; facts kept for replay');+ recordFailedPage(result, page.slug, `the page reads as ${pattern} but no message parsed under it; facts kept`);return { newestEnd: null };}- const { unchanged, keep, outcome } = await publish(true);+ const { unchanged, settled, liveKeys, outcome } = await publish(true);await setExtractionReceipt(engine, page.id, KIND, null);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`);@@ -422,9 +387,10 @@ export async function processSegmentedConversationPage(run: SegmentedConversatiorecordFailedPage(result, page.slug, 'the page changed during extraction; left unfinished for replay');return { newestEnd: null };}- if (outcome && !keep!.length) { result.pages_skipped++; result.pages_skipped_insufficient_turns++; result.pages_marked_non_extractable++; }+ if (outcome && !liveKeys!.length) { result.pages_skipped++; result.pages_skipped_insufficient_turns++; result.pages_marked_non_extractable++; }else result.pages_processed++;+ const detected = conversationDetectionWork.bytes - detectedBytes;process.stderr.write(`[extract-conversation-facts] ${page.slug}: ${extracted} new window(s) of ${windows.length} streamed from occurrence ${streamedFrom + 1} of ${liveIds.length}`- + `${stop ? `; stopped: ${stop}` : settledPage ? '; settled' : ''}\n`);+ + `${detected ? `; grammar ${pattern ?? 'none'} detected over ${detected} bytes` : ''}${stop ? `; stopped: ${stop}` : settled ? '; settled' : ''}\n`);return { newestEnd };}diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.tsindex 647389a482..70abb1676e 100644--- a/src/core/facts/conversation-publication.ts+++ b/src/core/facts/conversation-publication.ts@@ -80,7 +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';+import { sourceWindowKey, type SourceWindow } from '../page-body/derivations.ts';export const CONVERSATION_FACTS_INTENT = 'managed_maintenance_conversation_facts';export const CONVERSATION_FACTS_PROTOCOL = 1;@@ -416,30 +416,36 @@ type UnnumberedFact = Omit<ConversationFactRow, 'row_num' | 'source_markdown_slu/*** 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. A settled page (every live window extracted) passes `keep`: its- * extractor facts whose window key is not in it (windows that left the page) are cleared, and so are its unanchored facts- * (older full-pass runs) when `retireUnanchored`. An unsettled page passes `keep: null` and clears only the window keys in- * `clear` (windows extracted again, or covered by windows extracted since); every other fact keeps its row and id.+ * null for an outcome row). Facts are deleted only by exact window key: `replace` (windows extracted again: their prior+ * facts give way to the new rows) and the destination of a move (the reused facts stand for it); a fully settled page+ * also passes `live`, and every conversation fact whose window key is not in it (and every unanchored one, from older+ * full-pass runs) is cleared. Any other publication only adds and replaces.*/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. */+ /** Facts re-anchored, not re-extracted (ids unchanged): the same rendered window under the same context has another key now. */moves: ReadonlyArray<{ from: string; to: SourceWindow }>;- keep: readonly string[] | null;- clear?: readonly string[];- retireUnanchored: boolean;+ replace: readonly string[];+ live: readonly string[] | null;}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 })))]);- }+/**+ * Re-anchors the page's extractor facts of each `from` window key to its `to` window (ids unchanged) in one statement, so+ * a chain of moves among windows of the same text applies at once; the facts a destination key held beforehand (another+ * context's, or left by an earlier run) are cleared first, so a key never holds two batches.+ */+async function moveSourceWindows(tx: BrainEngine, sourceId: string, slug: string, moves: ConversationSegmentsPublication['moves']): Promise<number> {+ if (!moves.length) return 0;+ const sources = new Set(moves.map(m => m.from));+ const displaced = moves.map(m => sourceWindowKey(m.to)).filter(key => !sources.has(key));+ const cleared = displaced.length ? await clearConversationFacts(tx, sourceId, slug, { keys: displaced, keep: false, unanchored: false }) : 0;+ 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.map(m => ({ k: m.from, w: m.to })))]);+ return cleared;}/** Anchors freshly inserted facts to their windows, in bounded batches; one JSON bind per batch, so JSONB stays an object. */@@ -477,8 +483,12 @@ export async function publishConversationFacts(tx: BrainEngine, sourceId: stringconst 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;+ let retiredWindows = 0;+ if (segments) {+ retiredWindows += await moveSourceWindows(tx, sourceId, slug, segments.moves);+ if (segments.replace.length) retiredWindows += await clearConversationFacts(tx, sourceId, slug, { keys: segments.replace, keep: false, unanchored: false });+ if (segments.live) retiredWindows += await clearConversationFacts(tx, sourceId, slug, { keys: segments.live, keep: true, unanchored: true });+ }const outcomes = published.some(({ row }) => OUTCOME_SOURCES.has(row.source)) ? await tx.executeRaw<{ id: number }>(`DELETE FROM factsWHERE source_id=$1 AND source_markdown_slug=$2 AND source = ANY($3::text[]) RETURNING id`, [sourceId, slug, [...AUDIT_ROW_SOURCES]]) : [];return { deleted: retiredWindows + outcomes.length, ...await insertConversationFacts(tx, sourceId, slug, published.map(({ row }) => row)) };@@ -540,11 +550,22 @@ export async function countConversationFacts(db: BrainEngine, sourceId: string,return Number(row?.count ?? 0);}+/** The page's active conversation facts anchored to window `key`. */+export async function countWindowFacts(db: BrainEngine, sourceId: string, slug: string, key: string): Promise<number> {+ const [row] = await db.executeRaw<{ count: string }>(`SELECT count(*)::text AS count 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 f.source_window IS NOT NULL AND ${WINDOW_KEY_SQL} = $3`, [sourceId, slug, key]);+ return Number(row?.count ?? 0);+}++/**+ * With `windows`, only the page's anchored facts whose window key is in `keys` (`keep` false) or not in it (`keep` true),+ * and its unanchored facts when `unanchored`.+ */export async function clearConversationFacts(db: BrainEngine, sourceId: string, slug: string,- windows?: Pick<ConversationSegmentsPublication, 'keep' | 'clear' | 'retireUnanchored'>): Promise<number> {+ windows?: { keys: readonly string[]; keep: boolean; unanchored: boolean }): 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 (${WINDOW_KEY_SQL} = ANY($5::text[])) = $6::boolean END)` : '');- const params = windows ? [sourceId, slug, [...AUDIT_ROW_SOURCES], windows.retireUnanchored, [...(windows.keep ?? windows.clear ?? [])], windows.keep === null] : [sourceId, slug];+ ? ` AND NOT (f.source = ANY($3::text[])) AND (CASE WHEN f.source_window IS NULL THEN $4::boolean ELSE (${WINDOW_KEY_SQL} = ANY($5::text[])) <> $6::boolean END)` : '');+ const params = windows ? [sourceId, slug, [...AUDIT_ROW_SOURCES], windows.unanchored, [...windows.keys], 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})`, params);const [relinked] = await db.executeRaw<{ count: string }>(`WITH up AS (UPDATE facts f SET expired_at=now()diff --git a/src/core/facts/conversation-stream.ts b/src/core/facts/conversation-stream.tsindex 4d35b67432..9e2fa83adb 100644--- a/src/core/facts/conversation-stream.ts+++ b/src/core/facts/conversation-stream.ts@@ -2,18 +2,17 @@* PR 4 (Wave B incremental derivation, transcripts): the conversation windows of a segmented page, streamed across its* occurrences (wave-b spec 8.2 "Conversation facts").*- * Messages are parsed one occurrence at a time under one grammar for the whole page: `opts.pattern` (the caller's: a- * current run's recorded grammar, or the one the page's head detects), else the pattern the first parsed text detects.+ * Messages are parsed one occurrence at a time under one grammar for the whole page: `opts.pattern` (the caller's: the+ * one detectPagePattern picks over the whole page, as the whole-page pass picks it), else the pattern the first parsed+ * text detects.* Once known, every later text is parsed under it without detection, so a continuation that would* fail the detector's density floor on its own is still read as the message it continues. The last message of an* occurrence may continue into the next one, so it is held back and parsed again with the next occurrence's text, from* its anchor line and with the day-header date in force there; an occurrence with no anchor line only extends the held* message, unparsed, so a message spanning many occurrences is parsed once. The windows (createWindowStream, the same* gap groups and bounds as the whole-page pass) then run over message boundaries, never over segment cuts, so a window- * can span a cut. Each window is owned by the occurrence its first message starts in and carries the positions of its- * first and last message piece (the occurrence each message starts in, its ordinal among the messages starting there,- * and which piece of an oversized message the window starts or ends with). Reads one- * occurrence's text at a time and holds the carried message and the open window, never the whole body.+ * can span a cut. Each window is owned by the occurrence its first message starts in. Reads one occurrence's text at a+ * time and holds the carried message and the open window, never the whole body.** A run of occurrences is streamed on its own when the occurrence after it opens a gap group: its windows then equal* the whole stream's, because every window before that occurrence closed at the gap. startsConversationRun tells, from@@ -23,20 +22,14 @@import type { Page } from '../types.ts';import { BUILTIN_PATTERNS } from '../conversation-parser/builtins.ts';import { normalizeBlockConversation } from '../conversation-parser/normalize-block.ts';-import { DAY_HEADER_RE, applyPattern, deriveDateContext, isAnchorLine, parseConversation } from '../conversation-parser/parse.ts';+import { DAY_HEADER_RE, applyPattern, createPatternDetector, deriveDateContext, isAnchorLine, parseConversation } from '../conversation-parser/parse.ts';import type { ConversationOccurrence } from '../page-body/segment-conversation.ts';import type { ConversationMessage, ConversationSegment } from './conversation-types.ts';import { DEFAULT_SEGMENT_GAP_MINUTES, MAX_PAGE_SEGMENT_GAP_MINUTES, createWindowStream } from './conversation-windows.ts';-/**- * Where a piece of a message is: the occurrence (an index into the occurrences) the message's anchor line is in, its- * ordinal among the messages starting there, and the piece of it (an oversized message is split into pieces; 0 otherwise).- */-export interface MessagePosition { owner: number; n: number; piece: number }-export interface ConversationStreamSink {- /** A closed window: the positions of its first message (whose occurrence owns the window) and its last. */- window(first: MessagePosition, last: MessagePosition, seg: ConversationSegment): void;+ /** A closed window and the occurrence (an index into the occurrences) its first message starts in, which owns it. */+ window(owner: number, seg: ConversationSegment): void;/** Occurrence `index` was read; `startsGroup`: its first message opens a gap group. */occurrence(index: number, startsGroup: boolean): void;}@@ -55,9 +48,18 @@ interface Carry { parts: string[]; date: string | undefined; owner: number; regiconst gapMinutesFor = (opts: ConversationStreamOpts, patternId: string | null) =>opts.gapMinutes ?? (patternId === 'email-thread-heading' ? MAX_PAGE_SEGMENT_GAP_MINUTES : undefined);-/** The pattern the whole-page pass would pick for a page whose parser input starts with `head`, or null. */-export function detectConversationPattern(head: string, page: Page): string | null {- return parseConversation(head, { page }).matched_pattern_id ?? null;+/**+ * The grammar the whole-page pass picks for the page (parseConversation's choice over its whole parser input: the+ * occurrences in order, truth then timeline joined as readSummaryBody joins them), read one occurrence at a time; null+ * when the page is not a conversation the parser reads.+ */+export async function detectPagePattern(occurrences: readonly ConversationOccurrence[], readText: (index: number) => Promise<string>): Promise<string | null> {+ const detector = createPatternDetector();+ for (let i = 0; i < occurrences.length; i++) {+ if (i > 0 && occurrences[i]!.row.region !== occurrences[i - 1]!.row.region) detector.push('\n\n');+ detector.push(await readText(i));+ }+ return detector.finish();}/** Parse `text` under built-in `patternId` without detection, or detect the pattern when there is none yet. */@@ -132,14 +134,8 @@ export async function streamConversationWindows(occurrences: readonly Conversaticonst pageTitle = opts.page.title || opts.page.slug;let patternId = opts.pattern ?? null;let parsedMessages = 0;- let stream: ReturnType<typeof createWindowStream<{ owner: number; n: number }>> | null = null;+ let stream: ReturnType<typeof createWindowStream<number>> | null = null;let carry: Carry | null = null;- let counted = { owner: -1, n: 0 };- const positionOf = (owner: number) => {- if (counted.owner !== owner) counted = { owner, n: 0 };- return { owner, n: counted.n++ };- };- const at = (position: { owner: number; n: number }, piece: number): MessagePosition => ({ ...position, piece });const joint = (region: string, next: string) => (region === next ? '' : '\n\n');for (let i = from; i < to; i++) {const occurrence = occurrences[i]!;@@ -161,7 +157,7 @@ export async function streamConversationWindows(occurrences: readonly Conversaticonst fallbackDate: string | undefined = carry ? carry.date : occurrence.conversation?.fallbackDate ?? undefined;const parsed = parseUnder(chunk, patternId, opts, fallbackDate);patternId = parsed.patternId;- stream ??= createWindowStream<{ owner: number; n: number }>({ pageTitle, sinceIso: opts.sinceIso, gapMinutes: gapMinutesFor(opts, patternId) });+ stream ??= createWindowStream<number>({ pageTitle, sinceIso: opts.sinceIso, gapMinutes: gapMinutesFor(opts, patternId) });let messages = parsed.messages;parsedMessages += messages.length;const firstOwner = carry ? carry.owner : i;@@ -178,13 +174,13 @@ export async function streamConversationWindows(occurrences: readonly Conversatilet startsGroup: boolean | null = null;messages.forEach((message, k) => {const owner = k === 0 ? firstOwner : i;- const pushed = stream!.push(message, positionOf(owner));+ const pushed = stream!.push(message, owner);if (pushed.accepted && owner === i && startsGroup === null) startsGroup = pushed.startsGroup;- for (const w of pushed.windows) sink.window(at(w.tag, w.firstPiece), at(w.last, w.lastPiece), w.seg);+ for (const w of pushed.windows) sink.window(w.tag, w.seg);});sink.occurrence(i, startsGroup === true);carry = next;}- for (const w of stream?.end() ?? []) sink.window(at(w.tag, w.firstPiece), at(w.last, w.lastPiece), w.seg);+ for (const w of stream?.end() ?? []) sink.window(w.tag, w.seg);return { pattern: patternId, messages: parsedMessages };}diff --git a/src/core/facts/conversation-windows.ts b/src/core/facts/conversation-windows.tsindex a8f85cab31..2c006c1fe9 100644--- a/src/core/facts/conversation-windows.ts+++ b/src/core/facts/conversation-windows.ts@@ -134,11 +134,8 @@ function splitOversizedTurn(m: ConversationMessage, pageTitle: string, maxChars:return splitTurnText(m.text, budget).map((text) => ({ ...m, text }));}-/**- * A closed window: the tag of the message it starts with and of the message it ends with, and which piece of each- * (an oversized turn is split into pieces; 0 for a turn that fits whole).- */-export interface TaggedWindow<Tag> { seg: ConversationSegment; tag: Tag; last: Tag; firstPiece: number; lastPiece: number }+/** A closed window and the tag of the message it starts with. */+export interface TaggedWindow<Tag> { seg: ConversationSegment; tag: Tag }/** What one pushed message did: dropped (filtered out), or accepted, opening a new gap group or not. */export type WindowPush<Tag> = { accepted: false; windows: [] } | { accepted: true; startsGroup: boolean; windows: TaggedWindow<Tag>[] };@@ -159,12 +156,9 @@ export function createWindowStream<Tag>(opts: SplitSegmentsOpts = {}) {let groupMessages = 0;let cur: ConversationMessage[] = [];let curTag: Tag | undefined;- let lastTag: Tag | undefined;- let firstPiece = 0;- let lastPiece = 0;let held: TaggedWindow<Tag>[] = [];const close = (out: TaggedWindow<Tag>[]) => {- if (cur.length > 0) held.push({ seg: segmentOf(cur), tag: curTag as Tag, last: lastTag as Tag, firstPiece, lastPiece });+ if (cur.length > 0) held.push({ seg: segmentOf(cur), tag: curTag as Tag });cur = [];if (groupMessages >= MIN_SEGMENT_MESSAGES) { out.push(...held); held = []; }};@@ -183,13 +177,11 @@ export function createWindowStream<Tag>(opts: SplitSegmentsOpts = {}) {lastTs = ts;groupMessages++;const parts = renderedLength(pageTitle, [m]) <= maxChars ? [m] : splitOversizedTurn(m, pageTitle, maxChars);- parts.forEach((part, piece) => {+ for (const part of parts) {if (cur.length >= maxMessages || (cur.length > 0 && renderedLength(pageTitle, [...cur, part]) > maxChars)) close(windows);- if (cur.length === 0) { curTag = tag; firstPiece = piece; }- lastTag = tag;- lastPiece = piece;+ if (cur.length === 0) curTag = tag;cur.push(part);- });+ }if (groupMessages >= MIN_SEGMENT_MESSAGES && held.length) { windows.push(...held); held = []; }return { accepted: true, startsGroup, windows };},diff --git a/src/core/page-body/segment-conversation.ts b/src/core/page-body/segment-conversation.tsindex 5c08a53912..6b32b893ff 100644--- a/src/core/page-body/segment-conversation.ts+++ b/src/core/page-body/segment-conversation.ts@@ -96,14 +96,18 @@ export async function readConversationOccurrences(engine: BrainEngine, pageId: nreturn { 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> {+/** Bytes conversation facts read to detect a page's grammar over the whole page (conversation-incremental.ts), apart from segmentedPassWork. */+export const conversationDetectionWork = { bytes: 0 };++/** One occurrence's trusted stored text: reads exactly its segment's bytes, counted in segmentedPassWork (conversationDetectionWork with `detection`). */+export async function readOccurrenceText(engine: BrainEngine, body: SegmentedBody, row: BodyRow, opts: { detection?: boolean } = {}): 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;+ if (opts.detection) conversationDetectionWork.bytes += piece.bytes.length;+ else segmentedPassWork.bytes += piece.bytes.length;collect(piece.bytes.length);}return Buffer.concat(parts).toString('utf8');diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.tsindex c87eb4bbcc..d5876d1a9f 100644--- a/src/core/page-embedding-budget.ts+++ b/src/core/page-embedding-budget.ts@@ -294,16 +294,22 @@ class MeteredStepTracker extends BudgetTracker {* throw after the provider answered), and so is every failed attempt it may have billed (MeteredStepTracker); one it* definitively refused before generating (a rate limit, an auth error) and a failed embedding are not; an unpriced* model books the reservation; a step with no billed attempt books nothing. The attempts are reserved and recorded on- * the caller's tracker too, so the caller's cap bounds them.+ * the caller's tracker too, so the caller's cap bounds them. `unpricedModel` names the model when the step was refused+ * under an unpriced model's ceiling estimate or booked its reservation because the model has no price: the caller's+ * receipt then says `unpriced_model` (unpricedModelReceipt) and doctor derivation_unpriced_model names the fix.*/export async function meterPaidCall<T>(engine: BrainEngine, page: BudgetPage, signature: PageSpendSignature, estimateUsd: number,- call: () => Promise<T>, opts: { pricingOverrides?: PricingOverrides } = {}): Promise<{ refused: Extract<PageSpendDecision, { kind: 'refused' }> } | { value: T }> {+ call: () => Promise<T>, opts: { pricingOverrides?: PricingOverrides } = {}): Promise<({ refused: Extract<PageSpendDecision, { kind: 'refused' }> } | { value: T }) & { unpricedModel?: string }> {const decision = await reservePageSpend(engine, page, signature, estimateUsd);- if (decision.kind === 'refused') return { refused: decision };+ // PR 4 (Wave B incremental derivation, transcripts): an unpriced model reserves the ceiling estimate, so a refusal under it is the missing price's.+ const model = signature.slice(signature.indexOf(':') + 1);+ const unpriced = reservationCostUsd(model, 'chat', 1, 1, opts.pricingOverrides) === null ? { unpricedModel: model } : {};+ if (decision.kind === 'refused') return { refused: decision, ...unpriced };if (decision.kind === 'unmetered') return { value: await call() };const tracker = new MeteredStepTracker({ label: `page-spend:${signature}`, pricingOverrides: opts.pricingOverrides, providerRetries: 0 }, getCurrentBudgetTracker(), opts.pricingOverrides);try {- return { value: await withBudgetTracker(tracker, call) };+ const value = await withBudgetTracker(tracker, call);+ return { value, ...(tracker.unpricedAttempts > 0 ? { unpricedModel: model } : {}) };} finally {await decision.grant.settle({ ok: tracker.billedAttempts > 0, usd: tracker.unpricedAttempts > 0 ? decision.grant.reservedUsd : tracker.billedUsd });}@@ -449,3 +455,15 @@ export function sizeStateLines(tally: SyncSizeStates | undefined): string[] {if (tally.total > lines.length) lines.push(` ... and ${tally.total - lines.length} more large or embed_skip page(s) (--json lists the first ${tally.pages.length}).`);return lines;}++/**+ * The receipt a segmented derivation occurrence carries when its model has no price (PR 4, Wave B incremental+ * derivation): an unread_windows receipt the cap stopped under the model's ceiling estimate says reason `unpriced_model`+ * and the model; a finished one that booked a reservation for an unpriced call is `{ kind: 'unpriced_model', model }`.+ * Doctor derivation_unpriced_model reads both. `stop` is the run's stop reason; `unread` the windows left, if any.+ */+export function unpricedModelReceipt(pipeline: string, model: string | null, stop: string | null,+ unread: { windows_read: number; windows_total: number } | null): Record<string, unknown> | null {+ if (unread) return { kind: 'unread_windows', pipeline, reason: model && stop === 'cap_reached' ? 'unpriced_model' : stop, ...unread, ...(model ? { model } : {}) };+ return model ? { kind: 'unpriced_model', pipeline, model } : null;+}diff --git a/test/conversation-parser/pattern-detector.test.ts b/test/conversation-parser/pattern-detector.test.tsnew file mode 100644index 0000000000..20fa06d8ea--- /dev/null+++ b/test/conversation-parser/pattern-detector.test.ts@@ -0,0 +1,83 @@+/**+ * createPatternDetector (conversation-parser/parse.ts) against parseConversation: the streamed whole-page grammar+ * detection conversation facts uses on a segmented page (PR 4 lane 4b round 5, F3).+ *+ * 1. Protects: fed any body in arbitrary pieces (cut mid-line, CRLF or LF), the detector picks exactly the pattern+ * parseConversation(body) matches, or null when it matches none: head pass, full-body re-score, score_full_body+ * re-score, acceptance floor, structure gate, block-format collapse and the speaker-object region scan included.+ * 2. Fails when: the detector diverges from the whole-page parser on any seeded body (a preamble that tips the head+ * pass, a block header deep in the body, an invalid speaker-object region, a label list with no repeated speaker).+ */+import { describe, expect, test } from 'bun:test';+import { BUILTIN_PATTERNS } from '../../src/core/conversation-parser/builtins.ts';+import { createPatternDetector, parseConversation } from '../../src/core/conversation-parser/parse.ts';++const POSITIVE = BUILTIN_PATTERNS.flatMap(p => p.test_positive ?? []);+const NEGATIVE = BUILTIN_PATTERNS.flatMap(p => p.test_negative ?? []);+const OTHER = [+ '', '', ' ', '# Meeting', '## Summary', '## Transcript', '## Action Items', '## 2025-01-02', '### 2025-03-04', '```', '~~~', ' indented code',+ "{'source': 'microphone', 'attribution': 'me'}: hello", "{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi",+ "Alice's update was \"ready\" (after review).", 'An unfinished list [', 'Quoted note: "unfinished', '- **Theo** (Mon 11:18)', '- **Juan** (11:20 AM)',+ ' Body line of a block message.', '**Note:** remember the budget', '**Alice Example:** okay', '**Bob Example:** sure thing', 'User: one line of a preamble',+ 'The roadmap review moved to next quarter and the budget stays flat.', 'Plain prose about the launch and the hiring plan.', '---', '> quoted line',+];++function rng(seed: number) {+ let s = seed >>> 0 || 1;+ return () => { s = (s * 1103515245 + 12345) & 0x7fffffff; return s / 0x7fffffff; };+}++/** A seeded body: random lines, or a preamble then one pattern's positives repeated, with random noise. */+function body(seed: number): string {+ const next = rng(seed);+ const pick = <T>(xs: readonly T[]) => xs[Math.floor(next() * xs.length)]!;+ const lines: string[] = [];+ if (next() < 0.5) {+ for (let i = Math.floor(next() * 120); i > 0; i--) lines.push(pick(next() < 0.4 ? POSITIVE : next() < 0.5 ? NEGATIVE : OTHER));+ } else {+ const entry = pick(BUILTIN_PATTERNS);+ for (let i = Math.floor(next() * 40); i > 0; i--) lines.push(pick(next() < 0.3 ? POSITIVE : OTHER));+ for (let i = 1 + Math.floor(next() * 80); i > 0; i--) {+ lines.push(next() < 0.85 ? pick(entry.test_positive ?? POSITIVE) : pick(OTHER));+ if (next() < 0.3) lines.push('');+ }+ for (let i = Math.floor(next() * 10); i > 0; i--) lines.push(pick(OTHER));+ }+ return lines.join(next() < 0.2 ? '\r\n' : '\n');+}++/** The detector's pick over \`text\` fed in seeded pieces. */+function detect(text: string, seed: number): string | null {+ const next = rng(seed * 31 + 7);+ const detector = createPatternDetector();+ for (let at = 0; at < text.length;) {+ const size = 1 + Math.floor(next() * (next() < 0.5 ? 8 : 400));+ detector.push(text.slice(at, at + size));+ at += size;+ }+ return detector.finish();+}++describe('createPatternDetector', () => {+ test('picks what parseConversation picks on 3000 seeded bodies fed in arbitrary pieces', () => {+ const mismatches: Array<{ seed: number; parsed: string | null; detected: string | null }> = [];+ const picked = new Set<string | null>();+ for (let seed = 1; seed <= 3000; seed++) {+ const text = body(seed);+ const parsed = parseConversation(text).matched_pattern_id ?? null;+ const detected = detect(text, seed);+ picked.add(parsed);+ if (parsed !== detected) mismatches.push({ seed, parsed, detected });+ }+ expect(mismatches.slice(0, 10)).toEqual([]);+ expect(picked.size).toBeGreaterThan(12);+ });++ test('a preamble that tips the head pass loses to the transcript the whole body holds', () => {+ const preamble = Array.from({ length: 4000 }, (_, i) => (i % 4 === 3 ? 'User: a line of the preamble' : `Notes line ${i} about the roadmap review.`)).join('\n');+ const transcript = Array.from({ length: 30000 }, (_, i) => `**${['Alice Example', 'Bob Example'][i % 2]}** (9:${String(i % 60).padStart(2, '0')} AM): budget and launch.`).join('\n\n');+ const text = `${preamble}\n\n${transcript}`;+ expect(parseConversation(text.slice(0, 64 * 1024)).matched_pattern_id).toBe('plain-role-no-time');+ expect({ parsed: parseConversation(text).matched_pattern_id, detected: detect(text, 1) }).toEqual({ parsed: 'bold-paren-time-12h', detected: 'bold-paren-time-12h' });+ });+});diff --git a/test/conversation-stream-work.test.ts b/test/conversation-stream-work.test.tsindex 6d5424ab37..063f0d130a 100644--- a/test/conversation-stream-work.test.ts+++ b/test/conversation-stream-work.test.ts@@ -58,7 +58,7 @@ test('a message spanning 40 occurrences is parsed once, and the windows equal thconst windows: string[] = [];try {await streamConversationWindows(occurrences, 0, occurrences.length, { page, gapMinutes: null }, async i => texts[i]!, {- window(_first, _last, seg) { windows.push(renderSegmentForExtraction('Stream work', seg)); },+ window(_owner, seg) { windows.push(renderSegmentForExtraction('Stream work', seg)); },occurrence() {},});} finally {diff --git a/test/e2e/conversation-facts-incremental-postgres.test.ts b/test/e2e/conversation-facts-incremental-postgres.test.tsindex 936a8b5721..380fceba0a 100644--- a/test/e2e/conversation-facts-incremental-postgres.test.ts+++ b/test/e2e/conversation-facts-incremental-postgres.test.ts@@ -7,6 +7,8 @@ import { afterAll, beforeAll, describe } from 'bun:test';import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';import { defineDerivationSpendCases } from '../helpers/derivation-spend-cases.ts';import { defineConversationFactsRecoveryCases } from '../helpers/conversation-facts-recovery-cases.ts';+import { defineConversationFactsInvariantCases } from '../helpers/conversation-facts-invariant-cases.ts';+import { defineDerivationUnpricedCases } from '../helpers/derivation-unpriced-cases.ts';import { defineConversationFactsIncrementalCases, defineSegmentedAtomsCases, defineSegmentedBackstopCases, defineSegmentReceiptDoctorCases } from '../helpers/conversation-facts-incremental-cases.ts';import { hasDatabase } from './helpers.ts';@@ -20,4 +22,6 @@ import { hasDatabase } from './helpers.ts';defineSegmentReceiptDoctorCases({ getBrain: () => brain });defineDerivationSpendCases({ getBrain: () => brain });defineConversationFactsRecoveryCases({ getBrain: () => brain });+ defineConversationFactsInvariantCases({ getBrain: () => brain });+ defineDerivationUnpricedCases({ getBrain: () => brain });});diff --git a/test/e2e/conversation-facts-property-postgres.test.ts b/test/e2e/conversation-facts-property-postgres.test.tsnew file mode 100644index 0000000000..1833800c15--- /dev/null+++ b/test/e2e/conversation-facts-property-postgres.test.ts@@ -0,0 +1,16 @@+/**+ * Seeded property test of the conversation facts deletion invariant, Postgres arm (PR 4 lane 4b round 5). Cases:+ * test/helpers/conversation-facts-property-cases.ts. PGLite arm: test/large-pages/conversation-facts-property.test.ts.+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';+import { defineConversationFactsPropertyCases } from '../helpers/conversation-facts-property-cases.ts';+import { hasDatabase } from './helpers.ts';++(hasDatabase() ? describe : describe.skip)('conversation facts deletion invariant [postgres]', () => {+ let brain: AppendBrain;+ let fresh: AppendBrain;+ beforeAll(async () => { brain = await openAppendBrain('postgres'); fresh = await openAppendBrain('postgres'); }, 120_000);+ afterAll(async () => { await brain.close(); await fresh.close(); }, 120_000);+ defineConversationFactsPropertyCases({ getBrain: () => brain, getFresh: () => fresh });+});diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex e4b55a8201..7925ba98b5 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -889,6 +889,10 @@"category": "brain","name": "extraction_input_truncated"},+ {+ "category": "brain",+ "name": "derivation_unpriced_model"+ },{"category": "brain","name": "ghost_pages"diff --git a/test/helpers/conversation-facts-invariant-cases.ts b/test/helpers/conversation-facts-invariant-cases.tsnew file mode 100644index 0000000000..47ded6713b--- /dev/null+++ b/test/helpers/conversation-facts-invariant-cases.ts@@ -0,0 +1,173 @@+/**+ * Conversation facts deletion invariant on a segmented page (wave-b spec 8.2; PR 4 lane 4b round 5), 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). Fake extractors only; appends go through the remote+ * append_page operation (remote=true).+ *+ * 1. Protects: a partial run only adds and replaces facts per window key, and a row claims exactly the facts it holds:+ * two interrupted runs after an append lose no fact a row claims (F1); a window marked failed right after an append+ * leaves the facts of the window the append retired standing (F2); a run that re-extracts every window under an+ * unchanged key (a model change) leaves one batch per key (F6); rows from an older derivation version are never+ * read as window positions (F9); the grammar is detected over the whole page, not its head (F3), and that read is+ * counted; a page that reads as a transcript yet parses no message changes nothing and leaves a no_messages receipt.+ * 2. Fails when: anything but an exact-key replacement or a fully settled collection deletes a fact, a moved window's+ * old row keeps claiming it, a settling run keeps the old batch beside the new one, or the head of a page picks its+ * grammar.+ */+import { expect, spyOn, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { AppendBrain } from './append-brain.ts';+import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';+import { PAGE_DERIVATION_CAP_KEY } from '../../src/core/page-spend.ts';+import * as parser from '../../src/core/conversation-parser/parse.ts';+import { renderSegmentForExtraction, splitIntoSegments } from '../../src/core/facts/conversation-windows.ts';+import { WINDOW_FAILURE_LIMIT } from '../../src/core/facts/conversation-incremental.ts';+import { conversationDetectionWork } from '../../src/core/page-body/segment-conversation.ts';+import { extractionInputTruncatedEntry } from '../../src/commands/doctor/checks/extraction-input.ts';+import type { DoctorContext } from '../../src/commands/doctor/context.ts';+import type { Check } from '../../src/commands/doctor.ts';+import { chatDays, chatPage, derivations, extract, factsOf, turns } from './conversation-facts-incremental-cases.ts';++const caps = async (engine: BrainEngine, usd: string) => { await engine.setConfig(PAGE_DERIVATION_CAP_KEY, usd); await engine.setConfig(PAGE_EMBED_CAP_KEY, usd); };++/** Window records some row claims whose facts in the table are not exactly what the record says. */+export async function claimMismatches(engine: BrainEngine, slug: string) {+ const rows = await derivations(engine, slug);+ const facts = await factsOf(engine, slug);+ const count = new Map<string, number>();+ for (const f of facts) count.set(f.key, (count.get(f.key) ?? 0) + 1);+ return rows.rows.flatMap(row => ((row.output as { windows?: Array<{ ordinal: number; sha: string; facts: number }> })?.windows ?? [])+ .map(w => ({ key: `${row.occurrenceId}:${w.ordinal}:${w.sha}`, claimed: w.facts }))+ .filter(w => (count.get(w.key) ?? 0) !== w.claimed).map(w => ({ ...w, held: count.get(w.key) ?? 0 })));+}++export function defineConversationFactsInvariantCases(opts: { getBrain: () => AppendBrain }): void {+ test('F1: two interrupted runs after an append lose no fact and leave every row claiming exactly the facts it holds', async () => {+ const brain = opts.getBrain();+ const slug = `notes/interrupted-moves-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Interrupted moves', chatDays(3800, 100, 31)));+ await extract(brain.engine, slug);+ const before = await factsOf(brain.engine, slug);+ // Three hundred more turns on the last day: its windows move to the occurrences the append makes.+ expect(await brain.call('append_page', { slug, text: turns(3899, 50, 300, 31), request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });+ const outcomes: unknown[] = [];+ for (const abortAfter of [2, 3]) {+ await extract(brain.engine, slug, { abortAfter }).catch(() => undefined);+ const now = await factsOf(brain.engine, slug);+ outcomes.push({ lost: before.filter(f => !now.some(n => n.id === f.id)).length, mismatches: (await claimMismatches(brain.engine, slug)).slice(0, 3) });+ }+ expect(outcomes).toEqual([{ lost: 0, mismatches: [] }, { lost: 0, mismatches: [] }]);+ await extract(brain.engine, slug);+ const after = await factsOf(brain.engine, slug);+ const rows = await derivations(brain.engine, slug);+ expect({ mismatches: await claimMismatches(brain.engine, slug), facts: after.length, anchored: after.every(f => rows.keys.includes(f.key)), states: [...new Set(rows.states)] })+ .toEqual({ mismatches: [], facts: rows.keys.length, anchored: true, states: ['done'] });+ }, 600_000);++ test('F2: a window marked failed right after an append leaves the facts of the window the append retired standing', async () => {+ const brain = opts.getBrain();+ const slug = `notes/failed-after-append-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Failed after append', chatDays(3900, 100, 32)));+ await extract(brain.engine, slug);+ const before = await factsOf(brain.engine, slug);+ // Two more turns on the last day: its last window grows, and the window it was is retired.+ expect(await brain.call('append_page', { slug, text: turns(3999, 50, 2, 32), request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });+ let grown = null as string | null;+ const failOn = (text: string) => { grown ??= text; return text === grown; };+ for (let run = 1; run <= WINDOW_FAILURE_LIMIT; run++) await extract(brain.engine, slug, { failOn });+ const after = await factsOf(brain.engine, slug);+ const rows = await derivations(brain.engine, slug);+ expect({ lost: before.filter(f => !after.some(a => a.id === f.id)).length, failed: rows.receipts.filter(r => (r as { kind?: string } | null)?.kind === 'failed_windows').length,+ mismatches: await claimMismatches(brain.engine, slug) }).toEqual({ lost: 0, failed: 1, mismatches: [] });+ }, 600_000);++ test('F6: a model change re-extracts every window under its unchanged key and leaves one batch per key', async () => {+ const brain = opts.getBrain();+ const slug = `notes/model-change-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Model change', chatDays(4000, 100, 33)));+ await extract(brain.engine, slug);+ const before = await factsOf(brain.engine, slug);+ await brain.engine.setConfig('facts.extraction_model', 'anthropic:claude-haiku-4-5');+ try {+ const { calls, result } = await extract(brain.engine, slug, { force: true });+ const after = await factsOf(brain.engine, slug);+ const rows = await derivations(brain.engine, slug);+ const perKey = new Map<string, number>();+ for (const f of after) perKey.set(f.key, (perKey.get(f.key) ?? 0) + 1);+ expect({ calls: calls.length, facts: after.length, keys: new Set(rows.keys).size, sameKeys: [...perKey.keys()].sort().join() === before.map(f => f.key).sort().join(),+ doubled: [...perKey.values()].filter(n => n > 1).length, survivors: before.filter(f => after.some(a => a.id === f.id)).length, cleaned: result.orphan_facts_cleaned })+ .toEqual({ calls: before.length, facts: before.length, keys: before.length, sameKeys: true, doubled: 0, survivors: 0, cleaned: before.length + 1 });+ } finally {+ await brain.engine.setConfig('facts.extraction_model', '');+ }+ }, 600_000);++ test('F9: rows from an older derivation version (round-3 spans) are never read as positions: a one-window run after an append deletes nothing', async () => {+ const brain = opts.getBrain();+ const slug = `notes/old-rows-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Old rows', chatDays(4100, 100, 34)));+ await extract(brain.engine, slug);+ const before = await factsOf(brain.engine, slug);+ const { pageId, rows } = await derivations(brain.engine, slug);+ // Version 1 rows: spans were [occurrence, ordinal, occurrence, ordinal].+ for (const row of rows) {+ const output = row.output as { windows: Array<Record<string, unknown>> };+ const windows = output.windows.map(w => ({ ...w, span: [row.occurrenceId, 0, row.occurrenceId, 40] }));+ await brain.engine.executeRaw(`UPDATE page_segment_derivations SET pipeline_version = 1, output = $1::jsonb WHERE page_id = $2 AND pipeline = 'conversation_facts' AND occurrence_id = $3`,+ [JSON.stringify({ ...output, windows }), pageId, row.occurrenceId]);+ }+ expect(await brain.call('append_page', { slug, text: turns(4199, 50, 2, 34), request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });+ const limited = await extract(brain.engine, slug, { segmentLimit: 1 });+ const after = await factsOf(brain.engine, slug);+ expect({ calls: limited.calls.length, facts: after.length, lost: before.filter(f => !after.some(a => a.id === f.id)).length, cleaned: limited.result.orphan_facts_cleaned })+ .toEqual({ calls: 1, facts: before.length + 1, lost: 0, cleaned: 0 });+ }, 600_000);++ test('F3: the grammar is the whole page\'s, not its head\'s; the detection read is counted once, and a run on a pinned grammar reads none', async () => {+ const brain = opts.getBrain();+ const slug = `notes/preamble-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ const preamble = Array.from({ length: 4000 }, (_, i) => (i % 4 === 3 ? 'User: a line of the preamble' : `Notes line ${i} about the roadmap review.`)).join('\n');+ await brain.seed(slug, chatPage('Preamble', `${preamble}\n\n${chatDays(4200, 100, 35)}`));+ const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;+ const truth = (await brain.body(slug)).truth;+ expect(parser.parseConversation(truth.slice(0, 64 * 1024), { page }).matched_pattern_id).toBe('plain-role-no-time');+ expect(parser.parseConversation(truth, { page }).matched_pattern_id).toBe('bold-paren-time-12h');+ const expected = splitIntoSegments(parser.parseConversation(truth, { page }).messages, { pageTitle: 'Preamble' }).map(seg => renderSegmentForExtraction('Preamble', seg));+ const detected = conversationDetectionWork.bytes;+ const { calls } = await extract(brain.engine, slug, { segmentLimit: 5 });+ const read = conversationDetectionWork.bytes - detected;+ const rest = await extract(brain.engine, slug);+ const all = [...calls, ...rest.calls];+ expect({ read, again: conversationDetectionWork.bytes - detected - read, same: [...all].sort().join('\n') === [...expected].sort().join('\n') })+ .toEqual({ read: Buffer.byteLength(truth), again: 0, same: true });+ }, 600_000);++ test('a page that reads as a transcript yet parses no message changes nothing and leaves a no_messages receipt doctor lists', async () => {+ const brain = opts.getBrain();+ const slug = `notes/parser-fault-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Parser fault', chatDays(4300, 100, 36)));+ await extract(brain.engine, slug);+ const before = (await factsOf(brain.engine, slug)).map(f => f.id);+ await brain.seed(slug, chatPage('Parser fault', Array.from({ length: 8000 }, (_, i) => `Paragraph ${i} of the notes: the roadmap review moved to next quarter and the budget stays flat.`).join('\n\n')));+ // A detector fault: it reports a transcript format the page's text does not hold.+ const spy = spyOn(parser, 'createPatternDetector').mockImplementation(() => ({ push() {}, finish: () => 'bold-paren-time-12h' }));+ try {+ const { calls, result } = await extract(brain.engine, slug);+ expect({ calls: calls.length, failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, cleaned: result.orphan_facts_cleaned,+ facts: (await factsOf(brain.engine, slug)).map(f => f.id) }).toEqual({ calls: 0, failed: 1, nonExtractable: 0, cleaned: 0, facts: before });+ } finally {+ spy.mockRestore();+ }+ const check = (await extractionInputTruncatedEntry.run({ engine: brain.engine } as unknown as DoctorContext) as Check[]).find(c => c.name === 'extraction_input_truncated')!;+ const groups = (check.details as { groups: Array<{ pipeline: string; kind: string; samples: string[]; remedy: string | null }> }).groups;+ const group = groups.find(g => g.pipeline === 'conversation_facts' && g.kind === 'no_messages');+ expect({ listed: group?.samples.includes(`default:${slug}`), fault: group?.remedy?.includes('parser fault') }).toEqual({ listed: true, fault: true });+ }, 600_000);+}diff --git a/test/helpers/conversation-facts-property-cases.ts b/test/helpers/conversation-facts-property-cases.tsnew file mode 100644index 0000000000..6bfcc7dad8--- /dev/null+++ b/test/helpers/conversation-facts-property-cases.ts@@ -0,0 +1,227 @@+/**+ * Seeded property test of the conversation facts deletion invariant on a segmented page (wave-b spec 8.2; PR 4 lane 4b+ * round 5), shared by the PGLite arm (test/large-pages/conversation-facts-property.test.ts) and the Postgres arm+ * (test/e2e/conversation-facts-property-postgres.test.ts). A fake extractor yields one to three facts per window,+ * determined by the window's text; no model is called.+ *+ * Each of PROPERTY_SEEDS seeds runs PROPERTY_STEPS steps, each an optional change (an append on the last day or a new+ * day through the remote append_page, a mid-page edit, insert, delete or oversized turn, a title of another length, a+ * visibility, model or derivation-version change) followed by one run under an optional constraint (a provider-wide+ * failure, a window-specific failure, a cap, an abort, --since, --segment-limit, --force). After every step:+ * (i) a fact that disappeared had its exact window key extracted again (or a moved window's facts re-anchored onto+ * it) in that step, or the step fully settled the page and its key is no current window's; a moved fact keeps+ * its window text;+ * (ii) every window key holds exactly one batch: the fact count its text yields, no fact twice;+ * (iii) every window a row claims holds exactly the facts the row says, and a settled page holds only current windows.+ * At the end a healthy unconstrained --force run leaves the same windows and facts as one extraction of the same page on+ * a fresh brain.+ *+ * 1. Protects: deletion only by exact-key replacement or settled collection, rows claiming exactly what exists.+ * 2. Fails when: any partial-run path deletes by coverage, keeps or stale bookkeeping, a move loses or duplicates a+ * batch, a settling run leaves an old batch beside a new one, or incremental runs drift from a fresh extraction.+ */+import { expect, test } from 'bun:test';+import { createHash, randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { AppendBrain } from './append-brain.ts';+import { runExtractConversationFactsCore } from '../../src/commands/extract-conversation-facts.ts';+import { CONVERSATION_FACTS_DERIVATION_VERSION } from '../../src/core/facts/conversation-incremental.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 { PAGE_DERIVATION_CAP_KEY } from '../../src/core/page-spend.ts';+import { __setChatTransportForTests, chat as gatewayChat } from '../../src/core/ai/gateway.ts';+import { chatDays, chatPage, derivations, PAID_MODEL, paidTransport, SOURCE, turns } from './conversation-facts-incremental-cases.ts';+import { claimMismatches } from './conversation-facts-invariant-cases.ts';++export const PROPERTY_SEEDS = 30;+export const PROPERTY_STEPS = 16;+const FIRST_DAY = 5000;+const DAYS = 100;+const WORDS = ['launch', 'pricing', 'budget', 'roadmap', 'hiring', 'review', 'contract', 'latency', 'onboarding', 'forecast', 'retention', 'deploy'];+const sha = (text: string) => createHash('sha256').update(text).digest('hex');+const dateOf = (day: number) => new Date(Date.UTC(2025, 0, 1) + day * 86_400_000).toISOString().slice(0, 10);+/** Facts the fake extractor yields for a window, by its text. */+const yieldOf = (windowSha: string) => 1 + (parseInt(windowSha.slice(0, 2), 16) % 3);++function rng(seed: number) {+ let s = (seed * 2654435761) >>> 0 || 1;+ return () => { s = (s * 1103515245 + 12345) & 0x7fffffff; return s / 0x7fffffff; };+}++interface Fact { id: number; key: string; fact: string }+async function factsOf(engine: BrainEngine, slug: string): Promise<Fact[]> {+ const rows = await engine.executeRaw<{ id: number; w: unknown; fact: string }>(+ `SELECT id, source_window AS w, fact 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 w = parseSourceWindow(row.w) as SourceWindow | null; return { id: Number(row.id), key: w ? sourceWindowKey(w) : 'unanchored', fact: row.fact }; });+}+const shaOf = (key: string) => key.split(':')[2] ?? key;++interface RunOpts { force?: boolean; segmentLimit?: number; sinceIso?: string; abortAfter?: number; failAt?: number; doomed?: boolean; paid?: boolean }++/** One extraction run with the deterministic fake extractor; returns whether it threw and its counters. */+async function run(engine: BrainEngine, slug: string, o: RunOpts) {+ const controller = new AbortController();+ let calls = 0;+ try {+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [slug], sleepMs: 0, force: o.force, sinceIso: o.sinceIso, segmentLimit: o.segmentLimit,+ extractor: async input => {+ calls++;+ const windowSha = sha(input.turnText);+ if (o.paid) await gatewayChat({ model: PAID_MODEL, messages: [{ role: 'user', content: input.turnText }], maxTokens: 64 });+ if (calls === o.failAt) throw Object.assign(new Error('fake provider: upstream unavailable'), { status: 503 });+ if (o.doomed && /^[01]/.test(windowSha)) throw Object.assign(new Error('fake extractor: malformed output on this window'), { extractionReason: 'malformed_output' });+ if (calls === o.abortAfter) controller.abort();+ return Array.from({ length: yieldOf(windowSha) }, (_, j) => ({ fact: `Alice Example noted window ${windowSha.slice(0, 16)} item ${j}`, kind: 'fact', entity_slug: null, source: SOURCE }));+ } }, controller.signal);+ return { threw: false, failed: result.pages_failed };+ } catch {+ return { threw: true, failed: 1 };+ }+}++/** Every window key some row records, whether the page is fully settled, and the live occurrences' row windows. */+async function pageState(engine: BrainEngine, slug: string) {+ const d = await derivations(engine, slug);+ const liveRows = d.rows.filter(row => d.live.includes(row.occurrenceId));+ const windowsOf = (row: (typeof d.rows)[number]) => ((row.output as { windows?: Array<{ ordinal: number; sha: string; failed?: unknown }> })?.windows ?? []);+ const liveKeys = new Set(liveRows.flatMap(row => windowsOf(row).map(w => `${row.occurrenceId}:${w.ordinal}:${w.sha}`)));+ const settled = liveRows.length === d.live.length && liveRows.every(row => row.state === 'done' && row.version === CONVERSATION_FACTS_DERIVATION_VERSION)+ && d.rows.every(row => windowsOf(row).every(w => !w.failed));+ return { liveKeys, settled, windowShas: liveRows.flatMap(row => windowsOf(row).map(w => w.sha)).sort() };+}++/** Problems with one page's facts after a step (the module doc's (i)–(iii)). */+async function violations(engine: BrainEngine, slug: string, before: Fact[], o: RunOpts, outcome: { threw: boolean; failed: number }) {+ const after = await factsOf(engine, slug);+ const state = await pageState(engine, slug);+ const fullySettled = !outcome.threw && outcome.failed === 0 && !o.sinceIso && state.settled;+ const beforeById = new Map(before.map(f => [f.id, f]));+ const afterById = new Map(after.map(f => [f.id, f]));+ const replaced = new Set([...after.filter(f => !beforeById.has(f.id)).map(f => f.key),+ ...after.filter(f => beforeById.has(f.id) && beforeById.get(f.id)!.key !== f.key).map(f => f.key)]);+ const problems: string[] = [];+ for (const f of before) {+ if (afterById.has(f.id)) continue;+ if (replaced.has(f.key) || (fullySettled && !state.liveKeys.has(f.key))) continue;+ problems.push(`(i) fact ${f.id} of window ${f.key} disappeared without its window being extracted again or a settled collection`);+ }+ for (const f of after) {+ const was = beforeById.get(f.id);+ if (was && shaOf(was.key) !== shaOf(f.key)) problems.push(`(i) fact ${f.id} moved from ${was.key} to a window of other text ${f.key}`);+ }+ const perKey = new Map<string, Fact[]>();+ for (const f of after) perKey.set(f.key, [...(perKey.get(f.key) ?? []), f]);+ for (const [key, facts] of perKey) {+ if (key === 'unanchored') continue;+ if (facts.length !== yieldOf(shaOf(key)) || new Set(facts.map(f => f.fact)).size !== facts.length) problems.push(`(ii) window ${key} holds ${facts.length} facts, ${new Set(facts.map(f => f.fact)).size} distinct; its text yields ${yieldOf(shaOf(key))}`);+ }+ for (const m of await claimMismatches(engine, slug)) problems.push(`(iii) a row claims ${m.claimed} facts of ${m.key}; it holds ${m.held}`);+ if (fullySettled) for (const key of perKey.keys()) if (!state.liveKeys.has(key)) problems.push(`(iii) the settled page still holds facts of ${key}, no current window`);+ return { problems, after };+}++export function defineConversationFactsPropertyCases(opts: { getBrain: () => AppendBrain; getFresh: () => AppendBrain }): void {+ for (let seed = 1; seed <= PROPERTY_SEEDS; seed++) {+ test(`seed ${seed}: ${PROPERTY_STEPS} seeded changes and constrained runs keep the deletion invariant, and the page converges to a fresh extraction`, async () => {+ const brain = opts.getBrain();+ const engine = brain.engine;+ const next = rng(seed);+ const pick = <T>(xs: readonly T[]) => xs[Math.floor(next() * xs.length)]!;+ const words = (n: number) => Array.from({ length: n }, () => pick(WORDS)).join(' ');+ const slug = `notes/property-${seed}-${randomUUID().slice(0, 8)}`;+ for (const key of [PAGE_DERIVATION_CAP_KEY, PAGE_EMBED_CAP_KEY]) await engine.setConfig(key, 'off');+ await engine.setConfig('facts.extraction_model', '');+ await engine.setConfig('facts.default_visibility', 'private');+ let title = 'Property chat';+ let lastDay = FIRST_DAY + DAYS - 1;+ let nextTurn = 50;+ await brain.seed(slug, chatPage(title, chatDays(FIRST_DAY, DAYS, seed)));+ const log: string[] = [];+ let facts = await factsOf(engine, slug);+ const reseed = async (edit: (lines: string[], turnsAt: number[]) => void) => {+ const lines = (await brain.body(slug)).truth.split('\n');+ const turnsAt = lines.flatMap((line, i) => (line.startsWith('**') ? [i] : []));+ edit(lines, turnsAt.slice(Math.floor(turnsAt.length / 3), Math.floor((2 * turnsAt.length) / 3)));+ await brain.seed(slug, chatPage(title, lines.join('\n')));+ };+ try {+ for (let step = 1; step <= PROPERTY_STEPS + 1; step++) {+ const final = step > PROPERTY_STEPS;+ const change = final ? 'none' : pick(['none', 'none', 'append', 'append', 'append', 'new-day', 'edit', 'edit', 'insert', 'insert', 'delete', 'oversized',+ 'title', 'title', 'visibility', 'model', 'version'] as const);+ if (change === 'append') {+ const count = 1 + Math.floor(next() * 20);+ expect(await brain.call('append_page', { slug, text: turns(lastDay, nextTurn, count, seed * 100 + step), request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });+ nextTurn += count;+ } else if (change === 'new-day') {+ lastDay++;+ nextTurn = 1 + Math.floor(next() * 30);+ expect(await brain.call('append_page', { slug, text: `## ${dateOf(lastDay)}\n\n${turns(lastDay, 0, nextTurn, seed * 100 + step)}`, request_id: randomUUID() }, { remote: true }))+ .toMatchObject({ isError: false });+ } else if (change === 'edit' || change === 'oversized') {+ await reseed((lines, mid) => { const i = pick(mid); lines[i] = lines[i]!.replace(/\): .*$/, `): ${words(change === 'oversized' ? 1800 : 5 + Math.floor(next() * 40))} (step ${step}).`); });+ } else if (change === 'insert') {+ await reseed((lines, mid) => { const i = pick(mid); lines.splice(i + 1, 0, '', lines[i]!.replace(/\): .*$/, `): ${words(10 + Math.floor(next() * 30))} (inserted ${step}).`)); });+ } else if (change === 'delete') {+ await reseed((lines, mid) => { lines.splice(pick(mid), 1); });+ } else if (change === 'title') {+ title = `Property ${words(1 + Math.floor(next() * 12))}`;+ await reseed(() => {});+ } else if (change === 'visibility') {+ await engine.setConfig('facts.default_visibility', (await engine.getConfig('facts.default_visibility')) === 'world' ? 'private' : 'world');+ } else if (change === 'model') {+ await engine.setConfig('facts.extraction_model', (await engine.getConfig('facts.extraction_model')) === PAID_MODEL ? '' : PAID_MODEL);+ } else if (change === 'version') {+ const { pageId, rows } = await derivations(engine, slug);+ for (const row of rows) {+ const output = row.output as { windows?: Array<Record<string, unknown>> };+ const windows = (output.windows ?? []).map(w => ({ ...w, span: [row.occurrenceId, Number(w.ordinal), row.occurrenceId, Number(w.ordinal) + 3] }));+ await engine.executeRaw(`UPDATE page_segment_derivations SET pipeline_version = $1, output = $2::jsonb WHERE page_id = $3 AND pipeline = 'conversation_facts' AND occurrence_id = $4`,+ [1 + Math.floor(next() * (CONVERSATION_FACTS_DERIVATION_VERSION - 1)), JSON.stringify({ ...output, windows }), pageId, row.occurrenceId]);+ }+ }+ const constraint = final ? 'force' : pick(['none', 'none', 'none', 'limit', 'limit', 'abort', 'abort', 'provider', 'provider', 'doomed', 'doomed', 'since', 'cap', 'force'] as const);+ const o: RunOpts = {};+ if (constraint === 'force' || (['visibility', 'model', 'version'].includes(change) && next() < 0.7)) o.force = true;+ if (constraint === 'limit') o.segmentLimit = 1 + Math.floor(next() * 20);+ if (constraint === 'abort') o.abortAfter = 1 + Math.floor(next() * 30);+ if (constraint === 'provider') o.failAt = 1 + Math.floor(next() * 30);+ if (constraint === 'doomed') o.doomed = true;+ if (constraint === 'since') o.sinceIso = `${dateOf(FIRST_DAY + Math.floor(next() * (lastDay - FIRST_DAY)))}T12:00:00Z`;+ if (constraint === 'cap') {+ const { pageId } = await derivations(engine, slug);+ const [ledger] = await engine.executeRaw<{ spent: number }>("SELECT spent_usd AS spent FROM page_derivation_spend WHERE page_id=$1 AND family='facts'", [pageId]);+ await engine.setConfig(PAGE_DERIVATION_CAP_KEY, (Number(ledger?.spent ?? 0) + 0.02 + next() * 0.3).toFixed(4));+ __setChatTransportForTests(paidTransport);+ o.paid = true;+ }+ const outcome = await run(engine, slug, o).finally(async () => {+ __setChatTransportForTests(null);+ await engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');+ });+ const checked = await violations(engine, slug, facts, o, outcome);+ log.push(`step ${step}: ${change} + ${constraint} ${JSON.stringify(o)} -> ${JSON.stringify(outcome)}, ${checked.after.length} facts`);+ expect({ step, log: log.at(-1), problems: checked.problems.slice(0, 5) }).toEqual({ step, log: log.at(-1), problems: [] });+ facts = checked.after;+ }+ const state = await pageState(engine, slug);+ expect({ settled: state.settled, log: log.at(-1) }).toEqual({ settled: true, log: log.at(-1) });+ // The same page, extracted once on a fresh brain under the same configuration.+ const fresh = opts.getFresh();+ const freshSlug = `notes/property-fresh-${seed}-${randomUUID().slice(0, 8)}`;+ for (const key of ['facts.extraction_model', 'facts.default_visibility']) await fresh.engine.setConfig(key, (await engine.getConfig(key)) ?? '');+ for (const key of [PAGE_DERIVATION_CAP_KEY, PAGE_EMBED_CAP_KEY]) await fresh.engine.setConfig(key, 'off');+ await fresh.seed(freshSlug, chatPage(title, (await brain.body(slug)).truth));+ expect(await run(fresh.engine, freshSlug, {})).toEqual({ threw: false, failed: 0 });+ const freshState = await pageState(fresh.engine, freshSlug);+ const byWindow = (list: Fact[]) => list.map(f => `${shaOf(f.key)} ${f.fact}`).sort();+ expect({ windows: state.windowShas.length, sameWindows: state.windowShas.join() === freshState.windowShas.join(), facts: facts.length,+ sameFacts: byWindow(facts).join('\n') === byWindow(await factsOf(fresh.engine, freshSlug)).join('\n') })+ .toEqual({ windows: freshState.windowShas.length, sameWindows: true, facts: (await factsOf(fresh.engine, freshSlug)).length, sameFacts: true });+ } finally {+ await engine.setConfig('facts.extraction_model', '');+ await engine.setConfig('facts.default_visibility', 'private');+ }+ }, 900_000);+ }+}diff --git a/test/helpers/conversation-facts-recovery-cases.ts b/test/helpers/conversation-facts-recovery-cases.tsindex 76502a86ee..b90afaeb61 100644--- a/test/helpers/conversation-facts-recovery-cases.ts+++ b/test/helpers/conversation-facts-recovery-cases.ts@@ -60,7 +60,7 @@ const terminalStamps = async (engine: BrainEngine, slug: string) => {};export function defineConversationFactsRecoveryCases(opts: { getBrain: () => AppendBrain }): void {- test('a partial run on a transcript without message times clears only the window it extracted again', async () => {+ test('a partial run on a transcript without message times deletes nothing: the window it extracted is added beside the old facts', async () => {const brain = opts.getBrain();const slug = `notes/timeless-partial-${randomUUID().slice(0, 8)}`;await caps(brain.engine, 'off');@@ -75,7 +75,7 @@ export function defineConversationFactsRecoveryCases(opts: { getBrain: () => Appconst after = await factsOf(brain.engine, slug);expect({ calls: limited.calls.length, before: before.length, after: after.length, cleaned: limited.result.orphan_facts_cleaned,kept: before.filter(f => after.some(a => a.id === f.id)).length })- .toEqual({ calls: 1, before: before.length, after: before.length, cleaned: 1, kept: before.length - 1 });+ .toEqual({ calls: 1, before: before.length, after: before.length + 1, cleaned: 0, kept: before.length });}, 600_000);test('a time-less transcript whose turns cross segment cuts streams exactly the whole-page windows before it settles', async () => {@@ -179,7 +179,7 @@ export function defineConversationFactsRecoveryCases(opts: { getBrain: () => Appexpect({ calls: forced.calls, receipts: (await derivations(brain.engine, slug)).receipts.filter(Boolean) }).toEqual({ calls: [stuck!], receipts: [] });}, 600_000);- test('a one-window run on a page of oversized turns clears only the pieces that window holds', async () => {+ test('a one-window run on a page of oversized turns after a title of another length deletes nothing (piece numbers move with the title)', async () => {const brain = opts.getBrain();const slug = `notes/oversized-turns-${randomUUID().slice(0, 8)}`;await caps(brain.engine, 'off');@@ -191,11 +191,11 @@ export function defineConversationFactsRecoveryCases(opts: { getBrain: () => Appconst before = await factsOf(brain.engine, slug);expect(before.length).toBe(all.calls.length);expect(before.length).toBeGreaterThan(60);- await brain.seed(slug, chatPage('Oversized T2', (await brain.body(slug)).truth));+ await brain.seed(slug, chatPage('Oversized turns, retitled with a much longer page title', (await brain.body(slug)).truth));const limited = await extract(brain.engine, slug, { segmentLimit: 1 });const after = await factsOf(brain.engine, slug);expect({ calls: limited.calls.length, after: after.length, cleaned: limited.result.orphan_facts_cleaned, kept: before.filter(f => after.some(a => a.id === f.id)).length })- .toEqual({ calls: 1, after: before.length, cleaned: 1, kept: before.length - 1 });+ .toEqual({ calls: 1, after: before.length + 1, cleaned: 0, kept: before.length });}, 600_000);test('a page re-imported in another chat format is parsed in its new format, not the grammar its old rows recorded', async () => {@@ -218,22 +218,26 @@ export function defineConversationFactsRecoveryCases(opts: { getBrain: () => App.toEqual({ calls: expected.length, same: true, nonExtractable: 0, facts: expected.length, states: ['done'] });}, 600_000);- test('a run that parses no message from occurrences that had windows keeps their facts, settles nothing and leaves a receipt doctor lists', async () => {+ test('a page that stops being a transcript settles as non-extractable and its conversation facts are collected, under --force too', async () => {const brain = opts.getBrain();const slug = `notes/unparsed-${randomUUID().slice(0, 8)}`;await caps(brain.engine, 'off');await brain.seed(slug, chatPage('Unparsed', chatDays(3500, 100, 24)));await extract(brain.engine, slug);- const before = (await factsOf(brain.engine, slug)).map(f => f.id);+ const before = (await factsOf(brain.engine, slug)).length;+ expect(before).toBeGreaterThan(100);const prose = Array.from({ length: 6000 }, (_, i) => `Paragraph ${i} of the notes: the roadmap review moved to next quarter and the budget stays flat.`).join('\n\n');await brain.seed(slug, chatPage('Unparsed', prose));const { calls, result } = await extract(brain.engine, slug);+ const rows = await derivations(brain.engine, slug);expect({ calls: calls.length, failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, cleaned: result.orphan_facts_cleaned,- facts: (await factsOf(brain.engine, slug)).map(f => f.id), stamped: await terminalStamps(brain.engine, slug) })- .toEqual({ calls: 0, failed: 1, nonExtractable: 0, cleaned: 0, facts: before, stamped: 0 });+ facts: (await factsOf(brain.engine, slug)).length, states: [...new Set(rows.states)], receipts: rows.receipts.filter(Boolean) })+ .toEqual({ calls: 0, failed: 0, nonExtractable: 1, cleaned: before + 1, facts: 0, states: ['done'], receipts: [] });+ const forced = await extract(brain.engine, slug, { force: true });+ expect({ calls: forced.calls.length, failed: forced.result.pages_failed, facts: (await factsOf(brain.engine, slug)).length }).toEqual({ calls: 0, failed: 0, facts: 0 });const check = (await extractionInputTruncatedEntry.run({ engine: brain.engine } as unknown as DoctorContext) as Check[]).find(c => c.name === 'extraction_input_truncated')!;- const groups = (check.details as { groups: Array<{ pipeline: string; kind: string; samples: string[] }> }).groups;- expect(groups.some(g => g.pipeline === 'conversation_facts' && g.kind === 'no_messages' && g.samples.includes(`default:${slug}`))).toBe(true);+ const groups = ((check.details as { groups?: Array<{ pipeline: string; kind: string; samples: string[] }> } | undefined)?.groups ?? []);+ expect(groups.some(g => g.kind === 'no_messages' && g.samples.includes(`default:${slug}`))).toBe(false);}, 600_000);test('provider-wide failures (an auth error, a 503) never count against a window: it is never marked failed and extracts once the provider recovers', async () => {@@ -265,23 +269,29 @@ export function defineConversationFactsRecoveryCases(opts: { getBrain: () => App}}, 600_000);- test('a window marked failed keeps the facts of the earlier window it replaced until it is extracted', async () => {+ test('a window marked failed blocks collection across two context changes: every earlier fact stands until a --force run extracts it', async () => {const brain = opts.getBrain();const slug = `notes/failed-keeps-${randomUUID().slice(0, 8)}`;await caps(brain.engine, 'off');await brain.seed(slug, chatPage('Keeps T1', chatDays(3700, 100, 26)));await extract(brain.engine, slug);const before = await factsOf(brain.engine, slug);- await brain.seed(slug, chatPage('Keeps T2', (await brain.body(slug)).truth));- let stuck = null as string | null;- const failOn = (text: string) => { stuck ??= text; return text === stuck; };- for (let run = 1; run <= WINDOW_FAILURE_LIMIT; run++) await extract(brain.engine, slug, { failOn });- const settled = await factsOf(brain.engine, slug);- const survivors = before.filter(f => settled.some(s => s.id === f.id));- expect({ facts: settled.length, survivors: survivors.length, stamped: await terminalStamps(brain.engine, slug) }).toEqual({ facts: before.length, survivors: 1, stamped: 1 });+ const survivors = (facts: Awaited<ReturnType<typeof factsOf>>) => before.filter(f => facts.some(s => s.id === f.id)).length;+ const stuck: string[] = [];+ for (const title of ['Keeps T2', 'Keeps, a third and longer title']) {+ await brain.seed(slug, chatPage(title, (await brain.body(slug)).truth));+ let first = null as string | null;+ const failOn = (text: string) => { first ??= text; return text === first; };+ for (let run = 1; run <= WINDOW_FAILURE_LIMIT; run++) await extract(brain.engine, slug, { failOn });+ stuck.push(first!);+ const facts = await factsOf(brain.engine, slug);+ expect({ title, survivors: survivors(facts), stamped: await terminalStamps(brain.engine, slug) }).toEqual({ title, survivors: before.length, stamped: 1 });+ }const forced = await extract(brain.engine, slug, { force: true });const after = await factsOf(brain.engine, slug);- expect({ calls: forced.calls, facts: after.length, survivors: before.filter(f => after.some(a => a.id === f.id)).length }).toEqual({ calls: [stuck!], facts: before.length, survivors: 0 });+ const rows = await derivations(brain.engine, slug);+ expect({ calls: forced.calls, facts: after.length, survivors: survivors(after), anchored: after.every(f => rows.keys.includes(f.key)) })+ .toEqual({ calls: [stuck[1]!], facts: rows.keys.length, survivors: 0, anchored: true });}, 600_000);}diff --git a/test/helpers/derivation-unpriced-cases.ts b/test/helpers/derivation-unpriced-cases.tsnew file mode 100644index 0000000000..4ffac05607--- /dev/null+++ b/test/helpers/derivation-unpriced-cases.ts@@ -0,0 +1,117 @@+/**+ * Paid page derivations under a model with no price (PR 4 lane 4b round 5, item 10), 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). No default changes and no price is invented: an unpriced+ * model reserves its ceiling estimate, so the per-page cap stops it after about one window. Fake extractors only.+ *+ * 1. Protects: when the facts, conversation facts, atoms or synopsis step stops (or books its reservation) because the+ * model has no price, its derivation receipt says reason `unpriced_model` with the model id, and doctor+ * derivation_unpriced_model warns with a fix naming pricing.overrides (gbrain pricing set <model> ...); once the price+ * is registered the warning clears.+ * 2. Fails when: an unpriced stop reads as a plain cap stop (cap_reached) with no model, or doctor stays silent.+ */+import { expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { AppendBrain } from './append-brain.ts';+import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';+import { PAGE_DERIVATION_CAP_KEY } from '../../src/core/page-spend.ts';+import { derivationUnpricedModelEntry } from '../../src/commands/doctor/checks/derivation-pricing.ts';+import { reembedPageWithContextualRetrieval } from '../../src/core/contextual-retrieval-service.ts';+import { runPhaseExtractAtoms, EXTRACT_ATOMS_MODEL_KEY } from '../../src/core/cycle/extract-atoms.ts';+import { __setChatTransportForTests, chat as gatewayChat, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';+import { runExtractConversationFactsCore } from '../../src/commands/extract-conversation-facts.ts';+import type { DoctorContext } from '../../src/commands/doctor/context.ts';+import type { Check } from '../../src/commands/doctor.ts';+import { chatDays, chatPage, derivations, SOURCE } from './conversation-facts-incremental-cases.ts';++/** A model id gbrain ships no price for. */+export const UNPRICED = 'anthropic:claude-unpriced-example';++const doctor = async (engine: BrainEngine) => (await derivationUnpricedModelEntry.run({ engine } as unknown as DoctorContext) as Check[])+ .find(c => c.name === 'derivation_unpriced_model')!;+const receiptsOf = async (engine: BrainEngine, slug: string, kind: 'extract_atoms' | 'synopsis') => {+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]);+ return (await engine.readSegmentDerivations(Number(page!.id), { kind })).map(r => r.receipt as Record<string, unknown> | null).filter(Boolean);+};++export function defineDerivationUnpricedCases(opts: { getBrain: () => AppendBrain }): void {+ test('conversation facts under an unpriced model: the cap stop says unpriced_model with the model, doctor names pricing.overrides, a registered price clears it', async () => {+ const brain = opts.getBrain();+ const slug = `notes/unpriced-facts-${randomUUID().slice(0, 8)}`;+ await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, '2');+ await brain.engine.setConfig('facts.extraction_model', UNPRICED);+ try {+ await brain.seed(slug, chatPage('Unpriced facts', chatDays(4400, 100, 41)));+ // Each window's call is answered by the unpriced model, so it books its whole reservation (the ceiling estimate).+ __setChatTransportForTests(async (o: ChatOpts): Promise<ChatResult> => ({ text: '{"facts":[]}', blocks: [], stopReason: 'end', model: UNPRICED, providerId: 'anthropic',+ usage: { input_tokens: Math.ceil(JSON.stringify(o.messages).length / 4), output_tokens: 32, cache_read_tokens: 0, cache_creation_tokens: 0 } }));+ const calls: string[] = [];+ await runExtractConversationFactsCore(brain.engine, { sourceId: 'default', slugs: [slug], sleepMs: 0, extractor: async input => {+ calls.push(input.turnText);+ await gatewayChat({ model: UNPRICED, messages: [{ role: 'user', content: input.turnText }], maxTokens: 64 });+ return [{ fact: 'Alice Example noted the window', kind: 'fact', entity_slug: null, source: SOURCE }];+ } }).finally(() => __setChatTransportForTests(null));+ const unread = (await derivations(brain.engine, slug)).receipts.filter(Boolean) as Array<Record<string, unknown>>;+ expect({ calls: calls.length, receipts: unread.map(r => ({ kind: r.kind, reason: r.reason, model: r.model })) })+ .toEqual({ calls: 1, receipts: [{ kind: 'unread_windows', reason: 'unpriced_model', model: UNPRICED }] });+ const check = await doctor(brain.engine);+ const models = (check.details as { models: Array<{ model: string; pipelines: string[] }> }).models;+ expect({ status: check.status, models: models.map(m => [m.model, m.pipelines]), fix: check.fix?.argv?.slice(0, 4), names: check.message.includes('pricing.overrides') })+ .toEqual({ status: 'warn', models: [[UNPRICED, ['conversation_facts']]], fix: ['gbrain', 'pricing', 'set', UNPRICED], names: true });+ await brain.engine.setConfig('pricing.overrides', JSON.stringify({ [UNPRICED]: { input: 0.5, output: 0.5 } }));+ expect((await doctor(brain.engine)).status).toBe('ok');+ } finally {+ await brain.engine.setConfig('facts.extraction_model', '');+ await brain.engine.setConfig('pricing.overrides', '');+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');+ }+ }, 600_000);++ test('atoms under an unpriced model: the cap stop says unpriced_model with the model', async () => {+ const brain = opts.getBrain();+ const slug = `notes/unpriced-atoms-${randomUUID().slice(0, 8)}`;+ const prompts: string[] = [];+ const chat = async (o: ChatOpts): Promise<ChatResult> => {+ prompts.push(String(o.messages[0]?.content ?? ''));+ const text = JSON.stringify({ atoms: [] });+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: UNPRICED, providerId: 'groq', usage: { input_tokens: 10, output_tokens: 2, cache_read_tokens: 0, cache_creation_tokens: 0 } };+ };+ await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, '0.000001');+ await brain.engine.setConfig(EXTRACT_ATOMS_MODEL_KEY, UNPRICED);+ try {+ await brain.seed(slug, chatPage('Unpriced atoms', chatDays(4500, 100, 42)).replace('type: conversation', 'type: meeting'));+ await runPhaseExtractAtoms(brain.engine, { sourceId: 'default', _chat: chat, _transcripts: [] });+ const receipts = await receiptsOf(brain.engine, slug, 'extract_atoms');+ expect({ receipts: [...new Set(receipts.map(r => JSON.stringify({ kind: r!.kind, reason: r!.reason, model: r!.model })))] })+ .toEqual({ receipts: [JSON.stringify({ kind: 'unread_windows', reason: 'unpriced_model', model: UNPRICED })] });+ const check = await doctor(brain.engine);+ expect({ status: check.status, atoms: (check.details as { models: Array<{ model: string; pipelines: string[] }> }).models.some(m => m.model === UNPRICED && m.pipelines.includes('extract_atoms')) })+ .toEqual({ status: 'warn', atoms: true });+ } finally {+ await brain.engine.setConfig(EXTRACT_ATOMS_MODEL_KEY, '');+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');+ }+ }, 600_000);++ test('synopsis under an unpriced model: the refused reservation says unpriced_model with the model', async () => {+ const brain = opts.getBrain();+ const slug = `notes/unpriced-synopsis-${randomUUID().slice(0, 8)}`;+ await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, '1000');+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, '0.000001');+ try {+ await brain.seed(slug, chatPage('Unpriced synopsis', chatDays(4600, 100, 43)));+ let calls = 0;+ const out = await reembedPageWithContextualRetrieval({ engine: brain.engine, pageSlug: slug, sourceId: 'default', globalMode: 'per_chunk_synopsis', synopsisModel: UNPRICED,+ generateSynopsis: async () => { calls++; return { kind: 'success', synopsis: 'fixture synopsis' }; }, chunkConcurrency: 2 });+ const receipts = await receiptsOf(brain.engine, slug, 'synopsis');+ expect({ out, calls, receipts: receipts.map(r => ({ reason: r!.reason, model: r!.model })) })+ .toEqual({ out: { kind: 'skipped', reason: 'budget_limited' }, calls: 0, receipts: [{ reason: 'unpriced_model', model: UNPRICED }] });+ } finally {+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');+ await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');+ }+ }, 600_000);+}diff --git a/test/large-pages/conversation-facts-incremental.test.ts b/test/large-pages/conversation-facts-incremental.test.tsindex f994b1108b..871113a543 100644--- a/test/large-pages/conversation-facts-incremental.test.ts+++ b/test/large-pages/conversation-facts-incremental.test.ts@@ -6,6 +6,8 @@ import { afterAll, beforeAll, describe } from 'bun:test';import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';import { defineDerivationSpendCases } from '../helpers/derivation-spend-cases.ts';import { defineConversationFactsRecoveryCases } from '../helpers/conversation-facts-recovery-cases.ts';+import { defineConversationFactsInvariantCases } from '../helpers/conversation-facts-invariant-cases.ts';+import { defineDerivationUnpricedCases } from '../helpers/derivation-unpriced-cases.ts';import { defineConversationFactsIncrementalCases, defineSegmentedAtomsCases, defineSegmentedBackstopCases, defineSegmentReceiptDoctorCases } from '../helpers/conversation-facts-incremental-cases.ts';let brain: AppendBrain;@@ -20,4 +22,6 @@ describe('conversation facts incremental [pglite]', () => {defineSegmentReceiptDoctorCases({ getBrain: () => brain });defineDerivationSpendCases({ getBrain: () => brain });defineConversationFactsRecoveryCases({ getBrain: () => brain });+ defineConversationFactsInvariantCases({ getBrain: () => brain });+ defineDerivationUnpricedCases({ getBrain: () => brain });});diff --git a/test/large-pages/conversation-facts-property.test.ts b/test/large-pages/conversation-facts-property.test.tsnew file mode 100644index 0000000000..ecdb755baa--- /dev/null+++ b/test/large-pages/conversation-facts-property.test.ts@@ -0,0 +1,17 @@+/**+ * Seeded property test of the conversation facts deletion invariant, PGLite arm (PR 4 lane 4b round 5). Cases:+ * test/helpers/conversation-facts-property-cases.ts. Postgres arm: test/e2e/conversation-facts-property-postgres.test.ts.+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';+import { defineConversationFactsPropertyCases } from '../helpers/conversation-facts-property-cases.ts';++let brain: AppendBrain;+let fresh: AppendBrain;++beforeAll(async () => { brain = await openAppendBrain('pglite'); fresh = await openAppendBrain('pglite'); }, 120_000);+afterAll(async () => { await brain.close(); await fresh.close(); }, 120_000);++describe('conversation facts deletion invariant [pglite]', () => {+ defineConversationFactsPropertyCases({ getBrain: () => brain, getFresh: () => fresh });+});diff --git a/test/large-pages/segmented-conversation-facts.test.ts b/test/large-pages/segmented-conversation-facts.test.tsindex 759551d2b3..fb2d9bfe04 100644--- a/test/large-pages/segmented-conversation-facts.test.ts+++ b/test/large-pages/segmented-conversation-facts.test.ts@@ -15,9 +15,13 @@* it carries the day-header date in force there, and its parse is the* suffix of the whole body's parse (the same speakers, texts and times);* - a page over the single-string ceiling is extracted 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;+ * newest windows first; a run with no current grammar first detects it+ * over the whole page once (conversationDetectionWork counts exactly the+ * body's bytes), and every run, that one included, reads only the segment+ * it extracts (at most SEGMENT_MAX_BYTES under --segment-limit 2); a run on+ * the grammar the first one pinned reads nothing to detect it; its+ * partial-input receipt is 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@@ -25,7 +29,7 @@* 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.+ * Seams: `segmentedPassWork.bytes` counts bytes read; `conversationDetectionWork.bytes` the grammar detection's.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';@@ -38,7 +42,7 @@ import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';import { runExtractConversationFactsCore } from '../../src/commands/extract-conversation-facts.ts';import { readConversationInput, readSummaryBody } from '../../src/core/conversation-parser/body.ts';import { parseConversation } from '../../src/core/conversation-parser/parse.ts';-import { CONVERSATION_WINDOW_BYTES, readSegmentedConversationInput } from '../../src/core/page-body/segment-conversation.ts';+import { CONVERSATION_WINDOW_BYTES, conversationDetectionWork, readSegmentedConversationInput } from '../../src/core/page-body/segment-conversation.ts';import { segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';import { materializedPage } from '../../src/core/persistence/segmented-apply.ts';import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';@@ -200,7 +204,7 @@ describe('conversation facts over a segmented page (full-pass mode)', () => {}}, 300_000);- test('a page over the single-string ceiling is extracted per occurrence, newest windows first, reading only the occurrence it extracts', async () => {+ test('a page over the single-string ceiling is extracted per occurrence, newest windows first: the grammar is detected over the whole page once, apart, and each run reads only the occurrence it extracts', async () => {for (const engine of engines) {await engine.setConfig('pages.segmented_storage', 'on');const file = join(dir, 'huge.md');@@ -211,11 +215,14 @@ describe('conversation facts over a segmented page (full-pass mode)', () => {const huge = await stored(engine, 'conversations/huge');expect(Number(huge.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);const before = segmentedPassWork.bytes;+ const detectedBefore = conversationDetectionWork.bytes;const texts: string[] = [];const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: ['conversations/huge'], sleepMs: 0, segmentLimit: 2,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.+ // The first run has no current grammar: it detects it over the whole page once, counted apart from the extraction's reads.+ expect(conversationDetectionWork.bytes - detectedBefore).toBe(Number(huge.body_bytes));+ // The extraction reads one segment (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.@@ -223,6 +230,14 @@ describe('conversation facts over a segmented page (full-pass mode)', () => {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 }) }]);+ // A run on the grammar the first run pinned detects nothing and again reads only the segment it extracts.+ const pinnedBefore = segmentedPassWork.bytes;+ const detectedAgain = conversationDetectionWork.bytes;+ const next = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: ['conversations/huge'], sleepMs: 0, segmentLimit: 2,+ extractor: async input => { texts.push(input.turnText); return []; } });+ expect({ tooLarge: next.pages_skipped_too_large, calls: texts.length, detected: conversationDetectionWork.bytes - detectedAgain })+ .toEqual({ tooLarge: 0, calls: 4, detected: 0 });+ expect(segmentedPassWork.bytes - pinnedBefore).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);}}, 1_800_000);diff --git a/test/page-spend-reservation.test.ts b/test/page-spend-reservation.test.tsindex bcffa11cb9..d988a33d60 100644--- a/test/page-spend-reservation.test.ts+++ b/test/page-spend-reservation.test.ts@@ -25,7 +25,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { PAGE_EMBED_CAP_KEY, estimateChatCallUsd, estimateFactsExtractionUsd, meterPaidCall, planPageEmbedding, reservePageSpend, spendGrant,type PageSpendSignature } from '../src/core/page-embedding-budget.ts';import { PAGE_DERIVATION_CAP_KEY } from '../src/core/page-spend.ts';-import { __setChatTransportForTests, __setGenerateTextTransportForTests, chat, configureGateway, resetGateway, withBudgetTracker, type ChatResult } from '../src/core/ai/gateway.ts';+import { __setChatTransportForTests, __setEmbedTransportForTests, __setGenerateTextTransportForTests, chat, configureGateway, resetGateway, withBudgetTracker, type ChatResult } from '../src/core/ai/gateway.ts';+import { embedBatch } from '../src/core/embedding.ts';import { reservationCostUsd } from '../src/core/budget/reservation-cost.ts';import { BudgetExhausted, BudgetTracker, parsePricingOverrides } from '../src/core/budget/budget-tracker.ts';import { estimateChatInputTokens } from '../src/core/ai/chat-input-estimate.ts';@@ -336,6 +337,26 @@ describe('per-page spend ledgers', () => {}});+ test('an embed inside a metered call (the synopsis step\'s embedBatch) runs with the SDK\'s hidden retries off too; an unmetered embed keeps the default', async () => {+ for (const { name, engine } of engines) {+ const page = await segmentedPage(engine);+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 4, env: { OPENAI_API_KEY: 'sk-fake' } });+ const seen: unknown[] = [];+ __setEmbedTransportForTests((async (args: { values: string[]; maxRetries?: number }) => {+ seen.push('maxRetries' in args ? args.maxRetries : 'default');+ return { embeddings: args.values.map(() => [1, 0, 0, 0]), usage: { tokens: args.values.length } };+ }) as never);+ try {+ await meterPaidCall(engine, page, 'synopsis:openai:gpt-4o', 0.2, () => embedBatch(['chunk one', 'chunk two']));+ await embedBatch(['chunk three']);+ } finally {+ __setEmbedTransportForTests(null);+ resetGateway();+ }+ expect(seen, name).toEqual([0, 'default']);+ }+ });+test('failed attempts the provider may have billed are booked, so a run of them stops at the family cap: timeouts, retry-wrapped 408s and a 529, wrapped usage', async () => {const worst = reservationCostUsd(HAIKU, 'chat', estimateChatInputTokens({ messages: [{ content: 'window' }] }), 500)!;const status = (code: number) => Object.assign(new Error(`http ${code}`), { status: code });