Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(conversation-facts): hold a page with no detected format instead of guessing one; the operator chooses with --grammar

garrytan5caa47939d90
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 3d630f295e..9f78b5ff31 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 SEL
src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)
src/commands/doctor.ts 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 1890 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)
+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.ts 2677 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured
src/commands/jobs.ts 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/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.ts
index 926fca4d56..b1dbd6ecce 100644
--- a/src/commands/doctor/checks/extraction-input.ts
+++ b/src/commands/doctor/checks/extraction-input.ts
@@ -23,6 +23,13 @@
* synopsis or fact extraction made no paid call because a fact purge's sweep covers the
* page) counts under that kind, whatever its own: its remedy is finishing the sweep
* (doctor derivation_purge_sweeps), not a higher spend cap.
+ *
+ * conversation_detection_ambiguous (PR 4, Wave B incremental derivation, transcripts): segmented conversation pages
+ * held because no format is detected over them yet some format parses messages (a `detection_ambiguous` receipt
+ * with each format's count): nothing was extracted or collected there until the operator chooses the format with
+ * gbrain extract-conversation-facts --slug <slug> --grammar <format|none> (preview with --dry-run). Such a page's
+ * receipts are listed there, not here, so a stale window receipt never offers a spend cap for it; an operator choice
+ * (`grammar_chosen`) is not a truncation and is not listed.
*/
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
@@ -46,6 +53,8 @@ const PURGE_SWEEP = 'purge_sweep_pending';
const PURGE_SWEEP_REMEDY = 'a fact purge\'s sweep of stored derivation results covers the page, so the run made no paid call there; gbrain doctor --only derivation_purge_sweeps names the purge, gbrain forget --purge --status --request-id <request_id> --continue finishes its sweep, and the next run resumes where it stopped';
const NO_MESSAGES = 'no_messages';
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 AMBIGUOUS = 'detection_ambiguous';
+const CHOSEN = 'grammar_chosen';
const remedy = (g: ReceiptGroup): string | null => g.kind === PURGE_SWEEP ? PURGE_SWEEP_REMEDY : g.kind === UNREAD_WINDOWS ? UNREAD_REMEDY : g.kind === FAILED_WINDOWS ? FAILED_REMEDY
: g.kind === NO_MESSAGES ? NO_MESSAGES_REMEDY : REMEDY[g.pipeline] ?? null;
@@ -54,17 +63,45 @@ const describe = (g: ReceiptGroup): string =>
async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<Check[]> {
const checks: Check[] = [];
+ try {
+ const held = await connectedEngine(ctx).executeRaw<{ page: string; grammars: Record<string, number> | string | null; total: number }>(
+ `SELECT p.source_id || ':' || p.slug AS page, s.input_truncated->'grammars' AS grammars, count(*) OVER ()::int AS total
+ FROM page_extraction_state s JOIN pages p ON p.id = s.page_id AND p.deleted_at IS NULL
+ WHERE s.pipeline = 'conversation_facts' AND s.input_truncated->>'kind' = '${AMBIGUOUS}'
+ ORDER BY s.updated_at DESC LIMIT 20`);
+ const pages = held.map(r => ({ page: r.page, grammars: (typeof r.grammars === 'string' ? JSON.parse(r.grammars) : r.grammars ?? {}) as Record<string, number> }));
+ if (!pages.length) {
+ checks.push({ name: 'conversation_detection_ambiguous', status: 'ok', message: 'No conversation page is held for an undetected format.', details: { pages: 0, samples: [] } });
+ } else {
+ const total = Number(held[0]!.total);
+ const sample = pages.slice(0, 3).map(p => `${p.page} (${Object.entries(p.grammars).map(([id, n]) => `${id}: ${n}`).join(', ')})`).join('; ');
+ checks.push({ name: 'conversation_detection_ambiguous', status: 'warn',
+ message: `${total} conversation page(s) are held: no format is detected over the whole page, yet these formats parse messages in it, so nothing was extracted or removed there (messages per format: ${sample}). `
+ + 'Preview the format the page holds with gbrain extract-conversation-facts --source-id <source> --slug <slug> --grammar <format> --dry-run (--grammar none for a page that is not a transcript: its conversation facts are removed), then run it without --dry-run.',
+ details: { pages: total, samples: pages },
+ fix: agentFix(['gbrain', 'extract-conversation-facts', '--source-id', '<SOURCE>', '--slug', '<SLUG>', '--grammar', '<FORMAT>', '--dry-run'],
+ "Shows what a run under the chosen format would extract and which conversation facts its settled run would remove; it changes nothing. Running it without --dry-run applies the choice, which is the user's call.",
+ 'conversation_detection_ambiguous', { ask_user: true, inputs: [
+ { name: 'SOURCE', how: 'the source id before the colon of a page in details.samples' },
+ { name: 'SLUG', how: 'the slug after the colon of that page' },
+ { name: 'FORMAT', how: "one of that page's formats in details.samples, or none when the page is not a transcript, chosen with the user" }] }) });
+ }
+ } catch (error) {
+ checks.push(checkError('conversation_detection_ambiguous', 'read the held conversation pages', error, { details: { health: 'unknown' } }));
+ }
try {
const rows = await connectedEngine(ctx).executeRaw<{ pipeline: string; kind: string; pages: number; samples: string[] }>(
`WITH receipts AS (
SELECT s.page_id, s.pipeline, COALESCE(s.input_truncated->>'kind', 'unknown') AS kind, s.updated_at, NULL::text AS detail
- FROM page_extraction_state s WHERE s.input_truncated IS NOT NULL
+ FROM page_extraction_state s WHERE s.input_truncated IS NOT NULL AND COALESCE(s.input_truncated->>'kind', '') NOT IN ('${AMBIGUOUS}', '${CHOSEN}')
UNION ALL
SELECT d.page_id, d.pipeline, CASE WHEN d.receipt->>'reason' = '${PURGE_SWEEP}' THEN '${PURGE_SWEEP}' ELSE COALESCE(d.receipt->>'kind', 'unknown') END 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 AND d.receipt->>'kind' <> 'unpriced_model') OR d.receipt->>'reason' = '${PURGE_SWEEP}' GROUP BY 1, 2, 3)
+ WHERE ((d.receipt->>'kind' IS NOT NULL AND d.receipt->>'kind' <> 'unpriced_model') OR d.receipt->>'reason' = '${PURGE_SWEEP}')
+ AND NOT EXISTS (SELECT 1 FROM page_extraction_state h WHERE h.page_id = d.page_id AND h.pipeline = d.pipeline AND h.input_truncated->>'kind' = '${AMBIGUOUS}')
+ 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 samples
FROM receipts r JOIN pages p ON p.id = r.page_id AND p.deleted_at IS NULL
@@ -103,4 +140,4 @@ async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<Che
return checks;
}
-export const extractionInputTruncatedEntry: DoctorEntry = { name: 'extraction_input_truncated', emits: ['extraction_input_truncated'], run: runExtractionInputTruncatedCheck };
+export const extractionInputTruncatedEntry: DoctorEntry = { name: 'extraction_input_truncated', emits: ['conversation_detection_ambiguous', 'extraction_input_truncated'], run: runExtractionInputTruncatedCheck };
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 670617b049..e7c4f414f8 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -111,7 +111,8 @@ import {
import { conversationEntityHints } from '../core/facts/conversation-entity-hints.ts';
import { extractConversationWindow, nonExtractableAuditFact, outcomeSession, regularPageVersionToken, terminalAuditFact } from '../core/facts/conversation-window-extract.ts';
export { segmentObservationDate } from '../core/facts/conversation-window-extract.ts';
-import { processSegmentedConversationPage } from '../core/facts/conversation-incremental.ts';
+import { processSegmentedConversationPage, type GrammarPreview } from '../core/facts/conversation-incremental.ts';
+import { BUILTIN_PATTERNS } from '../core/conversation-parser/builtins.ts';
import { isSegmentedPage } from '../core/page-body/page-shape.ts';
// Re-exported verbatim so existing importers (this file's own helpers below
@@ -285,6 +286,13 @@ export interface ExtractConversationFactsCoreOpts {
* dedup → provenance all execute THIS production pipeline with zero LLM calls.
*/
extractor?: (input: ExtractInput) => Promise<ExtractedFact[]>;
+ /**
+ * 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)
+ * unless dryRun; bypasses the fresh-outcome skip.
+ */
+ grammar?: string | null;
}
export { extractExitCode, extractRunStatus };
@@ -347,6 +355,10 @@ export interface ExtractConversationFactsResult {
pages_blocked?: number;
/** Pages the run listed more than once and extracted once (#6500). */
pages_skipped_duplicate_listing?: number;
+ /** PR 4 (Wave B incremental derivation, transcripts): pages held because no format is detected over them yet some format parses a message. */
+ pages_detection_ambiguous?: number;
+ /** PR 4 (Wave B incremental derivation, transcripts): --grammar --dry-run, what a run under the chosen format would extract and collect. */
+ grammar_previews?: GrammarPreview[];
budget_exhausted?: boolean;
budget_reason?: BudgetReason;
budget_model?: string;
@@ -1187,7 +1199,7 @@ export async function runExtractConversationFactsCore(
}
// Close the race between batch selection and lock acquisition.
- if (!opts.force) {
+ if (!opts.force && opts.grammar === undefined) {
const outcome = (
await findFreshExtractionOutcomes(engine, sourceId, [currentPage])
).get(currentPage.slug);
@@ -1202,7 +1214,7 @@ export async function runExtractConversationFactsCore(
// delete-orphans-first makes that replay deterministic.
state.cpMap.delete(cpMapKey(sourceId, currentPage.slug));
if (isSegmentedPage(currentPage) && !state.managed && !hasRawTranscriptSidecar(currentPage)) {
- const { newestEnd } = await processSegmentedConversationPage(state, currentPage, { gapMinutes: pageSegmentGapMinutes(currentPage) ?? null, sinceIso: opts.sinceIso, retryFailed: opts.force });
+ const { newestEnd } = await processSegmentedConversationPage(state, currentPage, { gapMinutes: pageSegmentGapMinutes(currentPage) ?? null, sinceIso: opts.sinceIso, retryFailed: opts.force, grammar: opts.grammar });
if (newestEnd) state.cpMap.set(cpMapKey(sourceId, currentPage.slug), newestEnd);
return { newEndIso: newestEnd };
}
@@ -1505,6 +1517,8 @@ interface ParsedArgs {
overrideDisabled?: boolean;
/** v0.41.15.0 (D9): in-process parallel workers per source. */
workers?: number;
+ /** PR 4 (Wave B incremental derivation, transcripts): --grammar <format|none> for the one --slug page. */
+ grammar?: string | null;
yes?: boolean;
json?: boolean;
help?: boolean;
@@ -1523,6 +1537,15 @@ export function parseArgs(args: string[]): ParsedArgs {
if (a === '--override-disabled') { out.overrideDisabled = true; continue; }
if (a === '--slug') { out.slug = args[++i]; continue; }
if (a === '--slugs') { out.slugs = (args[++i] ?? '').split(',').map(s => s.trim()).filter(Boolean); continue; }
+ if (a === '--grammar') {
+ const v = args[++i] ?? '';
+ if (v !== 'none' && !BUILTIN_PATTERNS.some(p => p.id === v)) {
+ out.error = `--grammar takes none or a conversation format: ${BUILTIN_PATTERNS.map(p => p.id).join(', ')}`;
+ return out;
+ }
+ out.grammar = v === 'none' ? null : v;
+ continue;
+ }
if (a === '--source-id') { out.sourceId = args[++i]; continue; }
if (a === '--since') { out.sinceIso = args[++i]; continue; }
if (a === '--types') {
@@ -1563,6 +1586,7 @@ export function parseArgs(args: string[]): ParsedArgs {
return out;
}
}
+ if (out.grammar !== undefined && (!out.slug || out.slugs?.length)) out.error = '--grammar chooses the format of one page: pass it with --slug <slug>';
if (out.sinceIso) {
const ms = Date.parse(out.sinceIso);
if (!Number.isFinite(ms)) {
@@ -1588,6 +1612,12 @@ 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
+ (none: the page is not a transcript; it settles as not
+ extractable and its conversation facts are removed). For a page
+ held 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.
--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.
@@ -1627,9 +1657,19 @@ in the facts table (source='${TERMINAL_AUDIT_SOURCE}'). gbrain doctor's
conversation_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> {
+ 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);
+ }
+}
+
function buildJobParams(args: string[]): Record<string, unknown> {
const parsed = parseArgs(args);
if (parsed.error) throw usageError(parsed.error, ECF_HELP_HINT);
+ if (parsed.grammar !== undefined) throw usageError('--grammar runs in the foreground: drop --background', ECF_HELP_HINT);
return {
sourceId: parsed.sourceId,
types: parsed.types,
@@ -1675,8 +1715,8 @@ export async function runExtractConversationFacts(
// Chat gateway is required for non-dry-run. Recover a cold singleton before
// reporting an availability error (#2590).
- if (!parsed.dryRun && !isAvailable('chat')) configureGatewayIfUninitialized();
- if (!parsed.dryRun && !isAvailable('chat')) {
+ if (!parsed.dryRun && parsed.grammar !== null && !isAvailable('chat')) configureGatewayIfUninitialized();
+ if (!parsed.dryRun && parsed.grammar !== null && !isAvailable('chat')) {
console.error(
'Chat gateway unavailable. Set a provider key (OPENAI_API_KEY or ANTHROPIC_API_KEY — ' +
'extraction routes to whichever is present), or configure a model explicitly ' +
@@ -1701,6 +1741,7 @@ export async function runExtractConversationFacts(
? [parsed.sourceId]
: (await listSources(engine)).map((s) => s.id);
+ if (parsed.grammar !== undefined) await assertGrammarTarget(engine, sourceIds, parsed.slug!);
progress.start('extract.conversation_facts', sourceIds.length);
try {
@@ -1719,6 +1760,7 @@ export async function runExtractConversationFacts(
maxCostUsd: parsed.maxCostUsd,
overrideDisabled: parsed.overrideDisabled,
workers: parsed.workers,
+ grammar: parsed.grammar,
});
aggregate.pages_considered += perSource.pages_considered;
@@ -1746,6 +1788,8 @@ export async function runExtractConversationFacts(
aggregate.resolution_errors += perSource.resolution_errors;
if (perSource.pages_pending) aggregate.pages_pending = (aggregate.pages_pending ?? 0) + perSource.pages_pending;
if (perSource.pages_blocked) aggregate.pages_blocked = (aggregate.pages_blocked ?? 0) + perSource.pages_blocked;
+ if (perSource.pages_detection_ambiguous) aggregate.pages_detection_ambiguous = (aggregate.pages_detection_ambiguous ?? 0) + perSource.pages_detection_ambiguous;
+ if (perSource.grammar_previews) (aggregate.grammar_previews ??= []).push(...perSource.grammar_previews);
if (perSource.budget_exhausted) anyBudgetExhausted = true;
if (perSource.budget_reason === 'no_pricing') unpricedModels.add(perSource.budget_model ?? 'unknown model');
if (perSource.budget_pricing) pricingGuidance.set(perSource.budget_pricing.model, perSource.budget_pricing);
@@ -1812,6 +1856,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_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.ts
index 44a9018a47..24cc9d5f5b 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 the transcript can outweigh its message lines) is extracted in the format earlier runs recorded that parses the most messages in it, so only the windows that format still finds keep their facts; when two recorded formats both parse messages and neither parses more than twice the other, the run fails for that page and changes nothing until an edit makes one format clearly dominant; a page with no message in any recorded format, or with no recorded format and none detected (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 --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.' },
// 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/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index d1111a75fd..11d9e22cda 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -49,7 +49,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -61,7 +61,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--call-plan', '--call-plan-gate', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--error-unmatch', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--request-id', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--timings', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--body', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--timings', '--type', '--wait'],
'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--batch-check', '--body', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--legacy-lock', '--limit', '--literal-pathspecs', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--retry-held', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--timings', '--type', '--verbose', '--wait', '--workers', '--yes'],
- 'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--body', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
+ 'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--body', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--grammar', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--all', '--brain', '--clear', '--conversation', '--dry-run', '--entity', '--examples', '--expected-state', '--force', '--help', '--include-private', '--json', '--limit', '--list', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--reset', '--retry-model', '--since', '--slug', '--slugs', '--source', '--source-id'],
'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--held', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--retry-held', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'feedback': ['--brain', '--help', '--json', '--page', '--source'],
@@ -75,14 +75,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--input', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--output', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--input', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--output', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--purge', '--push-only', '--query', '--question', '--queue', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--purge', '--push-only', '--query', '--question', '--queue', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
@@ -130,7 +130,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],
- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index af73d634f1..f9ef16a3df 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): conversation pages held because no format is detected over them.
+ 'conversation_detection_ambiguous',
// PR 4 (Wave B incremental derivation, transcripts): segmented derivations held back by a model without a price.
'derivation_unpriced_model',
'facts_embedding_width_consistency',
diff --git a/src/core/extraction-watermark.ts b/src/core/extraction-watermark.ts
index 533ef1b6ea..b7f877596f 100644
--- a/src/core/extraction-watermark.ts
+++ b/src/core/extraction-watermark.ts
@@ -36,8 +36,14 @@ 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 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';
+ /**
+ * 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. `detection_ambiguous`, no format is
+ * detected over a segmented conversation page yet the formats in `grammars` parse messages in it: the page is held, nothing
+ * extracted or collected, until it changes or the operator chooses its format. `grammar_chosen`, the operator's format
+ * (`gbrain extract-conversation-facts --grammar`) for page version `version_token`; not a truncation.
+ */
+ kind: 'head' | 'tail_window' | 'skipped_too_large' | 'no_messages' | 'detection_ambiguous' | 'grammar_chosen';
pipeline: ExtractionPipeline;
/** Characters the extractor read (0 for a skipped page). */
processed_chars: number;
@@ -55,6 +61,11 @@ export interface InputTruncated {
*/
window_rule?: 'no_prior_facts' | 'prior_facts_kept';
prior_facts?: number;
+ /** PR 4 (Wave B incremental derivation, transcripts): `detection_ambiguous`: the messages each format that parses any parses over the page. */
+ grammars?: Record<string, number>;
+ /** PR 4 (Wave B incremental derivation, transcripts): `grammar_chosen`: the chosen format (null: none, the page is not a transcript) and the page version it holds for. */
+ grammar?: string | null;
+ version_token?: string;
}
export interface StoredWatermark { pipelineVersion: number; bytes: number; sha256: string }
@@ -208,6 +219,19 @@ export async function commitExtractionPlan(engine: BrainEngine, pageId: number,
}
/** Record (receipt) or clear (null) the partial-input receipt of a pipeline that keeps no watermark: the conversation-facts size skip. */
+/** PR 4 (Wave B incremental derivation, transcripts): the page's receipt for `pipeline`, or null (none, or unreadable). */
+export async function readExtractionReceipt(engine: BrainEngine, pageId: number, pipeline: ExtractionPipeline): Promise<InputTruncated | null> {
+ try {
+ const [row] = await engine.executeRaw<{ receipt: InputTruncated | string | null }>(
+ 'SELECT input_truncated AS receipt FROM page_extraction_state WHERE page_id = $1 AND pipeline = $2', [pageId, pipeline]);
+ const receipt = row?.receipt ?? null;
+ return typeof receipt === 'string' ? JSON.parse(receipt) as InputTruncated : receipt;
+ } catch (error) {
+ warnStorageOnce('read the extraction receipt', error);
+ return null;
+ }
+}
+
export async function setExtractionReceipt(engine: BrainEngine, pageId: number, pipeline: ExtractionPipeline,
receipt: InputTruncated | null): Promise<void> {
try {
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
index f19b2ec1ee..66e4089834 100644
--- a/src/core/facts/conversation-incremental.ts
+++ b/src/core/facts/conversation-incremental.ts
@@ -27,10 +27,11 @@
* 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; with none detected, the recorded grammar that
- * parses the most messages, while it parses more than twice any other recorded grammar (else the page fails and
- * nothing is published); 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
+ * recorded it under the same context are mostly unchanged by bytes, 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; no call, nothing
+ * published or collected) until it changes or the operator chooses; a page no format parses a message in 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;
@@ -51,13 +52,14 @@ import { loadPricingOverrides, type PricingOverrides } from '../budget/budget-tr
import { providerItemRefusal } from '../ai/errors.ts';
import { writeDerivedFacts } from '../persistence/derived-facts.ts';
import { estimateFactsExtractionUsd, meterPaidCall, unpricedModelReceipt } from '../page-embedding-budget.ts';
-import { setExtractionReceipt } from '../extraction-watermark.ts';
+import { readExtractionReceipt, setExtractionReceipt, type InputTruncated } from '../extraction-watermark.ts';
import { planSegmentDerivations, segmentDerivationContextHash, sourceWindowFor, sourceWindowKey, type SegmentDerivationInput,
type SegmentDerivationRow, type SourceWindow } from '../page-body/derivations.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 { countWindowFacts, publishConversationFacts, type ConversationFactRow } from './conversation-publication.ts';
+import { countConversationFactsOutside, countWindowFacts, publishConversationFacts, type ConversationFactRow } from './conversation-publication.ts';
+import { BUILTIN_PATTERNS } from '../conversation-parser/builtins.ts';
import { recordFailedPage } from './conversation-run-status.ts';
import { detectPagePattern, startsConversationRun, streamConversationWindows } from './conversation-stream.ts';
import type { ConversationSegment } from './conversation-types.ts';
@@ -84,8 +86,15 @@ export interface SegmentedConversationCounters {
pages_marked_non_extractable: number; pages_failed: number; segments_processed: number; facts_extracted: number;
facts_inserted: number; orphan_facts_cleaned: number; fallback_slugify_count: number; resolution_errors: number;
failed_pages: Array<{ slug: string; error: string }>;
+ /** Pages held because no format is detected over them yet some format parses a message (a detection_ambiguous receipt). */
+ pages_detection_ambiguous?: number;
+ /** --grammar --dry-run: what a run under the chosen format would extract and collect, per page. */
+ grammar_previews?: GrammarPreview[];
}
+/** 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 SegmentedConversationRun extends ConversationWindowRun {
result: SegmentedConversationCounters;
dryRun: boolean;
@@ -137,12 +146,23 @@ function windowFailure(error: unknown, signal: AbortSignal | undefined): boolean
return reason === 'provider_error' && providerItemRefusal((error as { cause?: unknown }).cause) !== null;
}
+/** The messages each built-in format parses over the whole page, for the formats that parse any (unpaid reads). */
+async function messagesByGrammar(occurrences: Parameters<typeof streamConversationWindows>[0], opts: { page: Page; gapMinutes: number | null },
+ readText: (index: number) => Promise<string>): Promise<Record<string, number>> {
+ const counts: Record<string, number> = {};
+ for (const { id } of BUILTIN_PATTERNS) {
+ const parsed = await streamConversationWindows(occurrences, 0, occurrences.length, { ...opts, pattern: id }, readText, { window() {}, occurrence() {} });
+ if (parsed.messages > 0) counts[id] = parsed.messages;
+ }
+ return counts;
+}
+
/**
* One segmented page's conversation facts, incrementally (module doc). `gapMinutes` is the page's own
* conversation_segment_gap_minutes (null: the default). Returns the end of the newest window it extracted.
*/
export async function processSegmentedConversationPage(run: SegmentedConversationRun, page: Page,
- opts: { gapMinutes: number | null; sinceIso?: string; retryFailed?: boolean; redetect?: boolean }): Promise<{ newestEnd: string | null }> {
+ opts: { gapMinutes: number | null; sinceIso?: string; retryFailed?: boolean; redetect?: boolean; grammar?: string | null }): Promise<{ newestEnd: string | null }> {
const { engine, sourceId, result } = run;
if (!opts.redetect) result.pages_considered++;
const versionToken = regularPageVersionToken(page);
@@ -177,42 +197,35 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
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;
- let recovered = false;
+ // The operator's format for the page (gbrain extract-conversation-facts --grammar): this run's, else the one chosen for
+ // this page version. It covers the whole page, so the stream starts at its head; none (null) settles it as non-extractable.
+ const stored = opts.grammar === undefined ? await readExtractionReceipt(engine, page.id, KIND) : null;
+ const choice = opts.grammar !== undefined ? opts.grammar
+ : stored?.kind === 'grammar_chosen' && stored.version_token === versionToken ? stored.grammar ?? null : undefined;
+ const choiceReceipt: InputTruncated | null = choice === undefined ? null : { kind: 'grammar_chosen', pipeline: KIND, processed_chars: 0, grammar: choice, version_token: versionToken };
+ if (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;
+ const pinned = choice === undefined && 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 (choice === undefined && !pattern && from < liveIds.length) pattern = await detectPagePattern(occurrences, i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }));
+ if (choice === undefined && !pattern && from < liveIds.length) {
if (opts.sinceIso) { result.pages_skipped++; return { newestEnd: null }; }
- // No grammar over the whole page (text around a transcript can tip the density test). Of the grammars earlier runs
- // recorded, the one that parses the most messages here (on a tie, the one recorded last) is the page's grammar: the
- // run goes on under it, so its windows replace their exact keys and a settled run collects the rest. It must parse
- // more than twice the messages of any other recorded grammar, else the other may be the real one and collecting
- // would delete its facts: the page fails with nothing published until an edit settles which format it is. When no
- // recorded grammar parses a message, the page stopped being a transcript: it settles as non-extractable below and
- // its conversation facts are collected.
- const lastRecorded = new Map<string, string>();
- for (const row of prior) {
- const recordedGrammar = rowOutput(row).pattern;
- if (recordedGrammar && row.updatedAt > (lastRecorded.get(recordedGrammar) ?? '')) lastRecorded.set(recordedGrammar, row.updatedAt);
- }
- const candidates: Array<{ grammar: string; messages: number; at: string }> = [];
- for (const [grammar, at] of lastRecorded) {
- const parsed = await streamConversationWindows(occurrences, 0, liveIds.length, { page, gapMinutes: opts.gapMinutes, pattern: grammar },
- i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }), { window() {}, occurrence() {} });
- candidates.push({ grammar, messages: parsed.messages, at });
- }
- candidates.sort((a, b) => b.messages - a.messages || (a.at < b.at ? 1 : a.at > b.at ? -1 : 0));
- const [best, rival] = candidates;
- if (best && rival && best.messages > 0 && best.messages <= 2 * rival.messages) {
- const why = `no format is detected and its recorded formats compete (${best.grammar}: ${best.messages} messages, ${rival.grammar}: ${rival.messages}); facts kept, nothing settled`;
- process.stderr.write(`[extract-conversation-facts] ${page.slug}: ${why}\n`);
- result.pages_failed++;
- recordFailedPage(result, page.slug, why);
+ // No format is detected over the whole page. One that still parses a message here may be the page's (text around a
+ // transcript can tip the density test) or a quoted part of it, and guessing has deleted current facts: the page is
+ // held, with no call, nothing published or collected and a detection_ambiguous receipt naming each format's count,
+ // until it changes or the operator chooses its format. A page no format parses a message in is not a transcript: it
+ // settles as non-extractable below and its conversation facts are collected.
+ const grammars = await messagesByGrammar(occurrences, { page, gapMinutes: opts.gapMinutes }, i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }));
+ if (Object.keys(grammars).length) {
+ if (!run.dryRun) await setExtractionReceipt(engine, page.id, KIND, { kind: 'detection_ambiguous', pipeline: KIND, processed_chars: 0, grammars });
+ result.pages_detection_ambiguous = (result.pages_detection_ambiguous ?? 0) + 1;
+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: held: 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`);
return { newestEnd: null };
}
- if (best && best.messages > 0) { pattern = best.grammar; recovered = true; }
- if (!pattern) from = 0;
+ 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 }>>();
@@ -279,6 +292,12 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
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++;
+ if (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,
+ facts_to_collect: await countConversationFactsOutside(engine, sourceId, page.slug, keys) });
+ }
return { newestEnd: null };
}
@@ -407,9 +426,16 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
result.resolution_errors += resolution.resolution_errors;
}
- if (pattern && !recovered && from < liveIds.length && parsedMessages === 0) {
+ 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 });
+ if (choice !== undefined) {
+ // The chosen format reads nothing here: the choice is dropped, nothing is published, and the page is held again.
+ await setExtractionReceipt(engine, page.id, KIND, null);
+ result.pages_failed++;
+ recordFailedPage(result, page.slug, `the chosen format ${pattern} parses no message on the page; facts kept, choose another or none`);
+ return { newestEnd: null };
+ }
// 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}: the page reads as ${pattern} but no message parsed under it; its facts were kept, nothing settled\n`);
@@ -418,7 +444,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
return { newestEnd: null };
}
const { unchanged, settled, liveKeys, outcome } = await publish(true);
- await setExtractionReceipt(engine, page.id, KIND, null);
+ await setExtractionReceipt(engine, page.id, KIND, choiceReceipt);
if (!unchanged) {
process.stderr.write(`[extract-conversation-facts] ${page.slug} changed during extraction; its finished windows were kept, the rest wait for the next run\n`);
result.pages_failed++;
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index e426dabc02..e857de000e 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -558,6 +558,14 @@ export async function countWindowFacts(db: BrainEngine, sourceId: string, slug:
return Number(row?.count ?? 0);
}
+/** The page's active conversation facts a settled collection keeping window `keys` removes: anchored to another window, or unanchored. */
+export async function countConversationFactsOutside(db: BrainEngine, sourceId: string, slug: string, keys: readonly 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 NOT (f.source = ANY($3::text[])) AND f.expired_at IS NULL
+ AND (f.source_window IS NULL OR NOT (${WINDOW_KEY_SQL} = ANY($4::text[])))`, [sourceId, slug, [...AUDIT_ROW_SOURCES], [...keys]]);
+ 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`.
diff --git a/test/extract-conversation-facts-flags.test.ts b/test/extract-conversation-facts-flags.test.ts
index fc3bbf3c89..b427f9a725 100644
--- a/test/extract-conversation-facts-flags.test.ts
+++ b/test/extract-conversation-facts-flags.test.ts
@@ -5,7 +5,7 @@
*/
import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { runExtractConversationFacts } from '../src/commands/extract-conversation-facts.ts';
+import { parseArgs, runExtractConversationFacts } from '../src/commands/extract-conversation-facts.ts';
let engine: PGLiteEngine;
@@ -57,3 +57,23 @@ describe('extract-conversation-facts numeric flags', () => {
}
});
});
+
+describe('extract-conversation-facts --grammar (PR 4, Wave B incremental derivation, transcripts)', () => {
+ test('takes a built-in conversation format or none, for one --slug page', () => {
+ expect(parseArgs(['--slug', 'notes/a', '--grammar', 'plain-role-no-time', '--dry-run'])).toMatchObject({ slug: 'notes/a', grammar: 'plain-role-no-time', dryRun: true });
+ expect(parseArgs(['--slug', 'notes/a', '--grammar', 'none']).grammar).toBeNull();
+ expect(parseArgs(['--slug', 'notes/a']).grammar).toBeUndefined();
+ });
+
+ test('refuses an unknown format, a missing --slug and --slugs', () => {
+ expect(parseArgs(['--slug', 'notes/a', '--grammar', 'no-such-format']).error).toContain('--grammar takes none or a conversation format');
+ expect(parseArgs(['--grammar', 'none']).error).toContain('pass it with --slug');
+ expect(parseArgs(['--slugs', 'notes/a,notes/b', '--grammar', 'none']).error).toContain('pass it with --slug');
+ });
+
+ test('refuses a page extracted whole before any work', async () => {
+ await engine.putPage('notes/small-chat', { type: 'conversation', title: 'Small chat', compiled_truth: 'User: hello\nAssistant: hi there\n', timeline: '' }, { sourceId: 'default' });
+ await expect(runExtractConversationFacts(engine, ['--dry-run', '--source-id', 'default', '--slug', 'notes/small-chat', '--grammar', 'plain-role-no-time']))
+ .rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('--grammar applies to a conversation page stored in segments; default:notes/small-chat is extracted whole') });
+ });
+});
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 948d41a303..4a31245a4e 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -209,6 +209,7 @@
" [OK] consumers_without_heartbeat: PGLite admits one process; no consumer heartbeat rows are kept.",
" [OK] host_identity_mismatch: This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.",
" [OK] extract_atoms_held_failed: No managed atom page or transcript is held after repeated extraction failures.",
+ " [OK] conversation_detection_ambiguous: No conversation page is held for an undetected format.",
" [OK] extraction_input_truncated: Every page extraction read all of its input (no head-only, tail-window or size-skip receipts).",
" [OK] derivation_unpriced_model: No segmented page derivation is held back by a model without a price.",
" [OK] ghost_pages: No live page is missing its canonical file (5 page(s) inspected).",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 483e095089..69abfa699d 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -3131,6 +3131,17 @@
"name": "extract_atoms_held_failed",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "pages": 0,
+ "samples": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No conversation page is held for an undetected format.",
+ "name": "conversation_detection_ambiguous",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index 7cd23e0eb2..c126a686e8 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -3334,6 +3334,17 @@
"name": "extract_atoms_held_failed",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "pages": 0,
+ "samples": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No conversation page is held for an undetected format.",
+ "name": "conversation_detection_ambiguous",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -7864,6 +7875,17 @@
"name": "extract_atoms_held_failed",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "pages": 0,
+ "samples": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No conversation page is held for an undetected format.",
+ "name": "conversation_detection_ambiguous",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index c1fc26dc9e..1d7cf636fb 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -3337,6 +3337,17 @@
"name": "extract_atoms_held_failed",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "pages": 0,
+ "samples": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No conversation page is held for an undetected format.",
+ "name": "conversation_detection_ambiguous",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -7868,6 +7879,17 @@
"name": "extract_atoms_held_failed",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "pages": 0,
+ "samples": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No conversation page is held for an undetected format.",
+ "name": "conversation_detection_ambiguous",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 6e3dba9060..9ba203740c 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -2852,6 +2852,17 @@
"name": "extract_atoms_held_failed",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "pages": 0,
+ "samples": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No conversation page is held for an undetected format.",
+ "name": "conversation_detection_ambiguous",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index eae3cb499a..ab3fae182e 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -2896,6 +2896,17 @@
"name": "extract_atoms_held_failed",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "pages": 0,
+ "samples": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No conversation page is held for an undetected format.",
+ "name": "conversation_detection_ambiguous",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index a5014cbe15..c4aefcfebe 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -2899,6 +2899,17 @@
"name": "extract_atoms_held_failed",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "pages": 0,
+ "samples": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No conversation page is held for an undetected format.",
+ "name": "conversation_detection_ambiguous",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 2acc8ab7fd..b2c0e4fdd0 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -885,6 +885,10 @@
"category": "brain",
"name": "extract_atoms_held_failed"
},
+ {
+ "category": "brain",
+ "name": "conversation_detection_ambiguous"
+ },
{
"category": "brain",
"name": "extraction_input_truncated"
diff --git a/test/helpers/conversation-facts-incremental-cases.ts b/test/helpers/conversation-facts-incremental-cases.ts
index 2a5799febb..c2626ddf5f 100644
--- a/test/helpers/conversation-facts-incremental-cases.ts
+++ b/test/helpers/conversation-facts-incremental-cases.ts
@@ -109,11 +109,11 @@ export function paidTransport(o: ChatOpts): Promise<ChatResult> {
* `abortAfter`: the run is aborted after that many calls; `segmentLimit`: at most that many windows per page.
*/
export async function extract(engine: BrainEngine, slug: string, opts: { force?: boolean; paid?: boolean; failAt?: number; failOn?: (text: string) => boolean;
- abortAfter?: number; sinceIso?: string; segmentLimit?: number } = {}) {
+ abortAfter?: number; sinceIso?: string; segmentLimit?: number; grammar?: string | null; dryRun?: boolean } = {}) {
const calls: string[] = [];
const controller = new AbortController();
const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [slug], sleepMs: 0, force: opts.force,
- sinceIso: opts.sinceIso, segmentLimit: opts.segmentLimit,
+ sinceIso: opts.sinceIso, segmentLimit: opts.segmentLimit, grammar: opts.grammar, dryRun: opts.dryRun,
extractor: async input => {
calls.push(input.turnText);
if (opts.paid) await gatewayChat({ model: PAID_MODEL, messages: [{ role: 'user', content: input.turnText }], maxTokens: 64 });
diff --git a/test/helpers/conversation-facts-invariant-cases.ts b/test/helpers/conversation-facts-invariant-cases.ts
index 7b92eb3f93..8ccdf6fd78 100644
--- a/test/helpers/conversation-facts-invariant-cases.ts
+++ b/test/helpers/conversation-facts-invariant-cases.ts
@@ -182,7 +182,7 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap
expect({ listed: group?.samples.includes(`default:${slug}`), fault: group?.remedy?.includes('parser fault') }).toEqual({ listed: true, fault: true });
}, 600_000);
- test('N1: a transcript whose grammar the whole page no longer shows (references added, title changed) runs on the grammar it recorded: every window is extracted again under its new key, holds its batch, and the page settles', async () => {
+ test('N1: a transcript whose format the whole page no longer shows (references added, title changed) is held: no call, every fact and row kept, --force too, and doctor lists it with its format\'s count', async () => {
const brain = opts.getBrain();
const slug = `notes/grammar-lost-${randomUUID().slice(0, 8)}`;
await caps(brain.engine, 'off');
@@ -192,14 +192,18 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap
const before = await factsOf(brain.engine, slug);
expect({ processed: first.result.pages_processed, facts: before.length > 100 }).toEqual({ processed: 1, facts: true });
await brain.seed(slug, chatPage('Grammar lost, renamed', `${transcript}\n\n## References\n\n${references(3000)}`));
- const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;
- expect(parser.parseConversation((await brain.body(slug)).truth, { page }).matched_pattern_id).toBeUndefined();
- const { calls, result } = await extract(brain.engine, slug);
- const after = await factsOf(brain.engine, slug);
- const rows = await derivations(brain.engine, slug);
- expect({ calls: calls.length, failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, processed: result.pages_processed, facts: after.length,
- windows: rows.keys.length >= before.length, mismatches: await claimMismatches(brain.engine, slug), states: [...new Set(rows.states)] })
- .toEqual({ calls: rows.keys.length, failed: 0, nonExtractable: 0, processed: 1, facts: rows.keys.length, windows: true, mismatches: [], states: ['done'] });
+ expect(await undetected(brain, slug)).toBeNull();
+ const rows = await rowState(brain, slug);
+ const runs = [];
+ for (const force of [false, true]) {
+ const { calls, result } = await extract(brain.engine, slug, { force });
+ runs.push({ calls: calls.length, failed: result.pages_failed, held: result.pages_detection_ambiguous ?? 0, nonExtractable: result.pages_marked_non_extractable,
+ facts: (await factsOf(brain.engine, slug)).map(f => f.id), rows: await rowState(brain, slug) });
+ }
+ const doctor = await heldPages(brain);
+ const run = { calls: 0, failed: 0, held: 1, nonExtractable: 0, facts: before.map(f => f.id), rows };
+ expect({ runs, status: doctor.status, listed: doctor.samples.find(s => s.page === `default:${slug}`)?.grammars, truncated: doctor.truncated.includes(slug) })
+ .toEqual({ runs: [run, run], status: 'warn', listed: { 'bold-name-no-time': 3000 }, truncated: false });
}, 600_000);
/** Three runs (two plain, one --force) on a page whose grammar is no longer detected: what each reported and left. */
@@ -208,8 +212,8 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap
for (const force of [false, false, true]) {
const { calls, result } = await extract(brain.engine, slug, { force });
const rows = await derivations(brain.engine, slug);
- out.push({ calls: calls.length, failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, facts: (await factsOf(brain.engine, slug)).length,
- windows: rows.keys.length, mismatches: (await claimMismatches(brain.engine, slug)).length });
+ out.push({ calls: calls.length, failed: result.pages_failed, held: result.pages_detection_ambiguous ?? 0, nonExtractable: result.pages_marked_non_extractable,
+ facts: (await factsOf(brain.engine, slug)).length, windows: rows.keys.length, mismatches: (await claimMismatches(brain.engine, slug)).length });
}
return out;
};
@@ -217,26 +221,40 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap
const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;
return parser.parseConversation((await brain.body(slug)).truth, { page }).matched_pattern_id ?? null;
};
+ /** A held run: no call, no failure, nothing added or removed. */
+ const heldRun = (facts: number, windows: number) => ({ calls: 0, failed: 0, held: 1, nonExtractable: 0, facts, windows, mismatches: 0 });
+ /** Every conversation_facts row of the page, as it stands. */
+ const rowState = async (brain: AppendBrain, slug: string) => JSON.stringify((await derivations(brain.engine, slug)).rows.map(row => [row.occurrenceId, row.output, row.state, row.receipt]));
+ /** What doctor reports: the held pages with each format's count, and whether extraction_input_truncated (the spend-cap remedy) names anything. */
+ const heldPages = async (brain: AppendBrain) => {
+ const checks = await extractionInputTruncatedEntry.run({ engine: brain.engine } as unknown as DoctorContext) as Check[];
+ const held = checks.find(c => c.name === 'conversation_detection_ambiguous')!;
+ return { status: held.status, samples: ((held.details as { samples?: Array<{ page: string; grammars: Record<string, number> }> } | undefined)?.samples ?? []),
+ fix: held.fix?.argv ?? null, truncated: JSON.stringify(checks.find(c => c.name === 'extraction_input_truncated')?.details ?? {}) };
+ };
- test('R4 (case A): a transcript rewritten to prose that keeps quoted message lines settles under its recorded grammar, keeping only the windows those lines still make', async () => {
+ test('R4 (case A): a transcript rewritten to prose that keeps one or three quoted message lines is held every run, --force too: its facts wait for the operator\'s call', async () => {
const brain = opts.getBrain();
const out: Record<string, unknown> = {};
+ const expected: Record<string, unknown> = {};
for (const quoted of [1, 3]) {
const slug = `notes/quoted-line-${randomUUID().slice(0, 8)}`;
await caps(brain.engine, 'off');
await brain.seed(slug, chatPage('Was a chat', chatDays(4600, 100, 38)));
await extract(brain.engine, slug);
- expect((await factsOf(brain.engine, slug)).length).toBeGreaterThan(100);
+ const facts = (await factsOf(brain.engine, slug)).length;
+ expect(facts).toBeGreaterThan(100);
+ const windows = (await derivations(brain.engine, slug)).keys.length;
const lines = Array.from({ length: quoted }, (_, i) => `**${i % 2 ? 'Bob Example' : 'Alice Example'}** (1:0${5 + i} PM): the orchard review moved, part ${i}.`).join('\n\n');
await brain.seed(slug, chatPage('Was a chat', `${references(9000)}\n\nLines we quoted from the old chat:\n\n${lines}`));
expect(await undetected(brain, slug)).toBeNull();
out[quoted] = await lostGrammarRuns(brain, slug);
+ expected[quoted] = [heldRun(facts, windows), heldRun(facts, windows), heldRun(facts, windows)];
}
- const run = (calls: number, nonExtractable: number, windows: number) => ({ calls, failed: 0, nonExtractable, facts: windows, windows, mismatches: 0 });
- expect(out).toEqual({ 1: [run(0, 1, 0), run(0, 0, 0), run(0, 1, 0)], 3: [run(1, 0, 1), run(0, 0, 1), run(0, 0, 1)] });
+ expect(out).toEqual(expected);
}, 600_000);
- test('R4 (cases B, B-heading): a transcript with reference lines added, before and after they move below a heading, settles under its recorded grammar every run', async () => {
+ test('R4 (cases B, B-heading): a transcript with reference lines added, before and after they move below a heading, is held every run with its facts kept', async () => {
const brain = opts.getBrain();
const slug = `notes/references-${randomUUID().slice(0, 8)}`;
await caps(brain.engine, 'off');
@@ -244,75 +262,132 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap
const refs = Array.from({ length: 100 }, (_, i) => `Additional reference paragraph ${i}.`).join('\n');
await brain.seed(slug, chatPage('References', transcript));
await extract(brain.engine, slug);
- const before = (await factsOf(brain.engine, slug)).length;
- expect(before).toBeGreaterThan(0);
+ const facts = (await factsOf(brain.engine, slug)).length;
+ const windows = (await derivations(brain.engine, slug)).keys.length;
+ expect(facts).toBeGreaterThan(0);
await brain.seed(slug, chatPage('References, retitled', transcript + refs));
expect(await undetected(brain, slug)).toBeNull();
const added = await lostGrammarRuns(brain, slug);
await brain.seed(slug, chatPage('References, retitled again', `${transcript}\n## References\n\n${refs}`));
expect(await undetected(brain, slug)).toBeNull();
const heading = await lostGrammarRuns(brain, slug);
- // The reference lines continue the last message, so its windows grow; every window is extracted under the new title.
- const settled = (runs: typeof added) => { const windows = runs[0]!.windows as number; const run = (calls: number) => ({ calls, failed: 0, nonExtractable: 0, facts: windows, windows, mismatches: 0 });
- return { grew: windows >= before, runs: [run(windows), run(0), run(0)] }; };
- expect({ added: { grew: true, runs: added }, heading: { grew: true, runs: heading } }).toEqual({ added: settled(added), heading: settled(heading) });
+ const held = [heldRun(facts, windows), heldRun(facts, windows), heldRun(facts, windows)];
+ expect({ added, heading }).toEqual({ added: held, heading: held });
}, 600_000);
/**
- * A page whose rows record two grammars, and whose grammar the whole page no longer shows: a bold-name transcript
- * extracted in full, rewritten to a plain-role one (keeping `quotes` bold-name lines) and extracted one window, so the
- * rows it reached record plain-role and the rest bold-name; then reference text and a new title around both.
+ * A page whose rows record two formats, with none detected over it (round-8 review P1 and P2): a bold-name transcript
+ * extracted in full, then a plain-role one extracted one window (its rows record plain-role, the rest bold-name), then
+ * reference prose, the plain-role transcript and a section quoting `quotes` short bold-name turns under a new title.
*/
- const twoGrammars = async (brain: AppendBrain, slug: string, quotes: number) => {
+ const mixedFormats = async (brain: AppendBrain, slug: string, quotes: number) => {
await caps(brain.engine, 'off');
- const old = Array.from({ length: 100 }, (_, i) => `**${i % 2 ? 'Bob Example' : 'Alice Example'}:** legacy turn ${i} ${'detail '.repeat(1600)}`).join('\n');
- await brain.seed(slug, chatPage('Format change', old));
+ const old = Array.from({ length: 100 }, (_, i) => `**${i % 2 ? 'Bob Example' : 'Alice Example'}:** old turn ${i} ${'detail '.repeat(1600)}`).join('\n');
+ await brain.seed(slug, chatPage('Old transcript', old));
await extract(brain.engine, slug);
const current = Array.from({ length: 200 }, (_, i) => `${i % 2 ? 'Assistant' : 'User'}: current turn ${i} ${'present '.repeat(700)}`).join('\n');
- const kept = Array.from({ length: quotes }, (_, i) => `**${i % 2 ? 'Bob Example' : 'Alice Example'}:** a line quoted from the old format, part ${i}.`).join('\n');
- await brain.seed(slug, chatPage('Format change', `${current}\n${kept}\n`));
+ await brain.seed(slug, chatPage('Current transcript', current));
await extract(brain.engine, slug, { segmentLimit: 1 });
expect(await recordedGrammars(brain, slug)).toEqual(['bold-name-no-time', 'plain-role-no-time']);
- const prose = Array.from({ length: 12_000 }, (_, i) => `Paragraph ${i} with unrelated reference material.`).join('\n');
- await brain.seed(slug, chatPage('Format change, retitled', `${prose}\n${current}\n${kept}\n`));
+ const quoted = Array.from({ length: quotes }, (_, i) => `**${i % 2 ? 'Bob Example' : 'Alice Example'}:** quoted historical turn ${i}.`).join('\n');
+ const prose = Array.from({ length: 12_000 }, (_, i) => `Reference paragraph ${i} explains the migration.`).join('\n');
+ await brain.seed(slug, chatPage('Combined transcript archive', `${prose}\n${current}\n## Quoted historical transcript\n${quoted}`));
expect(await undetected(brain, slug)).toBeNull();
- return { prose, current };
+ return { prose, current, quoted };
};
const recordedGrammars = async (brain: AppendBrain, slug: string) =>
[...new Set((await derivations(brain.engine, slug)).rows.map(row => (row.output as { pattern?: string | null }).pattern ?? null))].sort();
/** The plain-role turns the run's windows carry. */
const turnsIn = (calls: string[]) => new Set(calls.flatMap(text => [...text.matchAll(/current turn (\d+) /g)].map(m => m[1]))).size;
- test('G1: with no grammar detected, the recorded grammar that parses the most messages is the page\'s, not the first one that parses any: the current transcript is extracted again and the page settles', async () => {
+ test('G1 (round-8 P1, P2): with two recorded formats and none detected, a current transcript beside 2, 250 or 600 quoted turns of the old format is held: no call, every fact and row kept, --force too, never a failed page, and doctor lists it with each format\'s count instead of a spend cap', async () => {
const brain = opts.getBrain();
- const slug = `notes/format-change-${randomUUID().slice(0, 8)}`;
- await twoGrammars(brain, slug, 2);
- const { calls, result } = await extract(brain.engine, slug);
- const rows = await derivations(brain.engine, slug);
- expect({ calls: calls.length, turns: turnsIn(calls), failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, processed: result.pages_processed,
- facts: (await factsOf(brain.engine, slug)).length, grammars: await recordedGrammars(brain, slug), mismatches: await claimMismatches(brain.engine, slug), states: [...new Set(rows.states)] })
- .toEqual({ calls: rows.keys.length, turns: 200, failed: 0, nonExtractable: 0, processed: 1, facts: rows.keys.length, grammars: ['plain-role-no-time'], mismatches: [], states: ['done'] });
+ const out: Record<number, unknown> = {};
+ const expected: Record<number, unknown> = {};
+ for (const quotes of [2, 250, 600]) {
+ const slug = `notes/mixed-format-${quotes}-${randomUUID().slice(0, 8)}`;
+ await mixedFormats(brain, slug, quotes);
+ const facts = (await factsOf(brain.engine, slug)).map(f => f.id);
+ const rows = await rowState(brain, slug);
+ const runs = [];
+ for (const force of [false, true]) {
+ const { calls, result } = await extract(brain.engine, slug, { force });
+ runs.push({ calls: calls.length, failed: result.pages_failed, held: result.pages_detection_ambiguous ?? 0, facts: (await factsOf(brain.engine, slug)).map(f => f.id), rows: await rowState(brain, slug) });
+ }
+ const doctor = await heldPages(brain);
+ out[quotes] = { runs, status: doctor.status, listed: doctor.samples.find(s => s.page === `default:${slug}`)?.grammars, truncated: doctor.truncated.includes(slug), fix: doctor.fix?.includes('--grammar') };
+ const run = { calls: 0, failed: 0, held: 1, facts, rows };
+ expected[quotes] = { runs: [run, run], status: 'warn', listed: { 'plain-role-no-time': 200, 'bold-name-no-time': quotes }, truncated: false, fix: true };
+ }
+ expect(out).toEqual(expected);
}, 600_000);
- test('G1: while another recorded grammar parses half as many messages or more, the page fails with every fact and row kept, --force too; once an edit leaves one grammar dominant it settles under it', async () => {
+ test('p7: two transcripts inside prose on a page with no recorded format, whose facts the whole-page extractor left, are held, not collected as a page that is no transcript', async () => {
const brain = opts.getBrain();
- const slug = `notes/format-mix-${randomUUID().slice(0, 8)}`;
- const { prose, current } = await twoGrammars(brain, slug, 150);
+ const slug = `notes/two-formats-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ const plain = Array.from({ length: 100 }, (_, i) => `${i % 2 ? 'Assistant' : 'User'}: plain turn ${i} ${'present '.repeat(700)}`).join('\n');
+ const bold = Array.from({ length: 100 }, (_, i) => `**${i % 2 ? 'Bob Example' : 'Alice Example'}:** bold turn ${i} ${'legacy '.repeat(700)}`).join('\n');
+ await brain.seed(slug, chatPage('Two formats', plain));
+ await extract(brain.engine, slug);
+ await brain.seed(slug, chatPage('Two formats', bold));
+ await extract(brain.engine, slug);
const facts = (await factsOf(brain.engine, slug)).map(f => f.id);
- const rows = JSON.stringify((await derivations(brain.engine, slug)).rows.map(row => [row.occurrenceId, row.output, row.state]));
+ expect({ facts: facts.length >= 100, rows: (await derivations(brain.engine, slug)).rows.length }).toEqual({ facts: true, rows: 0 });
+ const prose = Array.from({ length: 12_000 }, (_, i) => `Paragraph ${i} with unrelated reference material.`).join('\n');
+ await brain.seed(slug, chatPage('Two formats merged', `${prose}\n${plain}\n\n${bold}`));
+ expect({ undetected: await undetected(brain, slug), storage: (await brain.body(slug)).storage }).toEqual({ undetected: null, storage: 'segmented' });
+ const runs = [];
+ for (const force of [false, false, true]) {
+ const { calls, result } = await extract(brain.engine, slug, { force });
+ runs.push({ calls: calls.length, failed: result.pages_failed, held: result.pages_detection_ambiguous ?? 0, nonExtractable: result.pages_marked_non_extractable, facts: (await factsOf(brain.engine, slug)).map(f => f.id) });
+ }
+ const run = { calls: 0, failed: 0, held: 1, nonExtractable: 0, facts };
+ expect({ runs, listed: (await heldPages(brain)).samples.find(s => s.page === `default:${slug}`)?.grammars })
+ .toEqual({ runs: [run, run, run], listed: { 'plain-role-no-time': 100, 'bold-name-no-time': 100 } });
+ }, 600_000);
+
+ test('--grammar on a held page: --dry-run previews what a run under the format extracts and removes and changes nothing; the run does exactly that, later plain runs follow the choice until the page changes, and none settles a page as no transcript', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/operator-format-${randomUUID().slice(0, 8)}`;
+ const { prose, current, quoted } = await mixedFormats(brain, slug, 250);
+ expect((await extract(brain.engine, slug)).result.pages_detection_ambiguous).toBe(1);
+ 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 ids = (await factsOf(brain.engine, slug)).map(f => f.id);
+ const rows = await rowState(brain, slug);
+ const preview = await extract(brain.engine, slug, { grammar: 'plain-role-no-time', dryRun: true });
+ const p = preview.result.grammar_previews?.[0];
+ expect({ calls: preview.calls.length, grammar: p?.grammar, messages: p?.messages, extracts: (p?.windows_to_extract ?? 0) > 0, collects: (p?.facts_to_collect ?? 0) > 0,
+ facts: (await factsOf(brain.engine, slug)).map(f => f.id), rows: await rowState(brain, slug), receipt: await receipt() })
+ .toEqual({ calls: 0, grammar: 'plain-role-no-time', messages: 200, extracts: true, collects: true, facts: ids, rows, receipt: 'detection_ambiguous' });
+ const applied = await extract(brain.engine, slug, { grammar: 'plain-role-no-time' });
+ const after = await factsOf(brain.engine, slug);
+ const derived = await derivations(brain.engine, slug);
+ expect({ calls: applied.calls.length, turns: turnsIn(applied.calls), removed: ids.filter(id => !after.some(f => f.id === id)).length, failed: applied.result.pages_failed,
+ processed: applied.result.pages_processed, facts: after.length, grammars: await recordedGrammars(brain, slug), states: [...new Set(derived.states)],
+ mismatches: await claimMismatches(brain.engine, slug), receipt: await receipt() })
+ .toEqual({ calls: p!.windows_to_extract, turns: 200, removed: p!.facts_to_collect, failed: 0, processed: 1, facts: derived.keys.length, grammars: ['plain-role-no-time'],
+ states: ['done'], mismatches: [], receipt: 'grammar_chosen' });
+ const kept = after.map(f => f.id);
+ const plainRuns = [];
for (const force of [false, true]) {
const { calls, result } = await extract(brain.engine, slug, { force });
- expect({ force, calls: calls.length, failed: result.pages_failed, why: result.failed_pages[0]?.error.includes('recorded formats compete'), facts: (await factsOf(brain.engine, slug)).map(f => f.id),
- rows: JSON.stringify((await derivations(brain.engine, slug)).rows.map(row => [row.occurrenceId, row.output, row.state])) })
- .toEqual({ force, calls: 0, failed: 1, why: true, facts, rows });
+ plainRuns.push({ calls: calls.length, failed: result.pages_failed, held: result.pages_detection_ambiguous ?? 0, facts: (await factsOf(brain.engine, slug)).map(f => f.id) });
}
- await brain.seed(slug, chatPage('Format change, retitled', `${prose}\n${current}\n**Alice Example:** the one line still quoted from the old format.\n`));
- expect(await undetected(brain, slug)).toBeNull();
- const { calls, result } = await extract(brain.engine, slug);
- const after = await derivations(brain.engine, slug);
- expect({ turns: turnsIn(calls), failed: result.pages_failed, processed: result.pages_processed, facts: (await factsOf(brain.engine, slug)).length,
- grammars: await recordedGrammars(brain, slug), mismatches: await claimMismatches(brain.engine, slug), states: [...new Set(after.states)] })
- .toEqual({ turns: 200, failed: 0, processed: 1, facts: after.keys.length, grammars: ['plain-role-no-time'], mismatches: [], states: ['done'] });
+ await brain.seed(slug, chatPage('Combined transcript archive, edited', `${prose}\n${current}\n## Quoted historical transcript\n${quoted}`));
+ const changed = await extract(brain.engine, slug);
+ expect({ plainRuns, changed: { calls: changed.calls.length, held: changed.result.pages_detection_ambiguous ?? 0, facts: (await factsOf(brain.engine, slug)).map(f => f.id) } })
+ .toEqual({ plainRuns: [{ calls: 0, failed: 0, held: 0, facts: kept }, { calls: 0, failed: 0, held: 0, facts: kept }], changed: { calls: 0, held: 1, facts: kept } });
+ const 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 });
+ 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,
+ held: later.result.pages_detection_ambiguous ?? 0, facts: (await factsOf(brain.engine, slug)).length, receipt: await receipt() })
+ .toEqual({ calls: 0, nonExtractable: 1, failed: 0, held: 0, facts: 0, receipt: 'grammar_chosen' });
}, 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 () => {
@@ -331,7 +406,7 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap
expect(await undetected(brain, slug)).toBeNull();
out[shape] = { before: before > 100, runs: await lostGrammarRuns(brain, slug) };
}
- const collected = { calls: 0, failed: 0, nonExtractable: 1, facts: 0, windows: 0, mismatches: 0 };
+ const collected = { calls: 0, failed: 0, held: 0, nonExtractable: 1, facts: 0, windows: 0, mismatches: 0 };
const settled = { ...collected, nonExtractable: 0 };
expect(out).toEqual({ 'rows without a grammar': { before: true, runs: [collected, settled, collected] }, 'no rows': { before: true, runs: [collected, settled, collected] } });
}, 600_000);
diff --git a/test/helpers/conversation-facts-property-cases.ts b/test/helpers/conversation-facts-property-cases.ts
index fd5e5354d9..11288863b7 100644
--- a/test/helpers/conversation-facts-property-cases.ts
+++ b/test/helpers/conversation-facts-property-cases.ts
@@ -18,11 +18,11 @@
* Before a step, the page may also be rewritten to prose that keeps zero to three of its message lines, so no grammar
* is detected while it still holds facts, then restored; each of the two runs is checked like a step. Or it may be
* rewritten to another transcript format and run one window, so its rows record two grammars, then lose detection with
- * a few or about as many of its own message lines kept, then be restored: each run is checked like a step, and the lost
- * run also holds that competing grammars publish nothing and a settled page records the grammar parsing the most messages.
+ * a few or about as many of its own message lines kept, then be restored: each run is checked like a step. A lost run on
+ * a page some built-in format still parses a message in must be held: no call, no fact lost.
* Each step records which paths it exercised (a moved window, a window-specific failure, a window marked failed, a
- * settled collection, a --since run, a cap refusal, a lost grammar on a page holding facts, a lost grammar on a page
- * recording two grammars that one dominates or that compete); across the seeds every path must fire at least its floor. Each seed
+ * settled collection, a --since run, a cap refusal, a lost grammar on a page holding facts, a held page keeping quoted
+ * lines, a held page recording two grammars); across the seeds every path must fire at least its floor. Each seed
* also dooms the windows whose text hash starts with one chosen digit for a span of steps, so windows reach the failure
* limit and block collection until the final --force run.
* At the end a healthy unconstrained --force run leaves the same windows and facts as one extraction of the same page on
@@ -148,17 +148,31 @@ async function violations(engine: BrainEngine, slug: string, before: Fact[], o:
return { problems, after, fired };
}
-type PropertyPath = 'moved' | 'failed_window' | 'marked_failed' | 'collected' | 'since' | 'cap' | 'grammar_lost' | 'grammar_adopted' | 'grammar_refused';
+type PropertyPath = 'moved' | 'failed_window' | 'marked_failed' | 'collected' | 'since' | 'cap' | 'grammar_lost' | 'held_quoted' | 'held_two_grammars';
+
+/** Whether some built-in conversation format parses a message in the page's text `body`. */
+async function anyFormatParses(engine: BrainEngine, slug: string, body: string): Promise<boolean> {
+ const page = (await engine.getPage(slug, { sourceId: 'default' }))!;
+ return BUILTIN_PATTERNS.some(entry => applyPattern(body, entry, deriveDateContext({ page })).length > 0);
+}
+
+/** A run on a page with no detected format but a parseable message is held: it never calls and never loses a fact. */
+function heldOracle(checked: { problems: string[]; after: Fact[]; fired: Set<PropertyPath> }, before: Fact[], outcome: { calls: number; failed: number }, path: PropertyPath): void {
+ checked.fired.add(path);
+ if (outcome.calls !== 0 || outcome.failed !== 0 || checked.after.map(f => f.id).join() !== before.map(f => f.id).join()) {
+ checked.problems.push(`(held) a page with no detected format and a parseable message made ${outcome.calls} call(s), failed ${outcome.failed} or changed its facts (${before.length} -> ${checked.after.length})`);
+ }
+}
/**
* Steps, across every seed, that must exercise each path: the round-5 floors (about half of 193, 165, 46, 133, 28, 21),
- * half of the 24 steps that lose the grammar on a page holding facts, and half of the 12 lost runs on a page recording two
- * grammars where one dominates and of the 12 where they compete (the 30 seeds now exercise 201, 153, 37, 184, 30, 22,
- * 24, 12, 12).
+ * half of the 24 steps that lose the grammar on a page holding facts, and half of the 18 held runs on a page keeping
+ * quoted lines and of the 24 on a page recording two grammars (the 30 seeds now exercise 206, 153, 47, 153, 27, 23, 24,
+ * 18, 24).
*/
-export const PROPERTY_PATH_FLOORS: Record<PropertyPath, number> = { moved: 96, failed_window: 82, marked_failed: 23, collected: 66, since: 14, cap: 10, grammar_lost: 12, grammar_adopted: 6, grammar_refused: 6 };
+export const PROPERTY_PATH_FLOORS: Record<PropertyPath, number> = { moved: 96, failed_window: 82, marked_failed: 23, collected: 66, since: 14, cap: 10, grammar_lost: 12, held_quoted: 9, held_two_grammars: 12 };
export function defineConversationFactsPropertyCases(opts: { getBrain: () => AppendBrain; getFresh: () => AppendBrain }): void {
- const firedSteps: Record<PropertyPath, number> = { moved: 0, failed_window: 0, marked_failed: 0, collected: 0, since: 0, cap: 0, grammar_lost: 0, grammar_adopted: 0, grammar_refused: 0 };
+ const firedSteps: Record<PropertyPath, number> = { moved: 0, failed_window: 0, marked_failed: 0, collected: 0, since: 0, cap: 0, grammar_lost: 0, held_quoted: 0, held_two_grammars: 0 };
let seedsRun = 0;
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 () => {
@@ -189,11 +203,13 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
const detector = createPatternDetector();
detector.push((await brain.body(slug)).truth);
const lostGrammar = phase === 'lost' && detector.finish() === null && facts.length > 0;
+ const parseable = lostGrammar && await anyFormatParses(engine, slug, (await brain.body(slug)).truth);
const constraint = (['none', 'none', 'abort', 'limit'] as const)[Math.floor(lost() * 4)]!;
const o: RunOpts = constraint === 'abort' ? { abortAfter: 1 + Math.floor(lost() * 30) } : constraint === 'limit' ? { segmentLimit: 1 + Math.floor(lost() * 20) } : {};
const outcome = await run(engine, slug, o);
const checked = await violations(engine, slug, facts, o, outcome);
if (lostGrammar) checked.fired.add('grammar_lost');
+ if (parseable) heldOracle(checked, facts, outcome, 'held_quoted');
log.push(`step ${step} (grammar ${phase}, ${quoted.length} message line(s) kept): ${constraint} ${JSON.stringify(o)} -> ${JSON.stringify(outcome)}, ${checked.after.length} facts; ${[...checked.fired].join(' ') || 'no path'}`);
for (const path of checked.fired) firedSteps[path]++;
expect({ step, log: log.at(-1), problems: checked.problems.slice(0, 5) }).toEqual({ step, log: log.at(-1), problems: [] });
@@ -204,10 +220,9 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
const rival = rng(seed + 104_729);
/**
* Rewrite the page to a plain-role transcript and run one window of it, so the rows record two grammars; then put
- * prose before it and keep a few of the page's own message lines (the plain-role grammar dominates) or about as many
- * as it has turns (the two compete), so no grammar is detected, and run; then restore the page and run. Each run is
- * checked like a step, and the lost run also against G1: competing grammars publish nothing, a dominant one is the
- * grammar every row of a settled page records.
+ * prose before it and keep a few of the page's own message lines or about as many as it has turns, so no grammar is
+ * detected, and run; then restore the page and run. Each run is checked like a step, and the lost run also holds
+ * that a page with a parseable message and no detected format is held: no call, no fact lost.
*/
const rivalGrammar = async (step: number) => {
const truth = (await brain.body(slug)).truth;
@@ -226,27 +241,14 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
detector.push(body);
const grammars = [...new Set((await derivations(engine, slug)).rows.map(row => (row.output as { pattern?: string | null }).pattern).filter((p): p is string => !!p))];
const lostTwo = phase === 'lost' && detector.finish() === null && facts.length > 0 && grammars.length > 1;
- const page = (await engine.getPage(slug, { sourceId: 'default' }))!;
- const parsed = grammars.map(id => ({ id, messages: applyPattern(body, BUILTIN_PATTERNS.find(p => p.id === id)!, deriveDateContext({ page })).length })).sort((a, b) => b.messages - a.messages);
- const counts = parsed.map(p => p.messages).join(' vs ');
- const refused = lostTwo && parsed[0]!.messages > 0 && parsed[0]!.messages <= 2 * parsed[1]!.messages;
+ const parseable = lostTwo && await anyFormatParses(engine, slug, body);
const constraint = phase === 'recorded' ? 'limit' : (['none', 'none', 'abort', 'limit'] as const)[Math.floor(rival() * 4)]!;
const o: RunOpts = phase === 'recorded' ? { segmentLimit: 1 } : constraint === 'abort' ? { abortAfter: 1 + Math.floor(rival() * 30) }
: constraint === 'limit' ? { segmentLimit: 1 + Math.floor(rival() * 20) } : {};
const outcome = await run(engine, slug, o);
const checked = await violations(engine, slug, facts, o, outcome);
- if (refused) {
- checked.fired.add('grammar_refused');
- if (outcome.calls !== 0 || outcome.failed !== 1 || checked.after.map(f => f.id).join() !== facts.map(f => f.id).join()) checked.problems.push(`(G1) competing recorded grammars (${counts} messages) published or extracted`);
- } else if (lostTwo && parsed[0]!.messages > 0) {
- checked.fired.add('grammar_adopted');
- const best = parsed[0]!.id;
- const state = await pageState(engine, slug);
- const d = await derivations(engine, slug);
- const live = d.rows.filter(row => d.live.includes(row.occurrenceId)).map(row => (row.output as { pattern?: string | null }).pattern);
- if (state.settled && live.some(p => p !== best)) checked.problems.push(`(G1) the page settled under ${[...new Set(live)].join()} although ${best} parses the most messages (${counts})`);
- }
- log.push(`step ${step} (rival grammar ${phase}, ${count} plain-role turns, ${keep} own line(s) kept, recorded ${grammars.join('+') || 'none'} parsing ${counts || 'nothing'}): ${constraint} ${JSON.stringify(o)} -> ${JSON.stringify(outcome)}, ${checked.after.length} facts; ${[...checked.fired].join(' ') || 'no path'}`);
+ if (parseable) heldOracle(checked, facts, outcome, 'held_two_grammars');
+ log.push(`step ${step} (rival grammar ${phase}, ${count} plain-role turns, ${keep} own line(s) kept, recorded ${grammars.join('+') || 'none'}): ${constraint} ${JSON.stringify(o)} -> ${JSON.stringify(outcome)}, ${checked.after.length} facts; ${[...checked.fired].join(' ') || 'no path'}`);
for (const path of checked.fired) firedSteps[path]++;
expect({ step, log: log.at(-1), problems: checked.problems.slice(0, 5) }).toEqual({ step, log: log.at(-1), problems: [] });
facts = checked.after;