Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): preserve explicit caps on unpriced conversation models (#5825, #5823)
garrytanccfdf6e6bdd7
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex c92077aedc..5c7c84d90a 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.-- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip) + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then replace the prior extractor batch in one `replaceDerivedFactsForPage` transaction after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).+- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip) + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then replace the prior extractor batch in one `replaceDerivedFactsForPage` transaction after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs walk replaces each page's own markdown-derived links through `replacePageFileLinks` (the per-slug contract below; a file with no page row is skipped and not stamped); the db link walk and `extract --stale` replace through `replaceDerivedLinks`. Timeline rows are inserted in batches of 100 via `addTimelineEntriesBatch` (`ON CONFLICT DO NOTHING`; `created` counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, `--stale` — runs `retractRemovedTimelineEntries` for the page. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the non-event rows whose (date, source, summary) any stored `page_versions` text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, `--infer-dates` anchors) are kept, and the version scan only runs when the page holds a row the current text does not produce. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` (`pruneTimelineOrphans`) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-locked `withCoordinatedWrite` transaction; these rows are removals, so `gbrain repair timeline` / `timeline_history` exclude them; pinned in `test/persistence-managed-lifecycle.test.ts`); the read-only `timeline_orphans` doctor check (`src/commands/doctor/checks/timeline-orphans.ts`) samples 500 pages and points at it. Pinned by `test/timeline-reconcile-all-paths.test.ts`. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. `extractLinksForSlugs` reads the requested files first, then loads page metadata only for those pages and their link endpoints (`fileLinkOwnership(engine, sourceId, { slugs })`); the unscoped whole-brain load happens only when a DB meeting or attendance origin needs `replaceFileLinks`. Both return `ExtractForSlugsResult { created, processed, errors? }`; `errors` names pages whose read or write failed, and sync reports them as `extract_error` (stderr line plus the `SyncResult` field) instead of swallowing them. `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`; on a managed brain it hands the sweep to `extractManagedStaleLinks` in `src/core/persistence/links-maintenance.ts` for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through `src/commands/extract-stale-delegate.ts`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. On a managed-persistence brain each page publishes its derived links (`prepareAutomaticLinks`), the coordinator's unrecorded canonical timeline tuples (`unrecordedCanonicalTimeline`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`, `test/persistence-managed-lifecycle.test.ts`. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Fresh-install schema in `src/schema.sql` (both generated blobs follow via `bun run build:schema`) + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor/checks/extraction-sync.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; pages whose attendance marker (`links_attendance_blocked_revision`, migration v180) equals their current `knowledge_revision` are left out of the lag count and reported as `details.attendance_blocked` (both `extract --stale` sweeps set the marker on an unresolved-attendance skip; pre-v180 brains fall back to the unfiltered count); strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 5ed2a493a6..e5affb6688 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -17,7 +17,7 @@ src/commands/embed.ts embedAllStale 560 seed: W5 baseline, refactor wave 1 (decosrc/commands/embed.ts runEmbedCore 376 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/extract-conversation-facts.ts processPage 307 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/commands/extract-conversation-facts.ts runExtractConversationFactsCore 372 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState+src/commands/extract-conversation-facts.ts runExtractConversationFactsCore 376 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState; +4 #5823: shared default-cap wiring and structured budget reason/model; decision logic is in facts/conversation-budget.tssrc/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/import.ts runImport 959 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bcb40929f4..45c5cb3d83 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -7,7 +7,7 @@ src/cli.ts 3202 ratchet +2 fix wave 5 (#5401): projections drain help line and tsrc/commands/autopilot.ts 1637 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 + auditsrc/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2190 ratchet 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-src/commands/extract-conversation-facts.ts 2146 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)+src/commands/extract-conversation-facts.ts 2164 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.tssrc/commands/extract.ts 2623 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference)src/commands/jobs.ts 658 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)src/commands/serve-http.ts 915 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.tsdiff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 0cce5cda29..0e4f6b1ce6 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -75,7 +75,8 @@ import {import { configureGatewayIfUninitialized, isAvailable, withBudgetTracker } from '../core/ai/gateway.ts';import { managedDerivedFactsPreflight, replaceDerivedFactsForPage, writeDerivedFacts } from '../core/persistence/derived-facts.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';-import { BudgetTracker, BudgetExhausted, loadPricingOverrides } from '../core/budget/budget-tracker.ts';+import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason } from '../core/budget/budget-tracker.ts';+import { conversationFactsCostCap } from '../core/facts/conversation-budget.ts';import { listSources } from '../core/sources-ops.ts';import {loadOpCheckpoint,@@ -383,6 +384,8 @@ export interface ExtractConversationFactsResult {/** Entity values kept raw after a best-effort resolution failure. */resolution_errors: number;budget_exhausted?: boolean;+ budget_reason?: BudgetReason;+ budget_model?: string;spent_usd?: number;}@@ -1615,10 +1618,11 @@ export async function runExtractConversationFactsCore(// tracker per gateway.ts AsyncLocalStorage semantics).await body();} else {+ const pricingOverrides = await loadPricingOverrides(engine);const tracker = new BudgetTracker({- maxCostUsd: opts.maxCostUsd ?? DEFAULT_MAX_COST_USD,+ maxCostUsd: await conversationFactsCostCap(engine, opts.maxCostUsd ?? DEFAULT_MAX_COST_USD, opts.maxCostUsd !== undefined, pricingOverrides),label: `extract-conversation-facts:${sourceId}`,- pricingOverrides: await loadPricingOverrides(engine),+ pricingOverrides,});ownedTracker = tracker;try {@@ -1630,6 +1634,8 @@ export async function runExtractConversationFactsCore(} catch (err) {if (err instanceof BudgetExhausted) {result.budget_exhausted = true;+ result.budget_reason = err.reason;+ result.budget_model = err.modelId;if (opts.budgetTracker) {result.spent_usd = opts.budgetTracker.totalSpent;}@@ -1655,6 +1661,7 @@ export async function runExtractConversationFactsCore(effectiveTracker.totalSpent > effectiveTracker.cap) {result.budget_exhausted = true;+ result.budget_reason = 'cost';result.spent_usd = effectiveTracker.totalSpent;}@@ -1740,7 +1747,7 @@ async function writeRunReceiptAndRollup(cost_delta: result.spent_usd ?? 0,...classifyRunStop({budget_exhausted: halted,- error: result.pages_failed > 0,+ error: result.pages_failed > 0 || result.budget_reason === 'no_pricing',}),});}@@ -1833,8 +1840,12 @@ function parseArgs(args: string[]): ParsedArgs {continue;}if (a === '--max-cost-usd') {- const n = parseFloat(args[++i] ?? '');- if (Number.isFinite(n) && n > 0) out.maxCostUsd = n;+ const n = Number(args[++i]);+ if (!Number.isFinite(n) || n <= 0) {+ out.error = '--max-cost-usd requires a positive finite number.';+ return out;+ }+ out.maxCostUsd = n;continue;}if (a === '--workers' || a === '--concurrency') {@@ -1900,6 +1911,8 @@ Multi-source: when --source-id is omitted, the command iterates ALLsources from gbrain sources list. Per-source budget cap defaults to--max-cost-usd; the brain-wide cap when running via the autopilot cyclephase is cycle.conversation_facts_backfill.max_total_cost_usd.+Default USD caps are not enforced for unpriced chat models (a warning is emitted).+Explicit caps remain fail-closed; configure pricing.overrides to supply missing prices.Resumability: per-page completion is durable via a terminal audit rowin the facts table (source='${TERMINAL_AUDIT_SOURCE}'). gbrain doctor's@@ -1908,6 +1921,7 @@ conversation_facts_backlog check counts pages without this row.function buildJobParams(args: string[]): Record<string, unknown> {const parsed = parseArgs(args);+ if (parsed.error) throw new Error(parsed.error);return {sourceId: parsed.sourceId,types: parsed.types,@@ -1995,6 +2009,7 @@ export async function runExtractConversationFacts(};let totalSpent = 0;let anyBudgetExhausted = false;+ const unpricedModels = new Set<string>();const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));@@ -2045,6 +2060,7 @@ export async function runExtractConversationFacts(aggregate.fallback_slugify_count += perSource.fallback_slugify_count;aggregate.resolution_errors += perSource.resolution_errors;if (perSource.budget_exhausted) anyBudgetExhausted = true;+ if (perSource.budget_reason === 'no_pricing') unpricedModels.add(perSource.budget_model ?? 'unknown model');if (perSource.spent_usd) totalSpent += perSource.spent_usd;progress.tick(1, `${sourceId}: ${perSource.facts_inserted} facts inserted`);@@ -2103,7 +2119,9 @@ export async function runExtractConversationFacts(console.log(` Preserved ${aggregate.resolution_errors} fact(s) without an entity target after best-effort resolution errors.`);}if (anyBudgetExhausted) {- console.log(` Budget cap reached. Re-run with a higher --max-cost-usd to continue.`);+ console.log(unpricedModels.size > 0+ ? ` no_pricing: ${[...unpricedModels].join(', ')}. Configure pricing.overrides; raising --max-cost-usd cannot resolve missing pricing.`+ : ` Budget cap reached. Re-run with a higher --max-cost-usd to continue.`);}// v0.41.15.0 (codex #3): exit 3 when pages were skipped due to@@ -2112,7 +2130,7 @@ export async function runExtractConversationFacts(// anyBudgetExhausted doesn't trigger exit 3; the budget message// above already tells the user what to do, and exit 0 is the right// signal for "ran to the cap intentionally."- if (aggregate.pages_failed > 0) {+ if (aggregate.pages_failed > 0 || unpricedModels.size > 0) {process.exit(1);}if (aggregate.pages_lock_skipped > 0 && !anyBudgetExhausted) {diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.tsindex 7765504596..b9f6266b2c 100644--- a/src/core/cycle/conversation-facts-backfill.ts+++ b/src/core/cycle/conversation-facts-backfill.ts@@ -59,6 +59,7 @@ import {// binding extract-conversation-facts.ts re-exports) so this phase is part of// the drift-guarded set in test/conversation-facts-type-allowlist-drift.test.ts.import { ALLOWED_TYPES, type AllowedType } from '../facts/conversation-types.ts';+import { conversationFactsCostCap } from '../facts/conversation-budget.ts';/** Per-phase wrapper opts. */export interface ConversationFactsBackfillPhaseOpts {@@ -89,6 +90,7 @@ interface ResolvedConfig {enabled: boolean;maxCostUsd: number; // per source per cyclemaxTotalCostUsd: number; // brain-wide per cycle+ explicitCostCap: boolean;maxWalltimeMin: number; // per source per cyclemaxTotalWalltimeMin: number; // brain-wide per cycletypes: AllowedType[];@@ -156,6 +158,7 @@ async function loadCfg(engine: BrainEngine): Promise<ResolvedConfig> {enabled: enabledFlag,maxCostUsd: parseFloatOrDefault(maxCost, 1.0),maxTotalCostUsd: parseFloatOrDefault(maxTotalCost, 5.0),+ explicitCostCap: maxCost !== null || maxTotalCost !== null,maxWalltimeMin: parseFloatOrDefault(maxWall, 20),maxTotalWalltimeMin: parseFloatOrDefault(maxTotalWall, 30),types,@@ -191,6 +194,7 @@ export async function runPhaseConversationFactsBackfill(}const startedAt = Date.now();+ const costCap = await conversationFactsCostCap(engine, cfg.maxTotalCostUsd, cfg.explicitCostCap, pricingOverrides);const maxTotalWalltimeMs = cfg.maxTotalWalltimeMin * 60_000;const maxWalltimeMs = cfg.maxWalltimeMin * 60_000;@@ -265,14 +269,14 @@ export async function runPhaseConversationFactsBackfill(}// Brain-wide cost check (sum of per-source tracker spends).- const remainingCostUsd = cfg.maxTotalCostUsd - totalSpent;+ const remainingCostUsd = costCap === undefined ? Infinity : costCap - totalSpent;if (remainingCostUsd <= 0) {skippedByBrainWideCap = sources.length - i;break;}const perSourceWallMs = Math.min(maxWalltimeMs, remainingWallMs);- const perSourceCapUsd = Math.min(cfg.maxCostUsd, remainingCostUsd);+ const perSourceCapUsd = costCap === undefined ? undefined : Math.min(cfg.maxCostUsd, remainingCostUsd);const tracker = new BudgetTracker({maxCostUsd: perSourceCapUsd,maxRuntimeMs: perSourceWallMs,@@ -331,6 +335,8 @@ export async function runPhaseConversationFactsBackfill(perSourceResults[src.id] = {...zeroResult(),budget_exhausted: true,+ budget_reason: err.reason,+ budget_model: err.modelId,error: err.message,};} else if (isAbortError(err)) {@@ -407,7 +413,7 @@ export async function runPhaseConversationFactsBackfill(}const anyError = Object.values(perSourceResults).some(- (r) => r.error || r.pages_failed > 0,+ (r) => r.error || r.pages_failed > 0 || r.budget_reason === 'no_pricing',);const status = anyError ? 'warn' : 'ok';const summary = `${totals.facts_inserted} facts inserted across ${totals.sources_processed}/${sources.length} sources, ~$${totalSpent.toFixed(4)} spent`;@@ -442,6 +448,7 @@ export async function runPhaseConversationFactsBackfill(sources_walltime_exhausted: sourcesWalltimeExhausted,types: cfg.types,max_cost_usd: cfg.maxCostUsd,+ cost_cap_enforced: costCap !== undefined,max_walltime_min: cfg.maxWalltimeMin,max_total_cost_usd: cfg.maxTotalCostUsd,max_total_walltime_min: cfg.maxTotalWalltimeMin,diff --git a/src/core/facts/conversation-budget.ts b/src/core/facts/conversation-budget.tsnew file mode 100644index 0000000000..a390b3a00d--- /dev/null+++ b/src/core/facts/conversation-budget.ts@@ -0,0 +1,27 @@+import type { BrainEngine } from '../engine.ts';+import { getFactsExtractionModel } from './extract.ts';+import { resolveModel, resolveTierDefault } from '../model-config.ts';+import { normalizeModelId } from '../model-id.ts';+import { isModelPriceable, type PricingOverrides } from '../budget/budget-tracker.ts';++/** Default USD ceilings cannot account for unpriced chat routes. Explicit+ * ceilings stay fail-closed, including either of the cycle's two cost caps.+ * Check the opt-in parser too: it bills under the same extraction tracker.+ * Runtime and page/segment bounds belong to the caller and are never lifted.+ */+export async function conversationFactsCostCap(+ engine: BrainEngine,+ cap: number,+ explicit: boolean,+ overrides?: PricingOverrides,+): Promise<number | undefined> {+ if (explicit) return cap;+ const models = [await getFactsExtractionModel(engine)];+ if (await engine.getConfig('conversation_parser.llm_fallback_enabled') === 'true') {+ models.push(normalizeModelId(await resolveModel(engine, { tier: 'utility', fallback: resolveTierDefault('utility') })));+ }+ const unpriced = models.find(model => !isModelPriceable(model, 'chat', overrides));+ if (!unpriced) return cap;+ console.error(`[conversation-facts] ${unpriced} has no pricing; default USD cap is not enforced. Configure pricing.overrides to enforce a USD cap; explicit caps remain fail-closed.`);+ return undefined;+}diff --git a/src/core/transcripts/ingest-facts.ts b/src/core/transcripts/ingest-facts.tsindex 51a8f997ce..2c29bbd0a9 100644--- a/src/core/transcripts/ingest-facts.ts+++ b/src/core/transcripts/ingest-facts.ts@@ -19,6 +19,7 @@ import type { BrainEngine } from '../engine.ts';import { isFactsExtractionEnabled } from '../facts/extract.ts';import { BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';import { withBudgetTracker } from '../ai/gateway.ts';+import { conversationFactsCostCap } from '../facts/conversation-budget.ts';import {DEFAULT_MAX_COST_USD,runExtractConversationFactsCore,@@ -44,10 +45,11 @@ export async function runIngestFacts(return { pages: 0, skippedDisabled: true };}+ const pricingOverrides = await loadPricingOverrides(engine);const tracker = new BudgetTracker({- maxCostUsd: opts.maxCostUsd ?? DEFAULT_MAX_COST_USD,+ maxCostUsd: await conversationFactsCostCap(engine, opts.maxCostUsd ?? DEFAULT_MAX_COST_USD, opts.maxCostUsd !== undefined, pricingOverrides),label: 'transcripts-ingest-facts',- pricingOverrides: await loadPricingOverrides(engine),+ pricingOverrides,});await withBudgetTracker(tracker, () =>runExtractConversationFactsCore(engine, {diff --git a/test/conversation-facts-pricing-wiring.test.ts b/test/conversation-facts-pricing-wiring.test.tsindex 66780e0d4b..70fa88d594 100644--- a/test/conversation-facts-pricing-wiring.test.ts+++ b/test/conversation-facts-pricing-wiring.test.ts@@ -120,6 +120,63 @@ beforeEach(async () => {});describe('Conversation Facts pricing override wiring', () => {+ // Default-cap regressions execute the real core/cycle and gateway reservation+ // boundary. Existing cases only covered explicit caps WITH a price override.+ // No new production seam: reuse the synthetic transport and isolated engine.+ test('an unpriced extraction model can run under a default core budget', async () => {+ await engine.setConfig('pricing.overrides', '{}');+ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default', slug: SLUG, sleepMs: 0,+ });+ expect(result.budget_exhausted).not.toBe(true);+ expect(chatCalls).toBeGreaterThan(0);+ expect(await terminalCount()).toBe(1);+ });++ test('an explicit core cap fails closed with a no_pricing diagnostic, not an expected spend limit', async () => {+ await engine.setConfig('pricing.overrides', '{}');+ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default', slug: SLUG, maxCostUsd: 0.1, sleepMs: 0,+ });+ expect(result).toMatchObject({ budget_exhausted: true, budget_reason: 'no_pricing', budget_model: MODEL, spent_usd: 0 });+ expect(chatCalls).toBe(0);+ expect(await terminalCount()).toBe(0);+ const [rollup] = await engine.executeRaw<{ halt_count: number; expected_limit_count: number }>(+ "SELECT halt_count, expected_limit_count FROM extract_rollup_7d WHERE kind='facts.conversation' AND source_id='default'",+ );+ expect(Number(rollup.halt_count)).toBe(1);+ expect(Number(rollup.expected_limit_count)).toBe(0);+ });++ test('cycle defaults allow an unpriced model while retaining per-source runtime limits', async () => {+ await engine.setConfig('pricing.overrides', '{}');+ await engine.unsetConfig('cycle.conversation_facts_backfill.max_cost_usd');+ await engine.unsetConfig('cycle.conversation_facts_backfill.max_total_cost_usd');+ const result = await runPhaseConversationFactsBackfill(engine, {});+ expect(result.details.sources_budget_exhausted).toBe(0);+ expect(chatCalls).toBeGreaterThan(0);+ expect(await terminalCount()).toBe(1);+ });++ test.each(['max_cost_usd', 'max_total_cost_usd'])('cycle explicit %s remains fail-closed without pricing', async key => {+ await engine.setConfig('pricing.overrides', '{}');+ await engine.unsetConfig('cycle.conversation_facts_backfill.max_cost_usd');+ await engine.unsetConfig('cycle.conversation_facts_backfill.max_total_cost_usd');+ await engine.setConfig(`cycle.conversation_facts_backfill.${key}`, '0.1');+ const result = await runPhaseConversationFactsBackfill(engine, {});+ expect(result.status).toBe('warn');+ expect(result.details.per_source).toMatchObject({ default: { budget_reason: 'no_pricing', budget_model: MODEL } });+ expect(chatCalls).toBe(0);+ expect(await terminalCount()).toBe(0);+ });++ test('transcript facts default does not strand an unpriced model', async () => {+ await engine.setConfig('pricing.overrides', '{}');+ await runIngestFacts(engine, { sourceId: 'default', slugs: [SLUG], quiet: true });+ expect(chatCalls).toBeGreaterThan(0);+ expect(await terminalCount()).toBe(1);+ });+test('the documented config key is accepted by the strict config registry', () => {expect(KNOWN_CONFIG_KEYS).toContain('pricing.overrides');});diff --git a/test/extract-conversation-facts-diagnostics.serial.test.ts b/test/extract-conversation-facts-diagnostics.serial.test.tsindex 16107f1d39..3f4742349f 100644--- a/test/extract-conversation-facts-diagnostics.serial.test.ts+++ b/test/extract-conversation-facts-diagnostics.serial.test.ts@@ -53,6 +53,7 @@ beforeEach(async () => {await engine.executeRaw('TRUNCATE facts, pages, op_checkpoints, extract_rollup_7d CASCADE');await engine.executeRaw('DELETE FROM gbrain_cycle_locks');await engine.setConfig('facts.extraction_enabled', 'true');+ await engine.setConfig('facts.extraction_model', 'anthropic:claude-sonnet-4-6');await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');await engine.setConfig('cycle.conversation_facts_backfill.workers', '3');@@ -72,6 +73,39 @@ beforeEach(async () => {});describe('#5364 diagnostics across workers, sources, CLI, and cycle', () => {+ // #5823: execute CLI diagnostics and parsing, not source-text assertions.+ test('explicit unpriced cap names pricing recovery rather than recommending a larger cap', async () => {+ await engine.setConfig('facts.extraction_model', 'anthropic:synthetic-unpriced-model');+ const log = spyOn(console, 'log').mockImplementation(() => {});+ const exit = spyOn(process, 'exit').mockImplementation(((code: number) => { throw new Error(`exit:${code}`); }) as never);+ try {+ await expect(runExtractConversationFacts(engine, ['--source-id', 'speaker-a', '--max-cost-usd', '0.1', '--sleep', '0'])).rejects.toThrow('exit:1');+ const summary = log.mock.calls.map(call => call.join(' ')).join('\n');+ expect(summary).toContain('no_pricing: anthropic:synthetic-unpriced-model');+ expect(summary).toContain('pricing.overrides');+ expect(summary).not.toContain('Re-run with a higher --max-cost-usd');+ expect(calls).toBe(0);+ } finally {+ exit.mockRestore();+ log.mockRestore();+ }+ });++ test.each(['0', '-1', 'invalid', '1junk', 'Infinity', undefined])('invalid explicit cap %s is rejected before extraction or background submission', async value => {+ const error = spyOn(console, 'error').mockImplementation(() => {});+ const exit = spyOn(process, 'exit').mockImplementation(((code: number) => { throw new Error(`exit:${code}`); }) as never);+ const args = ['--source-id', 'speaker-a', '--max-cost-usd', ...(value === undefined ? [] : [value])];+ try {+ await expect(runExtractConversationFacts(engine, args)).rejects.toThrow('exit:1');+ await expect(runExtractConversationFacts(engine, ['--background', ...args])).rejects.toThrow('--max-cost-usd requires a positive finite number');+ expect(error.mock.calls[0]?.[0]).toContain('--max-cost-usd requires a positive finite number');+ expect(calls).toBe(0);+ } finally {+ exit.mockRestore();+ error.mockRestore();+ }+ });+test('dry-run help promises segmentation without model calls', async () => {const log = spyOn(console, 'log').mockImplementation(() => {});try {