Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(receipts): Decision 8 doctor count, publisher module, inventories, docs and managed publication tests

time-attackcce0cb2cb60f
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 96faef59f1..3f53657dcd 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -6,7 +6,8 @@ src/core/persistence/links-maintenance.ts 1 coordinator Managed extract --stale
src/core/extract-takes-from-pages.ts 0 coordinator Managed bootstrap submits one revision-checked put_page per source page so its complete takes fence and projected rows commit together; unmanaged writes retain the md-first helper.
src/core/persistence/takes-prepare.ts 4 coordinator Semantic takes apply only through the journal publication callback after current revision, holder and authority validation. takes_remove deletes the removed row inside the same coordinated apply (#5167).
src/commands/extract-timeline-db.ts 2 coordinator `gbrain extract timeline --source db` (#5904): on a managed brain the timeline retraction and insert run only inside the managed_maintenance_timeline_extract publication (prepareTimelineExtract; owner-checked by maintenancePreflight, page key locked, revision-bound); only an unmanaged brain retracts and batch-inserts directly, where no canonical writer enforcement applies.
-src/commands/extract-conversation-facts.ts 4 coordinator On a managed brain the conversation fact rows and audit rows are database-only derived rows buffered per page and published through replaceDerivedFactsForPage, which deletes the prior extractor batch and inserts the replacement in one withCoordinatedWrite transaction under the page key after revalidating source activity, page identity, revision and parser-input snapshot; a local-writer preflight runs before provider work. Unmanaged calls keep their direct engine writes behind the SQL guard.
+src/commands/extract-conversation-facts.ts 4 coordinator On a managed brain each page's fact rows and outcome row are frozen into one database-only managed_maintenance_conversation_facts request (facts/conversation-publication.ts) after a maintenance preflight before provider work; the coordinator's preparer revalidates page identity, revision and parser-input snapshot under the page key. Unmanaged calls keep their direct engine writes behind the SQL guard (writeDerivedFacts refuses on a managed brain).
+src/core/facts/conversation-publication.ts 2 coordinator The managed conversation-facts preparer deletes the page's extractor rows and inserts the frozen batch inside the coordinator publication of its admitted managed_maintenance_conversation_facts request, after rechecking authority, page identity, revision, version token and embedding signature under the page key; a lost insert rolls the publication back.
src/commands/extract.ts 7 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. On a managed brain extract --stale inserts only the canonical timeline tuples inside withCoordinatedWrite for that page, after the revision-bound derived-link replacement locked and verified the page revision in the same transaction.
src/commands/frontmatter.ts 0 filesystem_guard Batch frontmatter repair preflights every target before the first backup/write.
src/commands/import.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
@@ -39,9 +40,9 @@ src/core/company-brain/profile.ts 2 engine_guard Company-profile legacy deletes
src/core/company-brain/runtime.ts 1 projection Only source policy metadata advances under the company-source lock and brain/source row locks; the same transaction validates immutable approval and creates a receipt with source-incarnation and managed owner/topology fences, without source-file writes.
src/core/cycle/drift.ts 1 coordinator A managed brain preflights maintenance authority before judge spend and publishes the report through publishMaintenancePage; the unmanaged putPage stays behind the canonical table trigger.
src/core/cycle/extract-atoms.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
-src/core/cycle/extract-facts.ts 7 coordinator Managed and unmanaged reconciliation key rows by fence row number under the page lock, update matched rows in place, expire and detach removed rows instead of deleting them, and expire fence-owned rows of soft-deleted pages; on a managed brain each page transaction and the deleted-page expiry run inside withCoordinatedWrite (page key locked, body rechecked) after a local-writer preflight before any embedding call; the managed deleted-page expiry locks each candidate page key and rechecks its deletion before expiring its rows.
+src/core/cycle/extract-facts.ts 7 coordinator Managed and unmanaged reconciliation key rows by fence row number, update matched rows in place, expire and detach removed rows instead of deleting them, and expire fence-owned rows of soft-deleted pages; on a managed brain each changed page publishes a managed_maintenance_fence_facts request and each soft-deleted page a managed_maintenance_deleted_page_facts_expire request, whose preparers replan or recheck the deletion under the page key inside the coordinator publication.
src/core/cycle/extract-atoms-page-state.ts 1 engine_guard Atom completion updates and cardinality checks share one transaction; managed canonical SQL remains fenced and scan/failure bookkeeping is stored separately.
-src/core/cycle/extract-takes.ts 5 coordinator On a managed brain the DB-source walk publishes each fenced page's takes inside a withCoordinatedWrite transaction for the page's own source under the page lock, re-reading the page there and writing the canonical projection's superseded_by while leaving resolution columns untouched; the file walk and unmanaged brains keep direct SQL, which the trigger refuses on managed brains. Stale-row pruning deletes only takes whose rows left a cleanly parsed fence on a live page in the same source.
+src/core/cycle/extract-takes.ts 4 coordinator On a managed brain the DB-source walk publishes each fenced page that needs a change as a managed_maintenance_takes_reextract request whose preparer re-reads the page under its key and writes the canonical projection's superseded_by while leaving resolution columns untouched; the file walk and unmanaged brains keep direct SQL, which the trigger refuses on managed brains. Stale-row pruning deletes only takes whose rows left a cleanly parsed fence on a live page in the same source.
src/core/cycle/grade-takes.ts 1 coordinator A managed brain applies auto-resolutions through the coordinated takes_resolve page mutation; the unmanaged resolveTake stays behind the canonical table trigger.
src/core/cycle/patterns.ts 1 coordinator Managed local patterns use admitted page operations and validate canonical outputs; the legacy reverse-file path runs only unmanaged. Quote grounding writes verified pattern pages back through publishMaintenancePage (revision-checked) on a managed brain; the unmanaged importFromContent write-back stays behind the canonical table trigger.
src/core/cycle/phantom-redirect.ts 3 coordinator Managed brains route the redirect to phantom-redirect-managed.ts (canonical merge and phantom delete as coordinated maintenance requests whose publication moves the rows); the legacy file-first path runs only unmanaged and its canonical SQL stays trigger-guarded.
@@ -186,7 +187,6 @@ src/commands/quarantine.ts 2 early_refusal Legacy direct content import. Direct
src/commands/reindex.ts 1 early_refusal Legacy direct content import. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).
src/eval/brainbench/metrics/write-back.ts 1 isolated_eval Explicit isolated evaluation database only; never opened against the active managed brain.
src/eval/longmemeval/diagnostics.ts 1 isolated_eval Explicit isolated evaluation database only; never opened against the active managed brain.
-src/core/persistence/derived-facts.ts 2 coordinator Managed derived-fact batch replacement deletes the page's prior rows for one writer prefix and inserts the replacement inside withDerivedFactsWrite (source capability, shared source lock, page key) only after the caller's current-page recheck passes.
src/core/persistence/effects.ts 1 coordinator The embedding effect clears only the page embedding signature, inside its claimed, source-guarded installation transaction, when #4616 refused a chunk, so embed --stale finds the page; no canonical content column changes.
src/core/schema-migrations/v002-slugify-existing-pages.ts 2 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.
src/core/schema-migrations/v009-timeline-dedup-index.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.
@@ -212,4 +212,4 @@ src/core/sync-upstream.ts 1 engine_guard `recordUpstreamObservation` (#5255/#517
src/core/persistence/mirror-read-only.ts 1 coordinator classifyMirrorPage stamps pages.database_only_reason=mirror_read_only only inside the coordinator publication transaction of a page write that published no file into a read-only mirror source (#5409), as classifyUnboundPage does for unbound sources.
src/core/persistence/worktree-refresh.ts 1 coordinator `gbrain sources refresh` (F0) is the one sanctioned managed Git writer: it fast-forwards the checkout only under the worktree native lock after admission refused and claims stopped every checkout write (`fenced`), then updates only sources.upstream_checked_at/upstream_commit/upstream_behind in the merged bookkeeping transaction; pages and the checkpoint advance through the ordinary managed --no-pull sync.
src/core/facts/unfenced-facts.ts 3 coordinator The extract_facts cycle phase and the v0.32.2 migration fence row_num-NULL facts onto their entity pages. On a managed brain the fence publishes through a coordinated maintenance request; an unmanaged brain writes the page file under the source filesystem and page locks, then mirrors the body and stamps row numbers in one maintenanceTransaction.
-src/core/repair/take-supersession.ts 1 coordinator gbrain repair take-supersession reprojects superseded_by for a page whose fence is already right: inside withCoordinatedWrite under the page key on a managed brain (revision-checked), maintenanceTransaction on an unmanaged one. Fence edits go through a revision-bound put_page request.
+src/core/repair/take-supersession.ts 1 coordinator gbrain repair take-supersession reprojects superseded_by for a page whose fence is already right: a managed_maintenance_take_reproject request replanned under the page key on a managed brain, maintenanceTransaction (revision-checked) on an unmanaged one. Fence edits go through a revision-bound put_page request.
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index c77071dbfe..d79bce3d45 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -14,6 +14,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.
- `src/commands/doctor/checks/revision-backfill.ts` — `revision_backfill` (#5216, META, registered before `search_mode`): reads `readRevisionBackfillStatus` (column state, pages still without `knowledge_revision`, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count and `gbrain apply-migrations --force-schema` as `fix` while any row is resumable (or only the NOT NULL step remains); failed rows are listed by page id, `source:slug`, attempt and error, and when only rows with spent attempts remain the `fix` is the read-only `gbrain repair orphan-children` preview. Tests: `test/doctor-revision-backfill.test.ts`.
- `src/commands/doctor/checks/extractor-facts.ts` — `extractor_facts_expired` (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyExtractorFacts`, and names `gbrain repair extractor-facts` (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.
+- `src/commands/doctor/checks/conversation-outcomes.ts` — `conversation_outcomes_stale` (wave check, host-only, resolution `operator`): counts active conversation extraction outcomes stamped with an older `extractor_version` than `CONVERSATION_EXTRACTOR_VERSION` (outcomes are never reopened automatically) and names the `--force --dry-run` re-extract preview; outcomes older than the stamp are counted as `unstamped` and never warn. Bounded scan of the extractor rows, capped at 5000 (reported as at least N). Read-only.
- `src/commands/doctor/checks/captured-facts.ts` — `captured_facts_active` (wave check, host-only): counts active capture-lane facts (`hook:writeback`, `hook:compact`, `sweep:corpus`) that `classifyCapturedFacts` classes as self-capture (`evidenced`) or paste candidates (`ambiguous`); `excluded` and `unclassifiable` are reported, never a finding. Names `gbrain repair captured-facts` (explicit-only) and says it counts facts while `self_capture` counts corpus files. Read-only; health unknown when the scan fails.
- `src/commands/doctor/checks/loop-facts.ts` — `loop_facts_drift` (#5869): counts closed commitment loops whose fact is still active and retirable (`loopFactDrift`) and names `gbrain repair loop-facts` (explicit-only). Read-only; health unknown when the query fails.
- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set), origins (`mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` excluded; the fix is `gbrain facts relink --dry-run`, and the remote report asks the brain host operator to run it. Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Tests: `test/doctor-unlinked-facts.test.ts`.
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 0e3da94712..6041d67113 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Both paths prevent LLM-chosen titles that drift between extractions from piling up.
Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (keyed `(source_id, file_path, content_hash)`, 16-char hash prefix, so an edit is a new row): `recordItemFailureCount` counts a transcript's malformed output or prompt-level provider block (`providerContentBlockReason`; never feeds the outage halt) toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (as pages do), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.
-- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (`row_num IS NULL`, live entity page) through `facts/unfenced-facts.ts` and adds those pages to the run's reconcile set (`unfencedRowsFenced`); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and still skip the destructive reconcile (the empty-fence guard, `legacyRowsPending`), while rows with no backing page or checkout never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. On an unmanaged brain each reconcile records its outcome in `page_facts_reconcile` (`src/core/facts/reconcile-watermark.ts`): a complete reconcile (including a no-op) stamps the page's `knowledge_revision` inside the write transaction, after a `FOR SHARE` lock and a revision recheck (a moved page writes nothing and stays due); `deferred` (lock, stale cache, embedding deferral, rejected write), `invalid` (malformed or misplaced fence, not retried until the page changes) and `cancelled` leave it due. The dream cycle passes `drain`, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call with `slugs: []` and no `drain` still reconciles nothing. Doctor's `extract_health` names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: `test/extract-facts-reconcile-drain.test.ts` (Postgres race through `test/e2e/extract-facts-reconcile-drain-postgres.test.ts`), `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`.
+- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (`row_num IS NULL`, live entity page) through `facts/unfenced-facts.ts` and adds those pages to the run's reconcile set (`unfencedRowsFenced`); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and still skip the destructive reconcile (the empty-fence guard, `legacyRowsPending`), while rows with no backing page or checkout never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. On an unmanaged brain each reconcile records its outcome in `page_facts_reconcile` (`src/core/facts/reconcile-watermark.ts`): a complete reconcile (including a no-op) stamps the page's `knowledge_revision` inside the write transaction, after a `FOR SHARE` lock and a revision recheck (a moved page writes nothing and stays due); `deferred` (lock, stale cache, embedding deferral, rejected write), `invalid` (malformed or misplaced fence, not retried until the page changes) and `cancelled` leave it due. The dream cycle passes `drain`, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call with `slugs: []` and no `drain` still reconciles nothing. Doctor's `extract_health` names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: `test/extract-facts-reconcile-drain.test.ts` (Postgres race through `test/e2e/extract-facts-reconcile-drain-postgres.test.ts`), `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`. On a managed brain each changed page publishes a `managed_maintenance_fence_facts` request bound to its revision (the preparer replans under the page key and uses a carried vector only for the same row and claim under the current model) and each soft-deleted page's expiry a `managed_maintenance_deleted_page_facts_expire` request (admitted only while the page is soft-deleted, rechecked under the lock); a page in sync admits nothing.
- `src/core/cycle/inline-drain.ts` — the dream cycle's private-queue drain. `runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)` runs N independent `drainLoop`s (`dream.synthesize.inline_concurrency`, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) while `promoteDelayed` runs in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker: `UnrecoverableError` → dead immediately; `RateLeaseUnavailableError` → `releaseLeaseFullJob` requeue without burning an attempt; timeout terminal. Handler invocation is wrapped in `withChatPhase('job:<name>')` (worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bare `await handler(context)` inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wraps `phase:synthesize`) would absorb every child's spend into the phase tag. `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank `percentile()` telemetry helper are exported. Pinned by `test/cycle-synthesize-inline-concurrency.test.ts` (loop semantics) + `test/e2e/dream-synthesize-concurrency-postgres.test.ts` (real-Postgres exact-once + lease-ceiling).
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index d82622755a..72d757a3f0 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -22,7 +22,8 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.
Derived atom pages may regenerate or retire when their canonical file is already absent, while ordinary page writes retain missing-file refusal.
Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.
-- `src/core/persistence/derived-facts.ts` — database-only fact rows derived from page text (fence reconcile, conversation facts): `managedDerivedFactsPreflight` (managed check, accepting persistence, local writer, active source; before provider spend), `withDerivedFactsWrite` (one transaction holding the coordinator source capability and the page keys, like derived links), `writeDerivedFacts` (that on a managed brain, the caller's own engine call otherwise) and `replaceDerivedFactsForPage` (inside that transaction: the caller's current-page recheck, then the page's prior rows for one writer prefix are deleted and the replacement batch inserted, so a failed or raced extraction keeps the prior batch; `test/managed-facts-writers.test.ts`). No persistence request is admitted per row. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.
+- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.
+- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` requests (`submitDatabaseMaintenanceIntent`, dispatched from `prepareMaintenanceMutation`). `startConversationGeneration` runs before model work: the generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, `--since`/`--segment-limit`, newest extractor row id) and attempt number make the request id, so an admitted request is replayed (`settled`, zero model calls), a retryable failure resubmits its stored batch (`resubmit`), a deterministic one (`invalid_params`, `permission_denied`, size) or three failed attempts block the generation until the page changes. `buildConversationIntent` freezes the rows (`FrozenExtractedFact` shape without source, page, row number or visibility; vectors only under the brain's facts embedding signature); `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest batch cannot fit before any model call; `assertConversationAdmissionHeadroom` stops the run at 80% of `principalOutstanding` (`maintenance_backpressure`, exit 12) and checks lifetime ids. The preparer rechecks authority, page id, revision and version token (sidecar bytes), the embedding signature and alias merges, and `replaceConversationFacts` deletes the page's extractor rows and inserts the batch numbered above every remaining row, failing on a lost insert. Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.
- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`.
diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsv
index 453851fcd7..a1fa5cc6ef 100644
--- a/docs/architecture/managed-mutating-writers.tsv
+++ b/docs/architecture/managed-mutating-writers.tsv
@@ -69,7 +69,7 @@ op mute_notice no_canonical_write Notice mute list in <GBRAIN_HOME>/notices/mute
op loops_unmute no_canonical_write Loop suppression rows.
op rate_answer no_canonical_write Writes only retrieval_* feedback tables (answer ratings and learned weights), never a guarded canonical table or file.
cli src/commands/enrich.ts coordinator gbrain enrich preflights maintenance authority, then publishMaintenancePage per page.
-cli src/commands/extract-conversation-facts.ts coordinator Bulk conversation facts commit through the coordinator capability after a derived-facts preflight.
+cli src/commands/extract-conversation-facts.ts coordinator Bulk conversation facts publish per page as receipted managed_maintenance_conversation_facts requests after a maintenance preflight.
cli src/commands/pages.ts coordinator gbrain pages purge-deleted runs purgeDeletedPagesCoordinated.
cli src/core/bootstrap/verify.ts coordinator gbrain bootstrap verify writes probes with put_page and purges them through delete_page purge.
cli src/core/google/loops-extract.ts coordinator Loop commitments publish through writeSingleFact's managed facts path.
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 138174c432..29afd0a1e1 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -214,7 +214,7 @@ Attributed (inside a request, a coordinated scope or `maintenanceTransaction`,
or a physical projection that leaves attribution untouched):
<!-- write-attribution-covered:start -->
-- `src/commands/extract-conversation-facts.ts` (3): the conversation fact index writes through `writeDerivedFacts`: one `maintenanceTransaction` on unmanaged brains, `withDerivedFactsWrite` on managed brains.
+- `src/commands/extract-conversation-facts.ts` (3): the unmanaged conversation fact index writes through `writeDerivedFacts` (one `maintenanceTransaction`); managed brains publish each page as a receipted `managed_maintenance_conversation_facts` request.
- `src/commands/extract-timeline-db.ts` (2): `gbrain extract timeline --source db` commits one `maintenanceTransaction` per 100-row batch on unmanaged brains; managed brains publish per page through a maintenance request.
- `src/commands/migrate-engine.ts` (5): engine copy keeps the source rows' attribution values verbatim.
- `src/commands/sync/holds.ts` (1): a full sync's move of a held rename (`updateSlug` and its `source_path`) runs in one `maintenanceTransaction`; managed sources publish renames through the sync request preparer.
@@ -226,8 +226,8 @@ or a physical projection that leaves attribution untouched):
- `src/core/cycle/drift.ts` (1): the unmanaged drift report page runs in `maintenanceTransaction`; managed brains publish it through a maintenance request.
- `src/core/cycle/extract-atoms-page-state.ts` (1): the atom completion stamp runs in `maintenanceTransaction`.
- `src/core/cycle/extract-atoms.ts` (1): stale atom retirement soft-deletes in 500-page `maintenanceTransaction` chunks.
-- `src/core/cycle/extract-facts.ts` (7): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains write through `withDerivedFactsWrite`.
-- `src/core/cycle/extract-takes.ts` (2): coordinated per page on managed brains; the unmanaged batch upsert runs in `maintenanceTransaction`.
+- `src/core/cycle/extract-facts.ts` (7): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains publish `managed_maintenance_fence_facts` and `managed_maintenance_deleted_page_facts_expire` requests whose preparers write inside the coordinator publication.
+- `src/core/cycle/extract-takes.ts` (2): a receipted `managed_maintenance_takes_reextract` request per changed page on managed brains; the unmanaged batch upsert runs in `maintenanceTransaction`.
- `src/core/cycle/grade-takes.ts` (1): unmanaged take auto-resolution runs in `maintenanceTransaction`; managed brains publish a `takes_resolve` request.
- `src/core/cycle/phantom-redirect.ts` (3): the unmanaged phantom fact move, canonical body refresh and phantom soft delete run in `maintenanceTransaction`; the managed redirect moves facts inside its coordinated write.
- `src/core/cycle/phases/consolidate.ts` (4): unmanaged consolidation takes and fact updates run in `maintenanceTransaction` per cluster step; managed brains submit a maintenance consolidation request.
@@ -235,6 +235,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/embed-facts.ts` (1): embedding columns only (physical projection).
- `src/core/embedding-dim-check.ts` (1): embedding columns only (physical projection).
- `src/core/extract/receipt-writer.ts` (1): the extraction receipt page runs in `maintenanceTransaction`.
+- `src/core/facts/conversation-publication.ts` (1): the managed conversation-facts preparer inserts the frozen batch inside the coordinator publication of its admitted request.
- `src/core/facts/backstop.ts` (3): the facts backstop's DB-only fallbacks insert each fact in `maintenanceTransaction`; managed brains publish through the facts request preparer.
- `src/core/facts/fence-write.ts` (2): the markdown-first fence reconcile insert and its page body mirror each run in `maintenanceTransaction`.
- `src/core/facts/forget.ts` (4): the legacy fence expiry, withdrawal and strike-through each run in `maintenanceTransaction` (nested inside a caller's coordinated write, they keep its actor).
@@ -254,7 +255,6 @@ or a physical projection that leaves attribution untouched):
- `src/core/persistence/canonical-projections.ts` (7): fence projection inside the request's publication.
- `src/core/persistence/connector-google-receipts.ts` (2): request preparer.
- `src/core/persistence/connector-sync.ts` (2): connector publication inside `withCoordinatedWrite`.
-- `src/core/persistence/derived-facts.ts` (1): `withDerivedFactsWrite` (managed derived facts); `writeDerivedFacts` runs legacy writers in `maintenanceTransaction` on unmanaged brains.
- `src/core/persistence/facts-prepare.ts` (3): managed `extract_facts` request preparer.
- `src/core/persistence/file-repair.ts` (2): `managed_file_repair` request preparer (#5988).
- `src/core/persistence/grandfather.ts` (2): request preparer.
@@ -270,7 +270,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/repair/captured-facts.ts` (1): a request on managed brains; the unmanaged captured-facts expiry runs in `maintenanceTransaction`.
- `src/core/repair/extractor-facts.ts` (1): a request on managed brains; the unmanaged extractor-facts restore runs in `maintenanceTransaction`.
- `src/core/repair/frontmatter.ts` (1): a `managed_file_repair` request on managed sources; the unmanaged rename runs in `maintenanceTransaction`.
-- `src/core/repair/take-supersession.ts` (1): `gbrain repair take-supersession` reprojection: `withCoordinatedWrite` under the page key on managed brains, `maintenanceTransaction` on unmanaged ones; fence edits go through a revision-bound `put_page`.
+- `src/core/repair/take-supersession.ts` (1): `gbrain repair take-supersession` reprojection: a receipted `managed_maintenance_take_reproject` request on managed brains, `maintenanceTransaction` on unmanaged ones; fence edits go through a revision-bound `put_page`.
- `src/core/repair/stale-atoms.ts` (3): a request on managed brains; the unmanaged retirement runs in `maintenanceTransaction`.
- `src/core/schema-pack/page-to-alias.ts` (1): the page-to-alias conversion soft-deletes each converted page in `maintenanceTransaction`.
- `src/core/schema-pack/page-to-link.ts` (1): the page-to-link conversion soft-deletes each converted page in `maintenanceTransaction`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 957b1214ce..0fb57760a4 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -69,7 +69,7 @@ of making a duplicate.
| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. |
| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
-| <a id="maintenance_backpressure"></a>`maintenance_backpressure` (exit 12) | `maintenance_backpressure` | A managed maintenance run (`gbrain extract-conversation-facts`, its cycle phase or job) publishes each page as its own request. Before each page's model work it checks this CLI writer's outstanding requests; at 80% of `persistence.limits.principalOutstanding` it stops admitting, so a slow or absent consumer cannot turn the run into refused admissions. Pages already published keep their facts and nothing is half-written. | Read the pending requests with `gbrain sources writer status --source <id> --json`. A resident `gbrain serve`, or the next CLI run, publishes them; once they settle, rerun the same command. Raising `persistence.limits.principalOutstanding` is the user's call. |
+| <a id="maintenance_backpressure"></a>`maintenance_backpressure` (exit 12) | `maintenance_backpressure` | A managed maintenance run (`gbrain extract-conversation-facts`, its cycle phase or job) publishes each page as its own request. Before each page's model work it checks this CLI writer's outstanding requests; at 80% of `persistence.limits.principal_outstanding` it stops admitting, so a slow or absent consumer cannot turn the run into refused admissions. Pages already published keep their facts and nothing is half-written. | Read the pending requests with `gbrain sources writer status --source <id> --json`. A resident `gbrain serve`, or the next CLI run, publishes them; once they settle, rerun the same command. Raising `persistence.limits.principal_outstanding` is the user's call. |
### Other error codes
diff --git a/docs/w9f/R.md b/docs/w9f/R.md
new file mode 100644
index 0000000000..36ffd3c633
--- /dev/null
+++ b/docs/w9f/R.md
@@ -0,0 +1,98 @@
+# Wave 9 follow-ups, lane R: receipts on managed brains
+
+Integrator notes for the release PR. Nothing here is stamped: no VERSION, no
+CHANGELOG header, no BEHAVIOR_CHANGES row was written to source. Copy the
+lines below when the PR is next to merge.
+
+## CHANGELOG lines
+
+- Managed brains now publish conversation facts through receipted maintenance
+ requests (`managed_maintenance_conversation_facts`). Each page's facts and
+ its outcome row commit in one transaction with their receipt. A crash after
+ the request was accepted replays the stored batch on the next run without
+ calling the model again; a request that fails the same way every time
+ blocks that page version (no more model calls until the page changes); at
+ most three requests are admitted per page version.
+- Managed brains now extract facts from email threads, and record single
+ emails, prose meeting notes and undated pages as "not extractable" for good
+ instead of rescanning them every run.
+- `gbrain extract-conversation-facts` on a managed brain stops admitting at
+ 80% of the writer's outstanding-request limit (`maintenance_backpressure`,
+ exit 12), skips a page whose largest batch cannot fit one request before any
+ model call, and refuses up front when the writer's permanent request ids
+ cannot cover the run.
+- The cycle `extract_facts` fence reconcile, its deleted-page fact expiry,
+ `gbrain extract takes --source db` / `gbrain takes rebuild` / the v0.28.0
+ takes backfill, and `gbrain repair take-supersession`'s database branch now
+ publish receipted maintenance requests on managed brains. A page that is
+ already in sync admits nothing.
+- Conversation extraction outcomes record the parser/extractor version
+ (`extractor_version=<n>` in the outcome row context). Doctor
+ `conversation_outcomes_stale` counts outcomes from an older version; they
+ are never reopened automatically.
+
+## BEHAVIOR_CHANGES candidate (one row, `since:` = this release)
+
+> Managed brains now extract facts from email threads and record single emails, prose meeting notes and undated pages as not extractable for good. Preview what a run would extract and its segment count with `gbrain extract-conversation-facts --source-id <id> --dry-run`; a two-message thread is one segment, about $0.006 on Haiku 4.5 or $0.017 on Sonnet 4.6. Spend stays under the existing caps (`--max-cost-usd`, default $5; the opt-in `cycle.conversation_facts_backfill` at $1 per run and $5 total); nothing submits extraction automatically. There is no separate opt-out for email threads: leave the backfill off, or narrow `cycle.conversation_facts_backfill.types`.
+
+The per-thread estimate is the plan's per-segment figure (about 3k input and
+0.5k output tokens per segment, priced from `model-pricing.ts`), not a
+measurement.
+
+## Upgrade notes
+
+- Managed conversation-fact extraction, fence reconcile, takes reextract and
+ take-supersession reprojection now preflight like every other managed
+ maintenance writer (`maintenancePreflight`): a source with a canonical
+ checkout needs its active owner on this host before any model work. The
+ cycle and takes paths preflight lazily, on the first page that needs a
+ write, so a run with nothing to change never needs it.
+- A request still pending after the job's wait is reported (`pages_pending`)
+ and replayed on the next run with no model call.
+
+## Decision 9: measured request volume
+
+Run: 200 managed conversation pages on PGLite (a quarter each of two-segment
+transcripts, one-segment transcripts, short transcripts and prose notes),
+three facts per segment with 1536-dimension vectors, injected extractor (no
+model calls). Script: `~/.capy/work/w9f-r/scratch/measure-d9.test.ts`
+(not committed); output `~/.capy/work/w9f-r/out/d9-measure.json`.
+
+| Measure | Per request | Per 1k pages | 50k pages | Share of default limit |
+|---|---|---|---|---|
+| Permanent request ids | 1 | 1,000 | 50,000 | 20% of `principalLifetimeIds` (250,000) |
+| Intent bytes (transient; released when the request settles) | avg 96 KB, max 191 KB | 96 MB (one at a time) | - | per request well under `principalIntentBytes` (32 MiB) |
+| Reserved receipt bytes (30-day window) | 16 KiB | 16 MiB | 819 MB | 51% of `principalTerminalBytes` (1,536 MiB) |
+
+One request id per page per extraction generation (each later page edit adds
+one). At 50k pages the backfill alone uses 20% of the writer's permanent
+request ids, above Decision 9's 10% switch threshold, and reserves half of
+its receipt bytes for the retention window (compacted receipts keep about
+4 KiB each, about 13% long term). Per Decision 9 (A) this wave keeps outcomes
+as receipted facts rows and reports the number; the threshold is crossed, so
+Garry's call on 9B (a non-guarded outcome side table for
+non-extractable/terminal outcomes) or batching outcomes across pages is the
+follow-up.
+
+## Functions touched in GBRA-52's file (`src/commands/extract-conversation-facts.ts`)
+
+`ExtractConversationFactsResult` (two optional counters), `ExtractCoreState`
+(`managed` is now the publisher or null), `processPage` (three managed call
+sites), `runExtractConversationFactsCore` (preflight line, run-stop errors in
+the two page loops), `runExtractConversationFacts` (aggregate and print the
+two counters), `terminalAuditFact`/`nonExtractableAuditFact` (version
+stamp); new `currentConversationVersionToken`; removed `replacePageFacts`.
+The managed logic lives in `src/core/facts/conversation-publication.ts`.
+
+## TODOs (not written to TODOS.md)
+
+- Receipts for the pages, timeline and alias derived writers
+ (`page-state/materialize.ts`, `timeline-extract.ts`, `reindex-aliases.ts`,
+ `mentions/pass.ts`) and for bootstrap verify's probe-fact cleanup
+ (`bootstrap/verify.ts`), each listed in `test/receipt-coverage.test.ts`.
+- Production fail-closed receipt guard (Decision 10 B): the contract harness
+ enforces it today.
+- Decision 9 follow-up above.
+- A parser-version change is part of the generation identity but has no
+ runtime test (the version is a constant); the stamp and doctor count are
+ tested.
diff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjs
index 2fb97dd41b..a5e54c298e 100644
--- a/scripts/check-core-guard-coverage.mjs
+++ b/scripts/check-core-guard-coverage.mjs
@@ -40,6 +40,10 @@ const EXEMPT = {
'src/core/shared-skills/publication.ts': 'skill bundles, not pages',
'src/core/persistence/prepared-import.ts': 'type definitions shared by import preparers; prepares nothing itself',
'src/commands/extract-timeline-db.ts': 'writes timeline rows; timeline never enters core',
+ 'src/core/facts/conversation-publication.ts': 'writes database-only conversation fact rows; page text is unchanged',
+ 'src/core/cycle/extract-facts.ts': 'fence reconcile and deleted-page expiry write fact rows only; page text is unchanged',
+ 'src/core/cycle/extract-takes.ts': 'takes reextract writes take rows only; page text is unchanged',
+ 'src/core/repair/take-supersession.ts': 'reprojection writes takes.superseded_by only; fence edits go through put_page (preparePageMutation)',
};
const GUARDED = /\b(preparePageMutation|prepareMemoryMutation|prepareCoreGuard)\b/;
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index a8dd5d4657..2621a43a73 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -32,7 +32,7 @@ src/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refa
src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle.ts runCycle 1271 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts)
src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 790 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts); +1 #5031: per-run page-atom title memo for the case-insensitive adoption fallback
-src/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/core/cycle/extract-facts.ts runExtractFacts 376 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); -129 wave 9 follow-ups (receipts): the page reconcile plan and writes moved into planFenceReconcile/reconcileWrites/writeFenceReconcile, shared with the managed preparer
src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/patterns.ts runPhasePatterns 303 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/propose-takes.ts ProposeTakesPhase.process 429 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout)
diff --git a/src/commands/doctor/checks/conversation-outcomes.ts b/src/commands/doctor/checks/conversation-outcomes.ts
new file mode 100644
index 0000000000..a064c858a7
--- /dev/null
+++ b/src/commands/doctor/checks/conversation-outcomes.ts
@@ -0,0 +1,51 @@
+/**
+ * conversation_outcomes_stale (wave 9 follow-ups, Decision 8): conversation
+ * pages whose durable extraction outcome (EXTRACTION_COMPLETE or
+ * EXTRACTION_NOT_APPLICABLE) was recorded by an older conversation
+ * parser/extractor version than this binary's CONVERSATION_EXTRACTOR_VERSION.
+ *
+ * An outcome stays fresh across a parser change (nothing reopens on its own,
+ * so an upgrade never spends without the user), so this check is how a newer
+ * parser's reach is seen: it counts stale outcomes and names the dry run that
+ * previews re-extracting them. Outcomes older than the version stamp itself
+ * are counted separately and never warn. Bounded: an indexed scan of the
+ * extractor rows (idx_facts_extract_conversation_session), capped at
+ * OUTCOME_SCAN_CAP and reported as "at least N" past it. Read-only.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { CONVERSATION_EXTRACTOR_VERSION, NON_EXTRACTABLE_AUDIT_SOURCE, outcomeExtractorVersion, TERMINAL_AUDIT_SOURCE } from '../../../core/facts/audit-sources.ts';
+
+export const OUTCOME_SCAN_CAP = 5000;
+
+export async function conversationOutcomesStaleCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
+ const name = 'conversation_outcomes_stale';
+ try {
+ const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
+ const rows = await engine.executeRaw<{ source_id: string; slug: string; context: string | null }>(
+ `SELECT source_id, source_markdown_slug AS slug, context FROM facts
+ WHERE source_id = ANY($1::text[]) AND source LIKE 'cli:extract-conversation-facts%' AND source = ANY($2::text[]) AND expired_at IS NULL
+ ORDER BY id DESC LIMIT $3`, [sources, [TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE], OUTCOME_SCAN_CAP + 1]);
+ const capped = rows.length > OUTCOME_SCAN_CAP;
+ const scanned = rows.slice(0, OUTCOME_SCAN_CAP).map(row => ({ ...row, version: outcomeExtractorVersion(row.context) }));
+ const stale = scanned.filter(row => row.version !== null && row.version < CONVERSATION_EXTRACTOR_VERSION);
+ const unstamped = scanned.filter(row => row.version === null).length;
+ const sample = stale.slice(0, 5).map(row => `${row.source_id}:${row.slug}`);
+ const details = { extractor_version: CONVERSATION_EXTRACTOR_VERSION, scanned: scanned.length, capped,
+ stale: stale.length, unstamped, sample, docs: 'docs/guides/repair.md#conversation-labels' };
+ const atLeast = capped ? 'at least ' : '';
+ if (!stale.length) {
+ return { name, status: 'ok', details,
+ message: `No conversation extraction outcome predates extractor version ${CONVERSATION_EXTRACTOR_VERSION}`
+ + (unstamped ? ` (${atLeast}${unstamped} outcome(s) were recorded before outcomes carried a version; they stay as they are).` : '.') };
+ }
+ const first = stale[0]!;
+ return { name, status: 'warn', details,
+ message: `${atLeast}${stale.length} conversation page(s) keep an extraction outcome from an older parser/extractor version (current ${CONVERSATION_EXTRACTOR_VERSION}); `
+ + 'they are not reopened automatically. Preview re-extracting one with: '
+ + `gbrain extract-conversation-facts --source-id ${first.source_id} --slug ${first.slug} --force --dry-run — then run it without --dry-run (spend is capped by --max-cost-usd, default $5).` };
+ } catch (error) {
+ return { name, status: 'warn', details: { stale: 'unknown' },
+ message: `Conversation extraction outcomes could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };
+ }
+}
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 89d34080d2..43576625b4 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -297,6 +297,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'google_file_modes',
'extractor_facts_expired',
'captured_facts_active',
+ 'conversation_outcomes_stale',
'loop_facts_drift',
],
run: runTimelineHistory,
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 15e0c6d401..eb7c7fec19 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -205,6 +205,14 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
impact: 'Some conversation-extractor facts were expired by the pre-v0.60.11.0 canonical projection and recall no longer returns them',
run: async (engine, scope) => (await import('./checks/extractor-facts.ts')).extractorFactsCheck(engine, scope.sourceIds),
},
+ {
+ id: 'conversation_outcomes_stale', resolution: 'operator', registration: 'wave',
+ hostOnly: 'Re-extracting conversation facts spends model calls on the brain host.',
+ instruction: 'Preview re-extracting a page the check names with gbrain extract-conversation-facts --source-id <id> --slug <slug> --force --dry-run, then run it without --dry-run after the user agrees to the spend.',
+ count: d => Number(d.stale ?? 0),
+ impact: 'Some conversation pages keep an extraction outcome recorded by an older conversation parser, which is never reopened automatically',
+ run: async (engine, scope) => (await import('./checks/conversation-outcomes.ts')).conversationOutcomesStaleCheck(engine, scope.sourceIds),
+ },
{
id: 'captured_facts_active', resolution: 'repair', registration: 'wave',
hostOnly: 'Classifying captured facts reads harness transcripts and the session corpus on the brain host; the repair is explicit-only.',
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index d44ee34af1..bd6e0b7fe0 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -77,21 +77,7 @@ import {
import { configureGatewayIfUninitialized, isAvailable, withBudgetTracker } from '../core/ai/gateway.ts';
import { writeDerivedFacts } from '../core/persistence/derived-facts.ts';
import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
-import { maintenancePreflight, type MaintenanceAuthority } from '../core/persistence/prepared-maintenance.ts';
-import { loadConfig, type GBrainConfig } from '../core/config.ts';
-import { OperationError } from '../core/ops/contract.ts';
-import { resolveManagedFactsEmbedding } from '../core/persistence/facts-maintenance.ts';
-import {
- assertConversationAdmissionHeadroom,
- buildConversationIntent,
- conversationIntentByteLimit,
- estimateConversationIntentBytes,
- startConversationGeneration,
- submitConversationIntent,
- type ConversationFactRow,
- type GenerationStart,
-} from '../core/facts/conversation-publication.ts';
-import type { FactEmbeddingSignature } from '../core/facts/extract.ts';
+import { managedConversationPublisher, publishManagedBatch, startManagedPage, stopsRun, type ManagedConversationPublisher } from '../core/facts/conversation-publication.ts';
import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason, type NoPricingGuidance } from '../core/budget/budget-tracker.ts';
import { noPricingMessage } from '../core/budget/no-pricing.ts';
import { conversationFactsCostCap } from '../core/facts/conversation-budget.ts';
@@ -765,13 +751,8 @@ interface ExtractCoreState {
result: ExtractConversationFactsResult;
engine: BrainEngine;
sourceId: string;
- /** Managed brain: a page's rows are buffered and replace the prior batch in one receipted request. */
- managed: boolean;
- /** Managed brain, not a dry run: the maintenance authority its requests publish under. */
- authority: MaintenanceAuthority | null;
- config: GBrainConfig;
- /** Managed brain: the facts embedding signature frozen batches carry (null: no vectors). */
- embedding: FactEmbeddingSignature | null;
+ /** Managed brain (not a dry run): a page's rows are buffered and replace the prior batch in one receipted request. */
+ managed: ManagedConversationPublisher | null;
dryRun: boolean;
sleepMs: number;
segmentLimit: number;
@@ -973,96 +954,6 @@ export async function currentConversationVersionToken(engine: BrainEngine, page:
return (await preparePageSnapshot(engine, page)).versionToken;
}
-/**
- * Managed brains, before any model work for one page: resolve its extraction
- * generation and settle it without the model when this writer already
- * admitted a request for it (replayed, resubmitted, pending or blocked), or
- * when its largest possible batch cannot fit one request. Returns the
- * generation to extract into otherwise.
- */
-async function startManagedPage(
- state: ExtractCoreState,
- snapshot: ConversationPageSnapshot,
- sinceIso: string | undefined,
- segments: number,
-): Promise<{ done: { newEndIso: string | null } } | { start: Extract<GenerationStart, { kind: 'extract' }> }> {
- const authority = state.authority!;
- const { page } = snapshot;
- const start = await startConversationGeneration(state.engine, authority, state.config, {
- slug: page.slug, page, versionToken: snapshot.versionToken, since: sinceIso ?? null, segmentLimit: state.segmentLimit,
- });
- if (start.kind === 'extract') {
- const planned = state.segmentLimit > 0 ? Math.min(segments, state.segmentLimit) : segments;
- const estimate = estimateConversationIntentBytes(planned, state.embedding);
- const limit = await conversationIntentByteLimit(state.engine);
- if (estimate > limit) {
- state.result.pages_skipped_too_large++;
- process.stderr.write(`[extract-conversation-facts] SKIP ${page.slug}: up to ${planned} segment(s) could freeze a ${estimate}-byte batch, over the ${limit}-byte request limit; its prior facts were kept and no model call ran. Narrow it with --slug ${page.slug} --segment-limit <n>\n`);
- return { done: { newEndIso: null } };
- }
- await assertConversationAdmissionHeadroom(state.engine, authority);
- return { start };
- }
- if (start.kind === 'resubmit') {
- process.stderr.write(`[extract-conversation-facts] ${page.slug}: resubmitting the stored batch of this page generation (attempt ${start.attempt + 1}); no model call\n`);
- await assertConversationAdmissionHeadroom(state.engine, authority);
- return { done: settleManagedReceipt(state, page.slug, await submitConversationIntent(state.engine, authority, page.slug, start, start.intent)) };
- }
- if (start.kind === 'settled') {
- process.stderr.write(`[extract-conversation-facts] ${page.slug}: this page generation was already published; replaying its receipt, no model call\n`);
- return { done: settleManagedReceipt(state, page.slug, start.receipt) };
- }
- if (start.kind === 'pending') {
- state.result.pages_pending = (state.result.pages_pending ?? 0) + 1;
- process.stderr.write(`[extract-conversation-facts] ${page.slug}: request ${start.requestId} for this page is accepted and still pending; rerun to confirm (no model call)\n`);
- return { done: { newEndIso: null } };
- }
- state.result.pages_blocked = (state.result.pages_blocked ?? 0) + 1;
- process.stderr.write(`[extract-conversation-facts] SKIP ${page.slug}: ${start.message}\n`);
- return { done: { newEndIso: null } };
-}
-
-/** Books a committed managed receipt into the run's counters. */
-function settleManagedReceipt(state: ExtractCoreState, slug: string, receipt: Record<string, unknown>): { newEndIso: string | null } {
- state.result.orphan_facts_cleaned += Number(receipt.deleted ?? 0);
- state.result.facts_inserted += Number(receipt.facts_inserted ?? 0);
- if (receipt.page_outcome === 'non_extractable') {
- state.result.pages_marked_non_extractable++;
- return { newEndIso: null };
- }
- state.result.pages_processed++;
- const newest = typeof receipt.newest_end === 'string' ? receipt.newest_end : null;
- if (newest) state.cpMap.set(cpMapKey(state.sourceId, slug), newest);
- return { newEndIso: newest };
-}
-
-/**
- * Managed publication of one page's frozen batch as a receipted request.
- * Returns the fact rows inserted, or null when the request is accepted but
- * still pending after the job's wait (the page stays unfinished).
- */
-async function publishManagedBatch(
- state: ExtractCoreState,
- snapshot: ConversationPageSnapshot,
- start: Extract<GenerationStart, { kind: 'extract' }>,
- rows: ConversationFactRow[],
- newestEnd: string | null,
-): Promise<number | null> {
- const complete = rows.some(row => row.source === TERMINAL_AUDIT_SOURCE || row.source === NON_EXTRACTABLE_AUDIT_SOURCE);
- const intent = await buildConversationIntent(state.engine, state.config, start, rows,
- { complete, newestEnd, visibility: state.factVisibility });
- try {
- const receipt = await submitConversationIntent(state.engine, state.authority!, snapshot.page.slug, start, intent);
- state.result.orphan_facts_cleaned += Number(receipt.deleted ?? 0);
- return Number(receipt.facts_inserted ?? 0);
- } catch (error) {
- if (!(error instanceof OperationError) || error.code !== 'write_pending') throw error;
- state.result.pages_pending = (state.result.pages_pending ?? 0) + 1;
- process.stderr.write(`[extract-conversation-facts] ${snapshot.page.slug}: its facts were accepted and are still pending; rerun to confirm (the rerun replays them, no model call)\n`);
- return null;
- }
-}
-
async function processPage(
state: ExtractCoreState,
snapshot: ConversationPageSnapshot,
@@ -1183,11 +1074,10 @@ async function processPage(
? 'no conversation messages found'
: 'fewer than two eligible messages');
if (await snapshotIsCurrent(state.engine, state.sourceId, snapshot)) {
- if (state.authority) {
+ if (state.managed) {
const managed = await startManagedPage(state, snapshot, sinceIso, 0);
if ('done' in managed) return managed.done;
- const row = nonExtractableAuditFact(page.slug, 0, snapshot.versionToken, reason);
- if (await publishManagedBatch(state, snapshot, managed.start, [row], null) === null) return { newEndIso: null };
+ if (await publishManagedBatch(state, snapshot, managed.start, [nonExtractableAuditFact(page.slug, 0, snapshot.versionToken, reason)], null) === null) return { newEndIso: null };
} else {
state.result.orphan_facts_cleaned += await deleteOrphanFactsForPage(state.engine, state.sourceId, page.slug);
const rowNum = await peekRowNumStart(state.engine, state.sourceId, page.slug);
@@ -1207,13 +1097,8 @@ async function processPage(
return { newEndIso: null };
}
- let managedStart: Extract<GenerationStart, { kind: 'extract' }> | null = null;
- if (state.authority) {
- const managed = await startManagedPage(state, snapshot, sinceIso, segments.length);
- if ('done' in managed) return managed.done;
- managedStart = managed.start;
- }
-
+ const managed = state.managed ? await startManagedPage(state, snapshot, sinceIso, segments.length) : null;
+ if (managed && 'done' in managed) return managed.done;
// D11: delete-orphans-first replay safety. Wipes any facts written by
// a prior crashed / killed / partial run for this (sourceId, slug)
// pair before we re-extract. The lock we hold (D2 + D12 refreshing
@@ -1366,11 +1251,10 @@ async function processPage(
return { newEndIso: null };
}
- if (managedStart && newestEnd !== null) {
- const inserted = await publishManagedBatch(state, snapshot, managedStart, managedRows, newestEnd);
+ if (managed && newestEnd !== null) {
+ const inserted = await publishManagedBatch(state, snapshot, managed.start, managedRows, newestEnd);
if (inserted === null) return { newEndIso: null };
- pageInsertedTotal = inserted;
- state.result.facts_inserted += pageInsertedTotal;
+ state.result.facts_inserted += pageInsertedTotal = inserted;
}
if (newestEnd !== null) {
@@ -1453,13 +1337,7 @@ export async function runExtractConversationFactsCore(
if (!sourceId) {
throw new Error('runExtractConversationFactsCore: opts.sourceId is required');
}
- // A managed brain publishes each page's batch as a receipted maintenance
- // request; the authority is preflighted once, before any model work. A dry
- // run writes nothing and registers nothing.
- const managed = await managedPersistenceEnabled(engine);
- const authority = managed && !opts.dryRun ? await maintenancePreflight(engine, sourceId) : null;
- const config = loadConfig() ?? { engine: engine.kind };
- if (authority) await assertConversationAdmissionHeadroom(engine, authority, opts.slugs?.length ?? (opts.slug ? 1 : opts.limit ?? 1));
+ const managed = await managedConversationPublisher(engine, sourceId, opts);
const result: ExtractConversationFactsResult = {
pages_considered: 0,
@@ -1544,9 +1422,6 @@ export async function runExtractConversationFactsCore(
engine,
sourceId,
managed,
- authority,
- config,
- embedding: authority ? await resolveManagedFactsEmbedding(engine, config) : null,
dryRun,
sleepMs,
segmentLimit,
@@ -2328,11 +2203,6 @@ function recordPageFailure(result: ExtractConversationFactsResult, sourceId: str
process.stderr.write(`[extract-conversation-facts] ${slug} failed (${reason}) and stays unfinished; retry: gbrain extract-conversation-facts --source-id ${sourceId} --slug ${slug}\n`);
}
-/** Managed admission backpressure and exhausted request ids stop the whole run, not one page. */
-function stopsRun(err: unknown): boolean {
- return err instanceof OperationError && (err.code === 'maintenance_backpressure' || err.code === 'queue_capacity');
-}
-
export function isAbortError(err: unknown): boolean {
if (!(err instanceof Error)) return false;
return err.name === 'AbortError' || /aborted|cancell?ed/i.test(err.message);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index f543e71e09..e81b770294 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -47,7 +47,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', '--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', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--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', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--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', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--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', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--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'],
@@ -79,7 +79,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--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': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--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', '--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', '--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', '--status', '--timeout', '--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'],
@@ -125,7 +125,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--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-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--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', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index ab833507bb..cec4765863 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -58,6 +58,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'abandoned_threads',
'atom_provenance_drift',
'captured_facts_active',
+ 'conversation_outcomes_stale',
'connector_checkpoints',
'connector_held_items',
'git_held_files',
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index ea6ebf7a32..6a99f2afd2 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -51,7 +51,9 @@ import { readJournalLimits } from '../persistence/limits.ts';
import { principalKey } from '../persistence/model.ts';
import { PERSISTENCE_IPC_MAX_BYTES } from '../persistence/ipc.ts';
import { assertManagedFactsEmbedding, resolveManagedFactsEmbedding } from '../persistence/facts-maintenance.ts';
-import { submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { loadConfig } from '../config.ts';
import { waitForWrite, writeResponse } from '../persistence/service.ts';
import { catalogueError } from '../error-catalogue.ts';
import { CONVERSATION_EXTRACTOR_VERSION, NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUDIT_SOURCE } from './audit-sources.ts';
@@ -235,13 +237,17 @@ function freezeRow(row: ConversationFactRow): FrozenConversationFact {
export async function buildConversationIntent(engine: BrainEngine, config: GBrainConfig, start: { generation: Generation },
rows: ConversationFactRow[], opts: { complete: boolean; newestEnd: string | null; visibility: 'private' | 'world' }): Promise<ConversationFactsIntent> {
const { generation } = start;
- const embedded = rows.some(row => row.embedding);
+ // Vectors freeze only under the brain's current facts embedding signature; any other
+ // vector is dropped and its row is embedded later, as an unembedded fact is.
+ const signature = rows.some(row => row.embedding) ? await resolveManagedFactsEmbedding(engine, config) : null;
+ const keep = (row: ConversationFactRow) => !!signature && !!row.embedding && row.embedding.length === signature.dimensions
+ && (!row.embedding_model || row.embedding_model === signature.model);
return {
kind: CONVERSATION_FACTS_INTENT, protocol: CONVERSATION_FACTS_PROTOCOL, expected_revision: generation.revision,
page_id: generation.pageId, version_token: generation.input.versionToken, extractor_version: CONVERSATION_EXTRACTOR_VERSION,
generation: generation.key, selectors: { since: generation.input.since, segment_limit: generation.input.segmentLimit },
complete: opts.complete, newest_end: opts.newestEnd, visibility: opts.visibility,
- embedding: embedded ? await resolveManagedFactsEmbedding(engine, config) : null, rows: rows.map(freezeRow),
+ embedding: signature, rows: rows.map(row => freezeRow(keep(row) ? { ...row, embedding_model: signature!.model } : { ...row, embedding: null })),
};
}
@@ -255,7 +261,7 @@ export async function submitConversationIntent(engine: BrainEngine, authority: M
const bytes = jsonBytes(intent);
if (bytes > limit) {
throw opError('request_too_large', 'The page\'s frozen fact batch exceeds the request size limit; its prior facts were kept.',
- `Page ${slug} produced a ${bytes}-byte batch, over the ${limit}-byte limit for one request, so nothing was submitted and the batch was not split. Narrow the run with --segment-limit, or raise persistence.limits.principalIntentBytes (the user's call).`);
+ `Page ${slug} produced a ${bytes}-byte batch, over the ${limit}-byte limit for one request, so nothing was submitted and the batch was not split. Narrow the run with --segment-limit, or raise persistence.limits.principal_intent_bytes (the user's call).`);
}
return submitDatabaseMaintenanceIntent(engine, authority, slug, intent, requestIdFor(start.generation.key, start.attempt));
}
@@ -361,3 +367,127 @@ export async function prepareConversationFactsPublication(engine: BrainEngine, r
newest_end: p.newest_end, extractor_version: p.extractor_version, generation: p.generation, entities_merged: merges.size };
} };
}
+
+/** A managed extraction run's publication context; null on an unmanaged brain or a dry run. */
+export interface ManagedConversationPublisher {
+ engine: BrainEngine;
+ authority: MaintenanceAuthority;
+ config: GBrainConfig;
+ /** The facts embedding signature frozen batches carry (null: no vectors). */
+ embedding: FactEmbeddingSignature | null;
+}
+
+/** The run counters a managed page publication books into. */
+export interface ManagedRunCounters {
+ pages_processed: number; pages_marked_non_extractable: number; pages_skipped_too_large: number;
+ orphan_facts_cleaned: number; facts_inserted: number; pages_pending?: number; pages_blocked?: number;
+}
+
+interface ManagedRunState {
+ managed: ManagedConversationPublisher | null;
+ segmentLimit: number;
+ factVisibility: 'private' | 'world';
+ result: ManagedRunCounters;
+}
+
+interface PageSnapshot { page: Page; versionToken: string }
+
+/**
+ * Once per run, before any model work: on a managed brain (not a dry run,
+ * which writes and registers nothing) preflight the maintenance authority,
+ * resolve the facts embedding signature and check that the planned
+ * admissions fit the writer's request capacity.
+ */
+export async function managedConversationPublisher(engine: BrainEngine, sourceId: string,
+ opts: { dryRun?: boolean; slugs?: string[]; slug?: string; limit?: number }): Promise<ManagedConversationPublisher | null> {
+ if (opts.dryRun || !await managedPersistenceEnabled(engine)) return null;
+ const authority = (await maintenancePreflight(engine, sourceId))!;
+ const config = loadConfig() ?? { engine: engine.kind };
+ await assertConversationAdmissionHeadroom(engine, authority, opts.slugs?.length ?? (opts.slug ? 1 : opts.limit ?? 1));
+ return { engine, authority, config, embedding: await resolveManagedFactsEmbedding(engine, config) };
+}
+
+/**
+ * Before any model work for one page: resolve its generation and settle it
+ * without the model when this writer already admitted a request for it
+ * (replayed, resubmitted, pending or blocked), or when its largest possible
+ * batch cannot fit one request. Returns the generation to extract into
+ * otherwise.
+ */
+export async function startManagedPage(state: ManagedRunState, snapshot: PageSnapshot, sinceIso: string | undefined, segments: number,
+): Promise<{ done: { newEndIso: string | null } } | { start: Extract<GenerationStart, { kind: 'extract' }> }> {
+ const { engine, authority, config, embedding } = state.managed!;
+ const { page } = snapshot;
+ const start = await startConversationGeneration(engine, authority, config, {
+ slug: page.slug, page, versionToken: snapshot.versionToken, since: sinceIso ?? null, segmentLimit: state.segmentLimit,
+ });
+ const log = (line: string) => process.stderr.write(`[extract-conversation-facts] ${line}\n`);
+ if (start.kind === 'extract') {
+ const planned = state.segmentLimit > 0 ? Math.min(segments, state.segmentLimit) : segments;
+ const estimate = estimateConversationIntentBytes(planned, embedding);
+ const limit = await conversationIntentByteLimit(engine);
+ if (estimate > limit) {
+ state.result.pages_skipped_too_large++;
+ log(`SKIP ${page.slug}: up to ${planned} segment(s) could freeze a ${estimate}-byte batch, over the ${limit}-byte request limit; its prior facts were kept and no model call ran. Narrow it with --slug ${page.slug} --segment-limit <n>`);
+ return { done: { newEndIso: null } };
+ }
+ await assertConversationAdmissionHeadroom(engine, authority);
+ return { start };
+ }
+ if (start.kind === 'resubmit') {
+ log(`${page.slug}: resubmitting the stored batch of this page generation (attempt ${start.attempt + 1}); no model call`);
+ await assertConversationAdmissionHeadroom(engine, authority);
+ return { done: settleManagedReceipt(state, await submitConversationIntent(engine, authority, page.slug, start, start.intent)) };
+ }
+ if (start.kind === 'settled') {
+ log(`${page.slug}: this page generation was already published; replaying its receipt, no model call`);
+ return { done: settleManagedReceipt(state, start.receipt) };
+ }
+ if (start.kind === 'pending') {
+ state.result.pages_pending = (state.result.pages_pending ?? 0) + 1;
+ log(`${page.slug}: request ${start.requestId} for this page is accepted and still pending; rerun to confirm (no model call)`);
+ return { done: { newEndIso: null } };
+ }
+ state.result.pages_blocked = (state.result.pages_blocked ?? 0) + 1;
+ log(`SKIP ${page.slug}: ${start.message}`);
+ return { done: { newEndIso: null } };
+}
+
+/** Books a committed receipt into the run's counters. */
+function settleManagedReceipt(state: ManagedRunState, receipt: Record<string, unknown>): { newEndIso: string | null } {
+ state.result.orphan_facts_cleaned += Number(receipt.deleted ?? 0);
+ state.result.facts_inserted += Number(receipt.facts_inserted ?? 0);
+ if (receipt.page_outcome === 'non_extractable') {
+ state.result.pages_marked_non_extractable++;
+ return { newEndIso: null };
+ }
+ state.result.pages_processed++;
+ return { newEndIso: typeof receipt.newest_end === 'string' ? receipt.newest_end : null };
+}
+
+/**
+ * Publishes one page's frozen batch as a receipted request. Returns the fact
+ * rows inserted, or null when the request is accepted but still pending after
+ * the job's wait (the page stays unfinished; the rerun replays it).
+ */
+export async function publishManagedBatch(state: ManagedRunState, snapshot: PageSnapshot,
+ start: Extract<GenerationStart, { kind: 'extract' }>, rows: ConversationFactRow[], newestEnd: string | null): Promise<number | null> {
+ const { engine, authority, config } = state.managed!;
+ const complete = rows.some(row => OUTCOME_SOURCES.has(row.source));
+ const intent = await buildConversationIntent(engine, config, start, rows, { complete, newestEnd, visibility: state.factVisibility });
+ try {
+ const receipt = await submitConversationIntent(engine, authority, snapshot.page.slug, start, intent);
+ state.result.orphan_facts_cleaned += Number(receipt.deleted ?? 0);
+ return Number(receipt.facts_inserted ?? 0);
+ } catch (error) {
+ if (!(error instanceof OperationError) || error.code !== 'write_pending') throw error;
+ state.result.pages_pending = (state.result.pages_pending ?? 0) + 1;
+ process.stderr.write(`[extract-conversation-facts] ${snapshot.page.slug}: its facts were accepted and are still pending; rerun to confirm (the rerun replays them, no model call)\n`);
+ return null;
+ }
+}
+
+/** Managed admission backpressure and exhausted request ids stop the whole run, not one page. */
+export function stopsRun(err: unknown): boolean {
+ return err instanceof OperationError && (err.code === 'maintenance_backpressure' || err.code === 'queue_capacity');
+}
diff --git a/test/conversation-facts-managed.test.ts b/test/conversation-facts-managed.test.ts
new file mode 100644
index 0000000000..e27e069eb2
--- /dev/null
+++ b/test/conversation-facts-managed.test.ts
@@ -0,0 +1,284 @@
+/**
+ * Wave 9 follow-ups, item 1: managed conversation facts publish as receipted
+ * `managed_maintenance_conversation_facts` requests with a generation identity.
+ *
+ * Protects: a crash after admission replays the stored batch with zero model
+ * calls; a deterministic failure blocks the page generation (one model call
+ * across three runs); --force and a partial-then-full run start a new
+ * generation; the frozen batch round-trips every column through JSONB; an
+ * embedding model change without a dimension change is refused, and the
+ * retry extracts again; a recreated page refuses the stale batch; a lost
+ * insert fails the publication; the intent-bytes, outstanding-request and
+ * lifetime-id bounds stop before any model call. Runs on PGLite, and on
+ * Postgres through test/e2e/conversation-facts-managed-postgres.test.ts.
+ * Seams: the Core's injected extractor (no gateway), the persistence fault
+ * hook (to stall publication) and the maintenance wait test seam.
+ */
+import { afterEach, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { ExtractedFact } from '../src/core/facts/extract.ts';
+import { runExtractConversationFactsCore, currentConversationVersionToken } from '../src/commands/extract-conversation-facts.ts';
+import { CONVERSATION_FACTS_INTENT, buildConversationIntent, replaceConversationFacts, startConversationGeneration,
+ submitConversationIntent } from '../src/core/facts/conversation-publication.ts';
+import { CONVERSATION_EXTRACTOR_VERSION, outcomeExtractorVersion } from '../src/core/facts/audit-sources.ts';
+import { maintenancePreflight } from '../src/core/persistence/prepared-maintenance.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { exitCodeForCode } from '../src/core/error-catalogue.ts';
+import { conversationOutcomesStaleCheck } from '../src/commands/doctor/checks/conversation-outcomes.ts';
+import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const SLUG = 'meetings/2026-09-28-plan-sync';
+const transcript = (extra = '') => [
+ '---', 'title: Plan sync', 'type: meeting', 'date: 2026-09-28', '---',
+ '**Alice Example:** Can you send me the quarterly plan before the review?',
+ '**Owner Example:** Yes, I will send it on Thursday with the finance appendix.',
+ '**Alice Example:** Good. I review plans on Mondays, so that works.',
+ `**Owner Example:** I will flag any launch date changes in the summary.${extra}`, '',
+].join('\n');
+
+afterEach(() => { installFaultHook(undefined); });
+
+async function putPage(brain: ManagedBrain, content: string, slug = SLUG): Promise<void> {
+ const current = await brain.engine.readPageSnapshot(slug, { sourceId: 'default' });
+ await submitPageMutation(brain.ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content,
+ ...(current ? { expected_revision: current.revision } : {}) } });
+ // The consumer keeps the config it started with; the extraction's own requests start a fresh one under the CLI config.
+ await disposePersistenceConsumer(brain.engine);
+}
+
+/** One extraction run on the page with a counting extractor; `fact` shapes the returned fact. */
+async function extract(engine: BrainEngine, calls: { n: number }, opts: { force?: boolean; segmentLimit?: number; fact?: Partial<ExtractedFact> } = {}) {
+ return runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [SLUG], sleepMs: 0, overrideDisabled: true,
+ force: opts.force, segmentLimit: opts.segmentLimit,
+ extractor: async () => {
+ calls.n++;
+ return [{ fact: 'Owner Example sends the quarterly plan on Thursday', kind: 'commitment', confidence: 0.9, entity_slug: null,
+ source: 'test', notability: 'high', ...opts.fact } as ExtractedFact];
+ } });
+}
+
+async function extractorRows(engine: BrainEngine) {
+ return engine.executeRaw<Record<string, any>>(`SELECT id, fact, kind, source, source_session, context, row_num, visibility, notability, confidence,
+ claim_metric, claim_value, claim_unit, claim_period, event_type, attributed_to, valid_from, embedding_model, embedding IS NOT NULL AS embedded
+ FROM facts WHERE source_id='default' AND source_markdown_slug=$1 AND source LIKE 'cli:extract-conversation-facts%' ORDER BY row_num`, [SLUG]);
+}
+
+async function requests(engine: BrainEngine) {
+ return engine.executeRaw<{ state: string; error_code: string | null }>(
+ "SELECT state, error_code FROM persistence_requests WHERE intent->>'kind'=$1 ORDER BY sequence", [CONVERSATION_FACTS_INTENT]);
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test(`${backend}: a transcript's facts and outcome commit in one receipted request; the frozen batch round-trips through JSONB`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ await putPage(brain, transcript());
+ await engine.setConfig('embedding_disabled', 'false');
+ const dims = Number(await engine.getConfig('embedding_dimensions') ?? 1536);
+ const vector = Float32Array.from({ length: dims }, (_, i) => ((i % 7) - 3) / 10);
+ const calls = { n: 0 };
+ const result = await extract(engine, calls, { fact: { claim_metric: 'plan_pages', claim_value: 12.5, claim_unit: 'pages', claim_period: 'quarterly',
+ event_type: 'meeting', attributed_to: 'user', embedding: vector, embedding_model: await engine.getConfig('embedding_model') ?? null,
+ valid_from: new Date('2026-09-28T10:00:00Z') } });
+ expect(result).toMatchObject({ pages_processed: 1, facts_inserted: 1, pages_failed: 0 });
+ expect(calls.n).toBe(1);
+ const rows = await extractorRows(engine);
+ expect(rows.map(r => r.fact)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);
+ expect(rows[0]).toMatchObject({ kind: 'commitment', source: 'cli:extract-conversation-facts', notability: 'high', claim_metric: 'plan_pages',
+ claim_unit: 'pages', claim_period: 'quarterly', event_type: 'meeting', attributed_to: 'user', embedded: true, row_num: 0 });
+ expect(Number(rows[0]!.claim_value)).toBe(12.5);
+ expect(Number(rows[0]!.confidence)).toBeCloseTo(0.9, 5);
+ expect(new Date(rows[0]!.valid_from).toISOString()).toBe('2026-09-28T10:00:00.000Z');
+ expect(outcomeExtractorVersion(rows[1]!.context)).toBe(CONVERSATION_EXTRACTOR_VERSION);
+ expect(await requests(engine)).toEqual([{ state: 'committed', error_code: null }]);
+ const [{ n }] = await engine.executeRaw<{ n: number }>(`SELECT count(DISTINCT write_request_id)::int AS n FROM facts
+ WHERE source_id='default' AND source_markdown_slug=$1`, [SLUG]);
+ expect(n).toBe(1);
+ expect((await conversationOutcomesStaleCheck(engine, ['default'])).status).toBe('ok');
+ }, { databaseUrl });
+ }, 120_000);
+
+ test(`${backend}: a crash after admission replays the stored batch with zero model calls`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ await putPage(brain, transcript());
+ let release!: () => void;
+ const stalled = new Promise<void>(resolve => { release = resolve; });
+ installFaultHook(async point => { if (point === 'consumer:prepared') await stalled; });
+ const restore = __setMaintenanceWriteWaitForTests(300);
+ const calls = { n: 0 };
+ try {
+ const first = await extract(engine, calls);
+ expect(first).toMatchObject({ pages_pending: 1, facts_inserted: 0 });
+ expect(calls.n).toBe(1);
+ __setMaintenanceWriteWaitForTests(20_000);
+ setTimeout(release, 300);
+ const second = await extract(engine, calls);
+ expect(second).toMatchObject({ pages_processed: 1, facts_inserted: 1 });
+ expect(calls.n).toBe(1);
+ } finally { release(); restore(); }
+ expect((await extractorRows(engine)).map(r => r.fact)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);
+ expect((await requests(engine)).map(r => r.state)).toEqual(['committed']);
+ const third = await extract(engine, calls);
+ expect(third).toMatchObject({ pages_skipped_completed: 1 });
+ expect(calls.n).toBe(1);
+ }, { databaseUrl });
+ }, 120_000);
+
+ test(`${backend}: a deterministic apply failure makes exactly one model call across three runs`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ await putPage(brain, transcript());
+ const calls = { n: 0 };
+ const bad = { kind: 'not-a-kind' } as unknown as Partial<ExtractedFact>;
+ const first = await extract(engine, calls, { fact: bad });
+ expect(first.pages_failed).toBe(1);
+ const second = await extract(engine, calls, { fact: bad });
+ const third = await extract(engine, calls, { fact: bad });
+ expect(calls.n).toBe(1);
+ expect(second).toMatchObject({ pages_blocked: 1, pages_failed: 0 });
+ expect(third).toMatchObject({ pages_blocked: 1 });
+ expect(await requests(engine)).toEqual([{ state: 'failed', error_code: 'invalid_params' }]);
+ expect(await extractorRows(engine)).toEqual([]);
+ // The page changes: a new generation extracts again.
+ await putPage(brain, transcript(' Thanks.'));
+ const fourth = await extract(engine, calls);
+ expect(fourth).toMatchObject({ pages_processed: 1, facts_inserted: 1 });
+ expect(calls.n).toBe(2);
+ }, { databaseUrl });
+ }, 120_000);
+
+ test(`${backend}: --force and a partial-then-full run each start a new generation`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ // 32 turns: two segments (DEFAULT_SEGMENT_MAX_MESSAGES is 30).
+ const turns = Array.from({ length: 32 }, (_, i) => `**${i % 2 ? 'Owner' : 'Alice'} Example:** Turn ${i + 1} about the quarterly plan.`);
+ await putPage(brain, ['---', 'title: Plan sync', 'type: meeting', 'date: 2026-09-28', '---', ...turns, ''].join('\n'));
+ const calls = { n: 0 };
+ const partial = await extract(engine, calls, { segmentLimit: 1 });
+ expect(partial).toMatchObject({ pages_processed: 1, segments_processed: 1, facts_inserted: 1 });
+ expect(calls.n).toBe(1);
+ // A committed partial batch is not a completed page: no outcome row.
+ expect((await extractorRows(engine)).map(r => r.fact)).toEqual(['Owner Example sends the quarterly plan on Thursday']);
+ const full = await extract(engine, calls);
+ expect(full).toMatchObject({ pages_processed: 1, segments_processed: 2 });
+ expect(calls.n).toBe(3);
+ expect((await extractorRows(engine)).map(r => r.fact).at(-1)).toBe('EXTRACTION_COMPLETE');
+ expect((await extract(engine, calls)).pages_skipped_completed).toBe(1);
+ expect(calls.n).toBe(3);
+ const forced = await extract(engine, calls, { force: true });
+ expect(forced).toMatchObject({ pages_processed: 1, segments_processed: 2 });
+ expect(calls.n).toBe(5);
+ expect((await requests(engine)).map(r => r.state)).toEqual(['committed', 'committed', 'committed']);
+ }, { databaseUrl });
+ }, 120_000);
+
+ test(`${backend}: an embedding model change without a dimension change is refused, and the retry extracts again`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ await putPage(brain, transcript());
+ await engine.setConfig('embedding_disabled', 'false');
+ const authority = (await maintenancePreflight(engine, 'default'))!;
+ const page = (await engine.getPage(SLUG, { sourceId: 'default' }))!;
+ const versionToken = await currentConversationVersionToken(engine, page);
+ const start = await startConversationGeneration(engine, authority, brain.ctx.config, { slug: SLUG, page, versionToken, since: null, segmentLimit: 0 });
+ if (start.kind !== 'extract') throw new Error(`unexpected generation state ${start.kind}`);
+ const dims = Number(await engine.getConfig('embedding_dimensions') ?? 1536);
+ const intent = await buildConversationIntent(engine, { engine: engine.kind }, start, [{ fact: 'A vector claim', kind: 'fact',
+ source: 'cli:extract-conversation-facts', row_num: 0, source_markdown_slug: SLUG, embedding: new Float32Array(dims).fill(0.1) }],
+ { complete: false, newestEnd: null, visibility: 'private' });
+ expect(intent.embedding).toMatchObject({ dimensions: dims });
+ const model = await engine.getConfig('embedding_model');
+ await engine.setConfig('embedding_model', 'openai:text-embedding-other-example');
+ try {
+ const error = await submitConversationIntent(engine, authority, SLUG, start, intent).then(() => null, (e: Error & { code?: string }) => e);
+ expect(error?.code).toBe('embedding_configuration');
+ } finally { await engine.setConfig('embedding_model', model!); }
+ const retry = await startConversationGeneration(engine, authority, brain.ctx.config, { slug: SLUG, page, versionToken, since: null, segmentLimit: 0 });
+ expect(retry).toMatchObject({ kind: 'extract', attempt: 1 });
+ expect(await extractorRows(engine)).toEqual([]);
+ }, { databaseUrl });
+ }, 120_000);
+
+ test(`${backend}: a page recreated at the same slug refuses the stale batch`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ await putPage(brain, transcript());
+ const authority = (await maintenancePreflight(engine, 'default'))!;
+ const page = (await engine.getPage(SLUG, { sourceId: 'default' }))!;
+ const versionToken = await currentConversationVersionToken(engine, page);
+ const start = await startConversationGeneration(engine, authority, brain.ctx.config, { slug: SLUG, page, versionToken, since: null, segmentLimit: 0 });
+ if (start.kind !== 'extract') throw new Error(`unexpected generation state ${start.kind}`);
+ const intent = await buildConversationIntent(engine, { engine: engine.kind }, start, [{ fact: 'A stale claim', kind: 'fact',
+ source: 'cli:extract-conversation-facts', row_num: 0, source_markdown_slug: SLUG }], { complete: false, newestEnd: null, visibility: 'private' });
+ const live = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ await submitPageMutation(brain.ctx, { operation: 'delete_page', params: { slug: SLUG, expected_revision: live.revision, request_id: randomUUID() } });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("DELETE FROM pages WHERE source_id='default' AND slug=$1", [SLUG]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await disposePersistenceConsumer(engine);
+ await putPage(brain, transcript());
+ const error = await submitConversationIntent(engine, authority, SLUG, start, intent).then(() => null, (e: Error & { code?: string }) => e);
+ expect(['revision_conflict', 'page_identity_changed']).toContain(error?.code ?? 'none');
+ expect(await extractorRows(engine)).toEqual([]);
+ }, { databaseUrl });
+ }, 120_000);
+
+ test(`${backend}: the intent-bytes, outstanding-request and lifetime-id bounds stop before any model call`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ await putPage(brain, transcript());
+ await putPage(brain, transcript().replace('Plan sync', 'Plan sync two'), 'meetings/2026-09-29-plan-sync');
+ const calls = { n: 0 };
+ // Intent bytes: one segment's largest batch cannot fit.
+ await engine.setConfig('persistence.limits.principal_intent_bytes', '20000');
+ const tooLarge = await extract(engine, calls);
+ expect(tooLarge).toMatchObject({ pages_skipped_too_large: 1, facts_inserted: 0 });
+ expect(calls.n).toBe(0);
+ await engine.executeRaw("DELETE FROM config WHERE key='persistence.limits.principal_intent_bytes'");
+ // Lifetime ids: no headroom refuses before the run.
+ const authority = (await maintenancePreflight(engine, 'default'))!;
+ const [used] = await engine.executeRaw<{ n: number }>("SELECT COALESCE(max(lifetime_ids),0)::int AS n FROM persistence_counters WHERE key LIKE 'principal:%'");
+ await engine.setConfig('persistence.limits.principal_lifetime_ids', String(used!.n));
+ const lifetime = await extract(engine, calls).then(() => null, (e: Error & { code?: string }) => e);
+ expect(lifetime?.code).toBe('queue_capacity');
+ expect(calls.n).toBe(0);
+ await engine.executeRaw("DELETE FROM config WHERE key='persistence.limits.principal_lifetime_ids'");
+ // Outstanding: with one request pending, a limit of 2 (80% = 1) stops admitting the next page.
+ await engine.setConfig('persistence.limits.principal_outstanding', '2');
+ let release!: () => void;
+ const stalled = new Promise<void>(resolve => { release = resolve; });
+ installFaultHook(async point => { if (point === 'consumer:prepared') await stalled; });
+ const restore = __setMaintenanceWriteWaitForTests(300);
+ try {
+ const pending = await extract(engine, calls);
+ expect(pending.pages_pending).toBe(1);
+ expect(calls.n).toBe(1);
+ const stopped = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: ['meetings/2026-09-29-plan-sync'], sleepMs: 0,
+ overrideDisabled: true, extractor: async () => { calls.n++; return []; } }).then(() => null, (e: Error & { code?: string }) => e);
+ expect(stopped?.code).toBe('maintenance_backpressure');
+ expect(exitCodeForCode('maintenance_backpressure')).toBe(12);
+ expect(calls.n).toBe(1);
+ } finally { release(); restore(); }
+ expect(authority.writer.principal.kind).toBe('local_cli');
+ }, { databaseUrl });
+ }, 120_000);
+}
+
+test('a lost insert fails the replacement instead of committing a partial batch', async () => {
+ const tx = {
+ executeRaw: async (sql: string) => sql.includes('DELETE') ? [{ count: '2' }] : [{ n: null }],
+ insertFacts: async () => ({ inserted: 1, ids: [1], warnings: [], deleted: 0 }),
+ } as unknown as BrainEngine;
+ const error = await replaceConversationFacts(tx, 'default', SLUG, [
+ { fact: 'one', source: 'cli:extract-conversation-facts' }, { fact: 'two', source: 'cli:extract-conversation-facts' },
+ ]).then(() => null, (e: Error & { code?: string }) => e);
+ expect(error?.code).toBe('storage_error');
+});
diff --git a/test/e2e/conversation-facts-managed-postgres.test.ts b/test/e2e/conversation-facts-managed-postgres.test.ts
new file mode 100644
index 0000000000..951503532c
--- /dev/null
+++ b/test/e2e/conversation-facts-managed-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../conversation-facts-managed.test.ts'));