Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(conversation-facts): --grammar applies to exactly one page; an operator choice never outlives its page version
garrytan2a7fb3dbf89c
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 9f78b5ff31..05540f1403 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -7,7 +7,7 @@ src/cli/main.ts 3018 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELsrc/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)src/commands/doctor.ts 692 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts)src/commands/embed.ts 2306 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts); +1 PR 4 E (gbrain-evals#180): per-page embedding lease import (lease and still-pending filter live in core/page-embedding-lease.ts); +2 PR 4 E round 2 (gbrain-evals#180): a busy lease skips the page and the install renews the lease (logic in core/page-embedding-lease.ts)-src/commands/extract-conversation-facts.ts 1936 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left; +1 GBRA-159: facts from a private page are private (tightenToPage per page; helper in core/facts/visibility.ts); +46 PR 4 (Wave B incremental derivation, transcripts) round 9: --grammar <format|none> for a held conversation page (the parser branch, six CLI help lines, the core option and two result fields with their doc comments, the assertGrammarTarget pre-check, the summary lines for held pages and previews); the held rule, the recorded choice and the preview live in core/facts/conversation-incremental.ts+src/commands/extract-conversation-facts.ts 1945 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left; +1 GBRA-159: facts from a private page are private (tightenToPage per page; helper in core/facts/visibility.ts); +46 PR 4 (Wave B incremental derivation, transcripts) round 9: --grammar <format|none> for a held conversation page (the parser branch, six CLI help lines, the core option and two result fields with their doc comments, the assertGrammarTarget pre-check, the summary lines for held pages and previews); the held rule, the recorded choice and the preview live in core/facts/conversation-incremental.ts; +9 PR 4 round 10: --grammar resolves exactly one source (resolveGrammarSource replaces assertGrammarTarget: --source-id, else the only source holding the slug; a slug in several sources refuses with each source's command) and two help lines saying so and how long a choice holdssrc/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)diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex e7c4f414f8..8c4bf49c04 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -289,7 +289,7 @@ export interface ExtractConversationFactsCoreOpts {/*** PR 4 (Wave B incremental derivation, transcripts): the operator's conversation format for the page (--grammar; null:* none, the page is not a transcript) for a page stored in segments on an unmanaged brain (the CLI refuses it otherwise:- * assertGrammarTarget). Recorded for the page's current version (later plain runs follow it until the page changes)+ * resolveGrammarSource). Recorded for the page's current version (later plain runs follow it until the page changes)* unless dryRun; bypasses the fresh-outcome skip.*/grammar?: string | null;@@ -1612,12 +1612,14 @@ Options:(falls back to the full allowlist).--slug <slug> Process a single page (overrides multi-page enumeration).--slugs <a,b,...> Process exactly these pages (comma-separated).- --grammar <format|none> With --slug: extract the page under this conversation format+ --grammar <format|none> With --slug (and --source-id when the slug is in more than one+ source): extract that one page under this conversation format(none: the page is not a transcript; it settles as notextractable and its conversation facts are removed). For a pageheld because no format is detected over it (gbrain doctor- conversation_detection_ambiguous). Preview with --dry-run first;- the choice is kept for the page until its text changes.+ conversation_detection_ambiguous). Preview with --dry-run first.+ The choice holds until the page changes; then it is detected+ again and, when still undetected, held for a new choice.--dry-run Show segmentation + counts; no model calls, DB writes, or checkpoint advance.--limit <N> Cap pages processed (default: all).--since <iso> Only consider messages newer than this ISO timestamp.@@ -1657,13 +1659,23 @@ in the facts table (source='${TERMINAL_AUDIT_SOURCE}'). gbrain doctor'sconversation_facts_backlog check counts pages without this row.`;-/** PR 4 (Wave B incremental derivation, transcripts): --grammar applies to a conversation page stored in segments on an unmanaged brain; anything else is refused before any work. */-async function assertGrammarTarget(engine: BrainEngine, sourceIds: string[], slug: string): Promise<void> {+/**+ * PR 4 (Wave B incremental derivation, transcripts): the one source whose page --grammar applies to: --source-id, else the+ * only source holding the slug (a slug is not a page identity across sources, so two refuse). The page must be stored in+ * segments on an unmanaged brain. Anything else is refused before any work.+ */+async function resolveGrammarSource(engine: BrainEngine, explicit: string | undefined, slug: string): Promise<string> {if (await managedPersistenceEnabled(engine)) throw usageError('--grammar applies to an unmanaged brain: a managed brain extracts a conversation page whole', ECF_HELP_HINT);- for (const sourceId of sourceIds) {- const page = await engine.getPage(slug, { sourceId });- if (page && (!isSegmentedPage(page) || hasRawTranscriptSidecar(page))) throw usageError(`--grammar applies to a conversation page stored in segments; ${sourceId}:${slug} is extracted whole`, ECF_HELP_HINT);+ const holders = explicit ? [explicit] : (await engine.executeRaw<{ source_id: string }>(+ 'SELECT source_id FROM pages WHERE slug = $1 AND deleted_at IS NULL ORDER BY source_id', [slug])).map(r => r.source_id);+ if (holders.length !== 1) {+ const commands = holders.map(s => `gbrain extract-conversation-facts --source-id ${s} --slug ${slug} --grammar <format|none> --dry-run`);+ throw usageError(holders.length ? `--grammar chooses the format of one page, and ${slug} is in ${holders.length} sources (${holders.join(', ')}): pass --source-id`+ : `--grammar: no page ${slug} in any source`, holders.length ? commands.join('; ') : ECF_HELP_HINT, { reason: holders.length ? 'grammar_source_ambiguous' : 'grammar_page_not_found' });}+ const page = await engine.getPage(slug, { sourceId: holders[0]! });+ if (page && (!isSegmentedPage(page) || hasRawTranscriptSidecar(page))) throw usageError(`--grammar applies to a conversation page stored in segments; ${holders[0]}:${slug} is extracted whole`, ECF_HELP_HINT);+ return holders[0]!;}function buildJobParams(args: string[]): Record<string, unknown> {@@ -1737,11 +1749,8 @@ export async function runExtractConversationFacts(const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));// Multi-source enumeration when --source-id NOT set.- const sourceIds: string[] = parsed.sourceId- ? [parsed.sourceId]- : (await listSources(engine)).map((s) => s.id);-- if (parsed.grammar !== undefined) await assertGrammarTarget(engine, sourceIds, parsed.slug!);+ const sourceIds: string[] = parsed.grammar !== undefined ? [await resolveGrammarSource(engine, parsed.sourceId, parsed.slug!)]+ : parsed.sourceId ? [parsed.sourceId] : (await listSources(engine)).map((s) => s.id);progress.start('extract.conversation_facts', sourceIds.length);try {@@ -1856,8 +1865,8 @@ export async function runExtractConversationFacts(for (const failed of aggregate.failed_pages) console.error(` ${failed.slug}: ${failed.error}`);}if (aggregate.pages_pending) console.log(` ${aggregate.pages_pending} page(s) were accepted and are still pending; rerun the same command to confirm them (no model call).`);- if (aggregate.pages_detection_ambiguous) console.log(` ${aggregate.pages_detection_ambiguous} page(s) are held: no conversation format is detected over them, yet some parse messages, so their facts were kept and nothing was extracted; gbrain doctor conversation_detection_ambiguous lists each with its formats, and --slug <slug> --grammar <format|none> --dry-run previews a choice.`);- for (const p of aggregate.grammar_previews ?? []) console.log(` Preview of ${p.slug} under --grammar ${p.grammar ?? 'none'}: ${p.messages} message(s) in ${p.windows} window(s), ${p.windows_to_extract} to extract; a settled run removes ${p.facts_to_collect} conversation fact(s).`);+ if (aggregate.pages_detection_ambiguous) console.log(` ${aggregate.pages_detection_ambiguous} page(s) are held: no conversation format is detected over them, yet some parse messages, so their facts were kept and nothing was extracted; gbrain doctor conversation_detection_ambiguous lists each with its formats, and --source-id <source> --slug <slug> --grammar <format|none> --dry-run previews a choice.`);+ for (const p of aggregate.grammar_previews ?? []) console.log(` Preview of ${p.source_id}:${p.slug} under --grammar ${p.grammar ?? 'none'}: ${p.messages} message(s) in ${p.windows} window(s), ${p.windows_to_extract} to extract; a settled run removes ${p.facts_to_collect} conversation fact(s).`);if (aggregate.pages_blocked) console.log(` ${aggregate.pages_blocked} page(s) are blocked at their current version after a request failed; they are retried only once the page changes (each SKIP line names the receipt).`);if (aggregate.pages_llm_fallback > 0) {console.log(` Parsed ${aggregate.pages_llm_fallback} page(s) with the opt-in LLM fallback.`);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex b0c3dd8e1a..242b4ae066 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1065,7 +1065,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ 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, 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 whose format is no longer detected over the whole page (text added around a transcript can outweigh its message lines, or it quotes another format) while some conversation format still parses a message in it is now held instead of guessed: no model call, no fact added or removed, so stale facts on such a page wait for the operator\'s call. `gbrain doctor` lists it as `conversation_detection_ambiguous` with each format\'s message count, and `gbrain extract-conversation-facts --slug <slug> --grammar <format> --dry-run` previews what a run under that format would extract and remove; without `--dry-run` it runs, and `--grammar none` settles the page as not a transcript and clears its conversation facts. The choice holds for the page until its text changes. A page no conversation format parses a message in (facts an older extractor left included) is no longer a transcript: it is marked non-extractable and its conversation facts are cleared, even under `--force`. A page that reads as a transcript yet parses no message keeps every fact and leaves a `no_messages` receipt doctor lists. A run settles and clears only if the page is still the version it read when the publication locks it, so a write that lands during the run leaves the page for the next run with every fact kept. Until a run settles, a page can briefly hold more facts than a settled extraction would: a run that stops partway (an abort, a crash, a limit) adds the facts of the windows it finished, and the facts of windows those replaced on the page stay until a later run extracts their exact window again or settles the page.' },+ { 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 whose format is no longer detected over the whole page (text added around a transcript can outweigh its message lines, or it quotes another format) while some conversation format still parses a message in it is now held instead of guessed: no model call, no fact added or removed, so stale facts on such a page wait for the operator\'s call. `gbrain doctor` lists it as `conversation_detection_ambiguous` with each format\'s message count, and `gbrain extract-conversation-facts --source-id <source> --slug <slug> --grammar <format> --dry-run` previews what a run under that format would extract and remove; without `--dry-run` it runs, and `--grammar none` settles the page as not a transcript and clears its conversation facts. `--grammar` applies to one page: a slug in more than one source needs `--source-id`, and the command refuses without it. The choice holds until the page changes; then the page is detected again, and when still no format is detected it is held for a new choice. A page no conversation format parses a message in (facts an older extractor left included) is no longer a transcript: it is marked non-extractable and its conversation facts are cleared, even under `--force`. A page that reads as a transcript yet parses no message keeps every fact and leaves a `no_messages` receipt doctor lists. A run settles and clears only if the page is still the version it read when the publication locks it, so a write that lands during the run leaves the page for the next run with every fact kept. Until a run settles, a page can briefly hold more facts than a settled extraction would: a run that stops partway (an abort, a crash, a limit) adds the facts of the windows it finished, and the facts of windows those replaced on the page stay until a later run extracts their exact window again or settles the page.' },// 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/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.tsindex b0ea22a2af..16c1dc01ba 100644--- a/src/core/facts/conversation-incremental.ts+++ b/src/core/facts/conversation-incremental.ts@@ -27,7 +27,8 @@* 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, or the one the operator chose for this page+ * recorded it under the same context are mostly unchanged by bytes (never rows written under an operator choice), or+ * the one the operator chose for this page* version (--grammar; none settles the page as non-extractable); with none detected while some built-in format still* parses a message, the page is held (a detection_ambiguous receipt with each format's count for the page version;* no call, nothing published or collected; a plain run on the same version reuses it without reading the page)@@ -94,7 +95,7 @@ export interface SegmentedConversationCounters {}/** What a run under the operator's format (null: none) would do on one page: its messages and windows, the windows it would extract, and the facts its settled collection would remove. */-export interface GrammarPreview { slug: string; grammar: string | null; messages: number; windows: number; windows_to_extract: number; facts_to_collect: number }+export interface GrammarPreview { source_id: string; slug: string; grammar: string | null; messages: number; windows: number; windows_to_extract: number; facts_to_collect: number }export interface SegmentedConversationRun extends ConversationWindowRun {result: SegmentedConversationCounters;@@ -108,7 +109,7 @@ export interface SegmentedConversationRun extends ConversationWindowRun {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> }+interface RowOutput { windows: WindowRecord[]; starts_group?: boolean; prev?: number | null; pattern?: string | null; chosen?: boolean; 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;state: 'reused' | 'todo' | 'extracted' | 'failed'; facts: number; failed?: WindowFailure }@@ -118,7 +119,7 @@ type Stop = 'segment_limit' | 'cap_reached' | 'purge_sweep_pending' | 'interruptfunction 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 : [] };+ pattern: output?.pattern ?? null, chosen: output?.chosen === true, 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 });@@ -207,13 +208,13 @@ export async function processSegmentedConversationPage(run: SegmentedConversatioif (opts.grammar !== undefined && !run.dryRun) await setExtractionReceipt(engine, page.id, KIND, choiceReceipt);if (choice !== undefined) from = 0;let pattern = choice !== undefined ? choice- : !opts.redetect && kept.length && 2 * bytesOf(kept) > bytesOf(recorded) ? rowOutput(kept[0]).pattern ?? null : null;+ : !opts.redetect && kept.length && 2 * bytesOf(kept) > bytesOf(recorded) && !recorded.some(row => rowOutput(row).chosen) ? rowOutput(kept[0]).pattern ?? null : null;const pinned = choice === undefined && pattern !== null;const detectedBytes = conversationDetectionWork.bytes;const hold = async (grammars: Record<string, number>, checked: boolean) => {if (checked && !run.dryRun) await setExtractionReceipt(engine, page.id, KIND, { kind: 'detection_ambiguous', pipeline: KIND, processed_chars: 0, grammars, version_token: versionToken });result.pages_detection_ambiguous = (result.pages_detection_ambiguous ?? 0) + 1;- process.stderr.write(`[extract-conversation-facts] ${page.slug}: held${checked ? '' : ' (unchanged since it was held, nothing read)'}: no format is detected over the page, yet ${Object.entries(grammars).map(([id, n]) => `${id} parses ${n}`).join(', ')} message(s); its facts were kept and nothing was extracted; gbrain extract-conversation-facts --slug ${page.slug} --grammar <format|none> --dry-run previews a choice\n`);+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: held${checked ? '' : ' (unchanged since it was held, nothing read)'}: no format is detected over the page, yet ${Object.entries(grammars).map(([id, n]) => `${id} parses ${n}`).join(', ')} message(s); its facts were kept and nothing was extracted; gbrain extract-conversation-facts --source-id ${sourceId} --slug ${page.slug} --grammar <format|none> --dry-run previews a choice\n`);return { newestEnd: null };};// A page held at this version stays held without reading it (a --force run checks it again).@@ -299,7 +300,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatioif (opts.grammar !== undefined) {// The operator's preview: what a run under the chosen format extracts and what its settled collection removes.const keys = windows.map(w => sourceWindowKey(w.window));- (result.grammar_previews ??= []).push({ slug: page.slug, grammar: opts.grammar, messages: parsedMessages, windows: windows.length, windows_to_extract: todo,+ (result.grammar_previews ??= []).push({ source_id: sourceId, slug: page.slug, grammar: opts.grammar, messages: parsedMessages, windows: windows.length, windows_to_extract: todo,facts_to_collect: await countConversationFactsOutside(engine, sourceId, page.slug, keys) });}return { newestEnd: null };@@ -330,7 +331,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatioconst finished = records.length === mine.length;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 } : {}) },+ output: { windows: records, starts_group: startsGroup.get(occurrenceId) ?? false, prev: prevOf(streamedFrom + k), pattern, ...(choice !== undefined ? { chosen: true } : {}), ...(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) };});diff --git a/test/helpers/conversation-facts-invariant-cases.ts b/test/helpers/conversation-facts-invariant-cases.tsindex c466b02107..240e7d7ae9 100644--- a/test/helpers/conversation-facts-invariant-cases.ts+++ b/test/helpers/conversation-facts-invariant-cases.ts@@ -20,7 +20,7 @@* grammar, a lost grammar collects a transcript's facts (under a stale recorded format included) or holds a prose page's facts forever, or a run settles a page version it did not read.*/import { expect, spyOn, test } from 'bun:test';-import { randomUUID } from 'node:crypto';+import { createHash, 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';@@ -32,7 +32,9 @@ import { conversationDetectionWork } from '../../src/core/page-body/segment-convimport { 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';+import { chatDays, chatPage, derivations, extract, factsOf, SOURCE, turns } from './conversation-facts-incremental-cases.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { runExtractConversationFacts, runExtractConversationFactsCore } from '../../src/commands/extract-conversation-facts.ts';const caps = async (engine: BrainEngine, usd: string) => { await engine.setConfig(PAGE_DERIVATION_CAP_KEY, usd); await engine.setConfig(PAGE_EMBED_CAP_KEY, usd); };@@ -406,7 +408,7 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Apconst none = await extract(brain.engine, slug, { grammar: null, dryRun: true });const q = none.result.grammar_previews?.[0];expect({ calls: none.calls.length, preview: q, facts: (await factsOf(brain.engine, slug)).map(f => f.id) })- .toEqual({ calls: 0, preview: { slug, grammar: null, messages: 0, windows: 0, windows_to_extract: 0, facts_to_collect: kept.length }, facts: kept });+ .toEqual({ calls: 0, preview: { source_id: 'default', slug, grammar: null, messages: 0, windows: 0, windows_to_extract: 0, facts_to_collect: kept.length }, facts: kept });const cleared = await extract(brain.engine, slug, { grammar: null });const later = await extract(brain.engine, slug);expect({ calls: cleared.calls.length + later.calls.length, nonExtractable: cleared.result.pages_marked_non_extractable, failed: cleared.result.pages_failed + later.result.pages_failed,@@ -414,6 +416,76 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap.toEqual({ calls: 0, nonExtractable: 1, failed: 0, held: 0, facts: 0, receipt: 'grammar_chosen' });}, 600_000);+ test('--grammar applies to one page: a slug in two sources refuses with nothing changed and names both commands; --source-id changes only that source; a slug in one source resolves to it', async () => {+ const brain = opts.getBrain();+ const engine = brain.engine;+ const slug = `notes/shared-chat-${randomUUID().slice(0, 8)}`;+ const other = `src-${randomUUID().slice(0, 8)}`;+ await caps(engine, 'off');+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [other]);+ const turns = Array.from({ length: 220 }, (_, i) => `${i % 2 ? 'Assistant' : 'User'}: turn ${i} ${'present '.repeat(800)}`).join('\n');+ for (const sourceId of ['default', other]) {+ await importFromContent(engine, slug, chatPage(`Chat in ${sourceId}`, turns), { noEmbed: true, sourceId });+ await runExtractConversationFactsCore(engine, { sourceId, slugs: [slug], sleepMs: 0,+ extractor: async input => [{ fact: `Alice Example noted window ${createHash('sha256').update(input.turnText).digest('hex').slice(0, 12)}`, kind: 'fact', entity_slug: null, source: SOURCE }] });+ }+ const state = async () => ({+ facts: await engine.executeRaw<{ source_id: string; n: number }>("SELECT source_id, count(*)::int AS n FROM facts WHERE source_markdown_slug = $1 AND source = $2 AND expired_at IS NULL GROUP BY source_id ORDER BY source_id", [slug, SOURCE]),+ choices: await engine.executeRaw<{ source_id: string; kind: string }>("SELECT p.source_id, s.input_truncated->>'kind' AS kind FROM page_extraction_state s JOIN pages p ON p.id = s.page_id WHERE p.slug = $1 AND s.pipeline = 'conversation_facts' ORDER BY 1", [slug]),+ });+ const cli = async (args: string[]) => {+ const lines: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.join(' ')); });+ try { await runExtractConversationFacts(engine, args); return { error: null, lines }; }+ catch (error) { return { error: error as { code?: string; message: string; suggestion?: string; reason?: string }, lines }; }+ finally { log.mockRestore(); }+ };+ const before = await state();+ expect(before.facts.map(r => r.source_id).sort()).toEqual(['default', other].sort());+ const refused = [await cli(['--slug', slug, '--grammar', 'none', '--dry-run']), await cli(['--slug', slug, '--grammar', 'none'])];+ const afterRefused = await state();+ const scoped = await cli(['--source-id', 'default', '--slug', slug, '--grammar', 'none']);+ const afterScoped = await state();+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE source_id = $1 AND slug = $2', [other, slug]);+ const single = await cli(['--slug', slug, '--grammar', 'none', '--dry-run']);+ const serialized = JSON.stringify(refused.map(r => r.error));+ expect({+ refused: refused.map(r => ({ code: r.error?.code, names: [other, 'default'].every(s => r.error?.message.includes(s)), command: [other, 'default'].every(s => serialized.includes(`--source-id ${s} --slug ${slug} --grammar`)) })),+ unchangedByRefusal: JSON.stringify(afterRefused) === JSON.stringify(before),+ scoped: scoped.error?.message ?? null,+ afterScoped: { facts: afterScoped.facts, choices: afterScoped.choices },+ single: { error: single.error?.message ?? null, preview: single.lines.some(l => l.includes(`Preview of default:${slug} under --grammar none`)) },+ }).toEqual({+ refused: [{ code: 'invalid_params', names: true, command: true }, { code: 'invalid_params', names: true, command: true }],+ unchangedByRefusal: true,+ scoped: null,+ afterScoped: { facts: before.facts.filter(r => r.source_id === other), choices: [{ source_id: 'default', kind: 'grammar_chosen' }] },+ single: { error: null, preview: true },+ });+ }, 600_000);++ test('a choice holds only for the page version it was made for: after an append the chosen rows do not pin their format, so a page still undetected is held with every fact kept', async () => {+ const brain = opts.getBrain();+ const slug = `notes/choice-version-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ const transcript = Array.from({ length: 160 }, (_, i) => `${i % 2 ? 'Assistant' : 'User'}: turn ${i} ${'fixture detail '.repeat(550)}`).join('\n');+ const preamble = Array.from({ length: 16_000 }, (_, i) => `Reference paragraph ${i} gives context, not a message.`).join('\n');+ await brain.seed(slug, chatPage('Constant title', `${preamble}\n${transcript}`));+ const receipt = async () => (await brain.engine.executeRaw<{ kind: string | null }>(+ "SELECT s.input_truncated->>'kind' AS kind FROM page_extraction_state s JOIN pages p ON p.id = s.page_id WHERE p.slug = $1 AND s.pipeline = 'conversation_facts'", [slug]))[0]?.kind ?? null;+ const summary = (r: Awaited<ReturnType<typeof extract>>) => ({ calls: r.calls.length, held: r.result.pages_detection_ambiguous ?? 0, failed: r.result.pages_failed });+ const held = summary(await extract(brain.engine, slug));+ const chosen = await extract(brain.engine, slug, { grammar: 'plain-role-no-time' });+ const same = summary(await extract(brain.engine, slug));+ const facts = (await factsOf(brain.engine, slug)).map(f => f.id);+ expect(await brain.call('append_page', { slug, text: '\nUser: a new message after the choice.\nAssistant: an appended response.', request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });+ expect(await undetected(brain, slug)).toBeNull();+ const after = summary(await extract(brain.engine, slug));+ const again = summary(await extract(brain.engine, slug));+ expect({ held, chose: chosen.calls.length > 0 && chosen.result.pages_failed === 0, same, after, again, facts: (await factsOf(brain.engine, slug)).map(f => f.id), receipt: await receipt() })+ .toEqual({ held: { calls: 0, held: 1, failed: 0 }, chose: true, same: { calls: 0, held: 0, failed: 0 }, after: { calls: 0, held: 1, failed: 0 }, again: { calls: 0, held: 1, failed: 0 }, facts, receipt: 'detection_ambiguous' });+ }, 600_000);+test('R3 (cases C, C2): a page turned to pure prose whose facts have no recorded grammar (rows without one, or no rows at all) is non-extractable and its facts are collected, --force too', async () => {const brain = opts.getBrain();const out: Record<string, unknown> = {};