Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(facts): batched conversation-facts receipts (Decision 9: batching, no migration)
time-attack07b6f80e2bed
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 73e63dab67..5685cedf0d 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -7,7 +7,7 @@ src/core/extract-takes-from-pages.ts 0 coordinator Managed bootstrap submits onesrc/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 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 3 coordinator The managed conversation-facts preparer clears the page's extractor rows (deleting them, but expiring rows an open loop or another fact's superseded_by references and keeping rows a label repair retired) 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. The unmanaged extractor's cleanup runs the same clear in its maintenance transaction.+src/core/facts/conversation-publication.ts 3 coordinator The managed conversation-facts preparer clears the page's extractor rows (deleting them, but expiring rows an open loop or another fact's superseded_by references and keeping rows a label repair retired) and inserts each member page's frozen entry inside the coordinator publication of its admitted managed_maintenance_conversation_facts batch request, after rechecking authority, page identity, revision and version token under each page key (a moved page is skipped and reported, never failing the batch); a lost insert rolls the publication back. The unmanaged extractor's cleanup runs the same clear in its maintenance transaction.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.@@ -204,7 +204,7 @@ src/core/persistence/connector-path.ts 1 coordinator Connector path clear lockssrc/core/source-delete.ts 1 engine_guard Unmanaged source delete with its incarnation binding; managed brains route removal through source lifecycle first and the writer guard refuses a direct delete.src/core/repair/extractor-facts.ts 1 coordinator `gbrain repair extractor-facts` (#5731) clears expired_at on preview-approved conversation-extractor facts and gives each a fresh row number. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_extractor_facts publication (withCoordinatedWrite, page key locked, each fact reclassified first); an unmanaged brain runs the same function in one transaction under the page lock.src/core/repair/captured-facts.ts 1 coordinator `gbrain repair captured-facts` expires preview-approved capture-lane facts that have no fence row. On a managed brain the UPDATE runs only inside the managed_maintenance_expire_captured_facts publication (owner-checked by maintenancePreflight, page key locked); an unmanaged brain runs it in one transaction. Fenced rows are never updated here: they are struck in the page and expired by the canonical projection of a revision-bound put_page.-src/core/repair/conversation-labels.ts 4 coordinator `gbrain repair conversation-labels` expires preview-approved label-misattributed conversation facts, expires the page completion marker and writes the not-extractable outcome, under the page key: one database-only managed_maintenance_conversation_label_retire request per page on a managed brain (the preparer reclassifies under the lock), one maintenanceTransaction on an unmanaged brain.+src/core/repair/conversation-labels.ts 4 coordinator `gbrain repair conversation-labels` expires preview-approved label-misattributed conversation facts, expires the page completion marker and writes the not-extractable outcome, under the page key: one database-only managed_maintenance_conversation_label_retire request per batch of up to 25 pages on a managed brain (the preparer reclassifies each page under its lock), one maintenanceTransaction per batch on an unmanaged brain.src/core/persistence/atom-maintenance.ts 1 coordinator A managed atom retirement stamps retired_by/retired_at on the tombstone inside the coordinator publication of its managed_atom_delete request, after the page deletion path removed the canonical file, so the database row and file change commit or roll back together.src/core/repair/stale-atoms.ts 2 coordinator gbrain repair stale-atoms retires an atom on a managed brain through a managed_maintenance_retire_stale_atoms coordinated request (the marker stamp runs in its publication); only an unmanaged brain soft-deletes and stamps in a direct page-locked transaction, where no canonical writer enforcement applies.src/core/repair/frontmatter.ts 2 coordinator `gbrain repair frontmatter --apply` (#5988) publishes a managed source's repaired file only through submitManagedFileRepair (the managed_file_repair request, preview-hash bound). On an unmanaged (legacy) source it writes the previewed bytes after a backup, moves a renamed page with updateSlug and its source_path in one maintenanceTransaction, then imports the file through importFromFile; no canonical writer enforcement applies there.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 11e0d4c966..005cf10474 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -23,7 +23,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core PersDerived 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` — `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 admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the whole planned run and again before each page. 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/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure or three failed batches block it; all without model calls. The batch request id digests its members' (generation, attempt) pairs. The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `replaceConversationFacts` deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the entry 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/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 43e913e9c3..e086336316 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.-- `src/core/repair/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; one database-only `managed_maintenance_conversation_label_retire` request per page on a managed brain (`prepareConversationLabelRetirement`), one transaction otherwise. No model calls. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.+- `src/core/repair/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; approved pages apply in batches of `LABEL_BATCH_PAGES` (25): one database-only `managed_maintenance_conversation_label_retire` request per batch on `LABELS_ANCHOR_SLUG` on a managed brain (`prepareConversationLabelRetirement`, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command. The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`).diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsvindex a1fa5cc6ef..bc87068529 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/muteop 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 publish per page as receipted managed_maintenance_conversation_facts requests after a maintenance preflight.+cli src/commands/extract-conversation-facts.ts coordinator Bulk conversation facts publish in batches of pages 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/guides/repair.md b/docs/guides/repair.mdindex 3d28f6a019..4bed2b2da3 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -530,9 +530,11 @@ Retired facts are expired, not deleted: each keeps its id and gains`retired: conversation-labels <hash>` in its context, recall stops returningit, and a later extraction, its orphan cleanup and `gbrain repairextractor-facts` leave it alone. To bring a page's facts back, re-extract the-page with the commands above. On a managed brain each page publishes one-database-only `managed_maintenance_conversation_label_retire` request; a rerun-after a crash skips pages whose request already committed. A non-interactive+page with the commands above. Pages apply in batches of up to 25: on a+managed brain each batch publishes one database-only+`managed_maintenance_conversation_label_retire` request (one receipt for the+batch, each page rechecked on its own), and a rerun after a crash skips+batches whose request already committed. A non-interactiveapply without `--yes` exits 3 with the consent payload and changes nothing;`preview_changed` means the hash names no saved preview, the preview is olderthan 7 days, or the apply's `--source` or `--include-ambiguous` differs fromdiff --git a/docs/w9f/F.md b/docs/w9f/F.mdindex dd00cd4630..dde44f6c2c 100644--- a/docs/w9f/F.md+++ b/docs/w9f/F.md@@ -40,6 +40,11 @@ Integrator notes for the release PR (no version stamped).## Notes+- Approved pages apply in batches of up to 25 (one request and one receipt+ per batch on a managed brain, one transaction per batch otherwise), each+ page rechecked on its own under its lock; the apply reports one `retired`+ outcome per batch with per-page outcomes in its detail.+- Under a live `gbrain serve` on PGLite the lock refusal is already immediate(`acquireLock` throws `LiveServeLockError` without waiting), and the fatalCLI seam's fix is the stop → rerun → restart plan; the test pins it for thisdiff --git a/docs/w9f/R.md b/docs/w9f/R.mdindex 9cda1a7525..9c2cea8a52 100644--- a/docs/w9f/R.md+++ b/docs/w9f/R.md@@ -7,12 +7,15 @@ 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.+ requests (`managed_maintenance_conversation_facts`), batched across pages:+ one request carries up to 25 pages (at most 10 with extracted facts, at+ most 8 MiB), and every page's facts and outcome row commit in the same+ transaction as that receipt. A page that changed while the batch was being+ built is skipped and reported inside the batch; the rest publish. A crash+ after the request was accepted replays the stored batch on the next run+ without calling the model again; a failed batch is resubmitted from its+ stored pages; a page whose rows can never publish, or that sat in three+ failed batches, is blocked until it changes.- Managed brains now extract facts from email threads, and record singleemails, prose meeting notes and undated pages as "not extractable" for goodinstead of rescanning them every run.@@ -51,45 +54,45 @@ measurement.- 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, stored intent dropped at compaction) | fact batch avg 128 KB (5 rows, 1536-dim vectors), outcome-only 1.5 KB | - | - | per request well under `principalIntentBytes` (32 MiB) |-| Reserved receipt bytes (until compaction, 30-day window) | 16,384 B flat, whatever the payload | 16 MiB | 781 MiB | 51% of `principalTerminalBytes` (1,536 MiB) |-| Retained receipt bytes (after compaction) | about 1.75 KB (1,743 B outcome-only, 1,754 B fact batch) | 1.7 MB | 87 MB | about 5.5% of `principalTerminalBytes`, long-term |--Breakdown (second run, same corpus, receipts force-compacted;-`~/.capy/work/w9f-r/scratch/measure-d9b.test.ts`, output-`~/.capy/work/w9f-r/out/d9-breakdown.json`): 50 of the 200 requests (25%)-were outcome-only (prose; no vectors) and 150 (75%) carried fact batches.-Request ids and reserved receipt bytes are charged per request, not per-payload byte, so each request type's share of the 20% and the 51% equals its-share of requests. Vectors only affect intent bytes.--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. The writer is the local CLI-principal the user's own CLI writes share, and outcome-only pages cost $0, so-no spend cap limits them; `maintenance_backpressure` therefore also stops at-80% of reserved receipt bytes and request ids. Per Decision 9 (A) this wave-keeps outcomes as receipted facts rows; the threshold is crossed, so batching-vs 9B (a non-guarded outcome side table) is Garry's call.+## Decision 9: measured request volume (batched; Garry chose batching, no migration)++Run: 200 managed conversation pages on PGLite, three facts per segment with+1536-dimension vectors, injected extractor (no model calls), default caps+(25 pages, 10 fact pages, 8 MiB per request), receipts then force-compacted.+Script: `~/.capy/work/w9f-r/scratch/measure-d9c.test.ts` (not committed);+outputs `~/.capy/work/w9f-r/out/d9-batched-1.json` (25% outcome-only) and+`d9-batched-3.json` (75% outcome-only). The 50k column scales the 200-page+run linearly.++| 50k pages | Before batching (one request per page) | Batched, 25% outcome-only | Batched, 75% outcome-only |+|---|---|---|---|+| Requests (permanent request ids) | 50,000 (20% of `principalLifetimeIds`) | 3,750 (1.5%) | 2,000 (0.8%) |+| Reserved receipt bytes, 30-day window | 781 MiB (51% of `principalTerminalBytes`) | 61 MB (3.8%) | 33 MB (2.0%) |+| Retained receipt bytes after compaction | 87 MB (5.5%) | 17 MB (1.1%) | 14 MB (0.9%) |+| Intent per request | 128 KB fact page, 1.5 KB outcome-only | avg 1.6 MB, max 1.6 MB | avg 1.2 MB, max 1.4 MB |++The fact-page cap (10 per request) sets the request count: 150 fact pages+made 15 requests in the 25% run, 50 fact pages and 150 outcome-only pages+made 8 in the 75% run. A batch receipt keeps one result per member+(about 150 bytes each), so a compacted batch receipt keeps about 4.6 KB.+Both mixes are now well under Decision 9's 10% switch threshold. The+`maintenance_backpressure` stop at 80% of reserved receipt bytes and request+ids stays, and the up-front check counts the run's planned batches (pages+over 10).++Before batching, for the record: request ids and reserved receipt bytes were+charged per request (16,384 B flat), so each request type's share of the 20%+and 51% equalled its share of pages; a compacted per-page receipt kept about+1.75 KB.## 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+sites; a managed page is enqueued and counted when its batch publishes),+`runExtractConversationFactsCore` (preflight line, run-stop errors in the two+page loops, the final batch flush before the checkpoint and on the error+path), `runExtractConversationFacts` (aggregate and print thetwo counters), `terminalAuditFact`/`nonExtractableAuditFact` (versionstamp); new `currentConversationVersionToken`; removed `replacePageFacts`.The managed logic lives in `src/core/facts/conversation-publication.ts`.diff --git a/llms-full.txt b/llms-full.txtindex 6750f770b6..0739472840 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -11517,9 +11517,11 @@ Retired facts are expired, not deleted: each keeps its id and gains`retired: conversation-labels <hash>` in its context, recall stops returningit, and a later extraction, its orphan cleanup and `gbrain repairextractor-facts` leave it alone. To bring a page's facts back, re-extract the-page with the commands above. On a managed brain each page publishes one-database-only `managed_maintenance_conversation_label_retire` request; a rerun-after a crash skips pages whose request already committed. A non-interactive+page with the commands above. Pages apply in batches of up to 25: on a+managed brain each batch publishes one database-only+`managed_maintenance_conversation_label_retire` request (one receipt for the+batch, each page rechecked on its own), and a rerun after a crash skips+batches whose request already committed. A non-interactiveapply without `--yes` exits 3 with the consent payload and changes nothing;`preview_changed` means the hash names no saved preview, the preview is olderthan 7 days, or the apply's `--source` or `--include-ambiguous` differs fromdiff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex ef81da0eb2..2e01aefca3 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -77,7 +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 { clearConversationFacts, managedConversationPublisher, publishManagedBatch, startManagedPage, stopsRun, type ManagedConversationPublisher } from '../core/facts/conversation-publication.ts';+import { clearConversationFacts, enqueueManagedPage, flushManagedBatch, managedConversationPublisher, 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';@@ -1063,9 +1063,10 @@ async function processPage(: 'fewer than two eligible messages');if (await snapshotIsCurrent(state.engine, state.sourceId, snapshot)) {if (state.managed) {+ // Counted when its batch publishes.const managed = await startManagedPage(state, snapshot, sinceIso, 0);- if ('done' in managed) return managed.done;- if (await publishManagedBatch(state, snapshot, managed.start, [nonExtractableAuditFact(page.slug, 0, snapshot.versionToken, reason)], null) === null) return { newEndIso: null };+ if ('start' in managed) await enqueueManagedPage(state, snapshot, managed.start, [nonExtractableAuditFact(page.slug, 0, snapshot.versionToken, reason)], 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);@@ -1239,11 +1240,8 @@ async function processPage(return { newEndIso: null };}- if (managed && newestEnd !== null) {- const inserted = await publishManagedBatch(state, snapshot, managed.start, managedRows, newestEnd);- if (inserted === null) return { newEndIso: null };- state.result.facts_inserted += pageInsertedTotal = inserted;- }+ // A managed page is counted, and its checkpoint set, when its batch publishes.+ if (managed && newestEnd !== null) { await enqueueManagedPage(state, snapshot, managed.start, managedRows, newestEnd); return { newEndIso: null }; }if (newestEnd !== null) {// v0.41.15.0 (codex #5/#6): per-page atomic checkpoint write. Mutate@@ -1616,7 +1614,8 @@ export async function runExtractConversationFactsCore(}}- // Final checkpoint flush.+ // The last partial batch publishes before the final checkpoint flush.+ await flushManagedBatch(state);if (!dryRun) {await recordCompleted(engine, checkpointKey(sourceId), cpMapToEntries(state.cpMap));}@@ -1643,6 +1642,7 @@ export async function runExtractConversationFactsCore(}}} catch (err) {+ await flushManagedBatch(state, { afterError: true }); // spent model work still publishesif (err instanceof BudgetExhausted) {Object.assign(result, { budget_exhausted: true, budget_reason: err.reason, budget_model: err.modelId });if (err.pricing) result.budget_pricing = err.pricing;diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.tsindex 8425be7d02..ec0c1d782f 100644--- a/src/core/facts/conversation-publication.ts+++ b/src/core/facts/conversation-publication.ts@@ -1,37 +1,51 @@/**- * Receipted publication of one conversation page's derived facts on a managed- * brain (wave 9 follow-ups, item 1).+ * Receipted publication of conversation pages' derived facts on a managed+ * brain (wave 9 follow-ups, item 1), batched across pages (Decision 9:+ * batching, no migration).** `gbrain extract-conversation-facts` replaces a page's* `cli:extract-conversation-facts*` rows with a fresh batch: the facts the* model extracted plus the page outcome (EXTRACTION_COMPLETE or- * EXTRACTION_NOT_APPLICABLE). On a managed brain that batch is frozen into a- * database-only `managed_maintenance_conversation_facts` request, so every- * row change commits in the same transaction as its receipt.+ * EXTRACTION_NOT_APPLICABLE). On a managed brain each page's batch is frozen+ * into a page entry, and one database-only `managed_maintenance_conversation_facts`+ * request carries the entries of up to BATCH_CAPS.pages pages (at most+ * BATCH_CAPS.factPages with extracted facts, at most BATCH_CAPS.bytes of+ * intent), so every row change commits in the same transaction as its+ * receipt while one request id and one receipt reservation cover many pages.+ * The request sits on ANCHOR_SLUG, a slug no page can hold (a dot-led+ * segment), so no single member page's revision gates the whole batch; the+ * member pages' keys are locked with it.*- * Generation identity. A request belongs to one logical extraction+ * Generation identity. A page entry belongs to one logical extraction* generation, keyed by the intent protocol, the source incarnation, the page* id, its revision and parser-input version token (sidecar bytes included),* the extractor version (`CONVERSATION_EXTRACTOR_VERSION`), the selectors* (`--since`, `--segment-limit`) and the page's newest extractor row id (so* every committed batch, an approved repair or `--force` after a commit- * starts the next generation). Request ids are `(generation, attempt)`- * digests under the caller's principal, so:- * - a crash after admission replays the stored batch: the rerun finds the- * accepted request and waits for it, with zero model calls;- * - a retryable failure (lock, claim loss, owner change) resubmits the- * stored batch under the next attempt, still with zero model calls;- * - a deterministic failure (validation, authorization, size) blocks the- * generation: no model call until the page changes;- * - at most MAX_GENERATION_ATTEMPTS requests are admitted per generation.- * A committed batch without an outcome row (a `--segment-limit` run that did- * not reach the last segment) is not a completed page.+ * starts the next generation). A batch's request id is the digest of its+ * members' (generation, attempt) pairs. Before a page's model work the run+ * consults the writer's unsettled and failed batch requests (loaded once per+ * run; compacted ones drop out):+ * - a member of a still-unsettled batch (a crash after admission) waits for+ * it and replays its receipt, with zero model calls;+ * - a member of a batch that failed retryably is resubmitted from the stored+ * entry in the next batch, still with zero model calls;+ * - a member of a batch that failed deterministically (validation,+ * authorization, size), or of MAX_GENERATION_ATTEMPTS failed batches, is+ * blocked: no model call until the page changes.+ * Under the lock each member is rechecked on its own: a page that was+ * deleted, replaced, or whose revision or version token moved is skipped and+ * reported in the receipt (the next run extracts it again); a page whose rows+ * fail validation is blocked by a durable not-extractable outcome naming the+ * reason. Neither fails the batch. A committed partial entry (no outcome row)+ * is not a completed page.** Apply re-pins source, page slug, source prefix and visibility from the* request, rechecks authority, page identity, revision and version token,- * the embedding signature and entity merges (a slug that became an alias- * moves to its canonical page), allocates row numbers under the page lock,- * and fails the request when an insert is lost.+ * the embedding signature (vectors under another signature are dropped, the+ * rows embedded later like any unembedded fact) and entity merges, allocates+ * row numbers under the page lock, and fails the request when an insert is+ * lost.*/import type { BrainEngine, NewFact } from '../engine.ts';import type { GBrainConfig } from '../config.ts';@@ -46,25 +60,36 @@ import { opError, OperationError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import { authorizeStoredRequest, authorizeWrite } from '../persistence/authority.ts';import { digest, jsonBytes } from '../persistence/digest.ts';-import { getWriteRequest } from '../persistence/journal.ts';+import { getWriteRequestById } from '../persistence/journal.ts';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 { resolveManagedFactsEmbedding } from '../persistence/facts-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 { waitForWrite } 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';+import { CONVERSATION_EXTRACTOR_VERSION, NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUDIT_SOURCE, stampExtractorVersion } from './audit-sources.ts';import { ALLOWED_TYPES, pageTypesForAllowed, type AllowedType } from './conversation-types.ts';export const CONVERSATION_FACTS_INTENT = 'managed_maintenance_conversation_facts';export const CONVERSATION_FACTS_PROTOCOL = 1;export const CONVERSATION_FACTS_SOURCE_PREFIX = 'cli:extract-conversation-facts';+/** The request slug of every conversation-facts batch: a dot-led segment, which no page slug may have. */+export const ANCHOR_SLUG = '.maintenance/conversation-facts';export const MAX_GENERATION_ATTEMPTS = 3;/** Admission stops once the principal's outstanding requests, reserved receipt bytes or request ids reach this share of their limit. */export const OUTSTANDING_ADMISSION_SHARE = 0.8;+/** Pages per batch request: at most `pages`, at most `factPages` carrying extracted facts, at most `bytes` of intent. */+export const DEFAULT_BATCH_CAPS = Object.freeze({ pages: 25, factPages: 10, bytes: 8 * 1024 * 1024 });+let batchCaps: { pages: number; factPages: number; bytes: number } = { ...DEFAULT_BATCH_CAPS };+/** Test seam: smaller batch caps (null restores the defaults). Returns the restore function. */+export function __setConversationBatchCapsForTests(caps: Partial<{ pages: number; factPages: number; bytes: number }> | null): () => void {+ const previous = batchCaps;+ batchCaps = caps ? { ...DEFAULT_BATCH_CAPS, ...caps } : { ...DEFAULT_BATCH_CAPS };+ return () => { batchCaps = previous; };+}/** Facts per segment the extractor returns at most (extractFactsFromTurn's default maxFactsPerTurn). */const MAX_FACTS_PER_SEGMENT = 10;/** Upper bound for one frozen row without its vector: claim, context, provenance and JSON overhead. */@@ -72,26 +97,27 @@ const ROW_BYTES = 4096;/** One embedding dimension as JSON text ("-0.012345678901234567,"). */const DIMENSION_BYTES = 24;-/** Request error codes that fail the same way on every retry of one generation. */+/** Request error codes that fail the same way on every retry. */const DETERMINISTIC_CODES = new Set(['invalid_params', 'permission_denied', 'request_too_large', 'payload_too_large']);-/** Retryable codes whose stored batch is stale: the next attempt extracts again. */+/** Retryable codes whose stored entries are stale: the next attempt extracts again. */const REEXTRACT_CODES = new Set(['embedding_configuration', 'revision_conflict', 'page_identity_changed', 'page_not_found']);const OUTCOME_SOURCES = new Set([TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE]);export type ConversationFactRow = NewFact & { row_num: number; source_markdown_slug: string };-/** A frozen row: no source, page or row number (the request pins them) and no visibility (one per batch). */+/** A frozen row: no source, page or row number (the request pins them) and no visibility (one per entry). */export type FrozenConversationFact = Omit<FrozenExtractedFact, 'visibility' | 'entity_inferred'>;-export interface ConversationFactsIntent extends Record<string, unknown> {- kind: typeof CONVERSATION_FACTS_INTENT;- protocol: number;- expected_revision: string;+/** One page's frozen batch inside a batch request. */+export interface ConversationPageEntry {+ slug: string;page_id: number;+ expected_revision: string;version_token: string;extractor_version: number;generation: string;+ attempt: number;selectors: { since: string | null; segment_limit: number };- /** True when the batch carries the page outcome (EXTRACTION_COMPLETE / EXTRACTION_NOT_APPLICABLE). */+ /** True when the entry carries the page outcome (EXTRACTION_COMPLETE / EXTRACTION_NOT_APPLICABLE). */complete: boolean;/** The checkpoint end of the newest extracted segment, echoed in the receipt. */newest_end: string | null;@@ -100,43 +126,33 @@ export interface ConversationFactsIntent extends Record<string, unknown> {rows: FrozenConversationFact[];}-export interface ConversationGenerationInput {- slug: string;- page: Page;- versionToken: string;- since: string | null;- segmentLimit: number;+export interface ConversationFactsIntent extends Record<string, unknown> {+ kind: typeof CONVERSATION_FACTS_INTENT;+ protocol: number;+ expected_revision: null;+ pages: ConversationPageEntry[];}-interface Generation { key: string; revision: string; pageId: number; input: ConversationGenerationInput }--export type GenerationStart =- /** No admitted request for this generation yet (or a retry that must extract again): model work runs. */- | { kind: 'extract'; generation: Generation; attempt: number }- /** A retryable failure left a stored batch: resubmit it under `attempt`, with no model call. */- | { kind: 'resubmit'; generation: Generation; attempt: number; intent: ConversationFactsIntent }- /** An admitted request already settled (committed, or replayed after a crash): no model call. */- | { kind: 'settled'; receipt: Record<string, unknown> }- /** Still pending after the job's wait: unfinished, retried next run. */- | { kind: 'pending'; requestId: string }- /** A deterministic failure or the attempt cap: no model call until the page changes. */- | { kind: 'blocked'; requestId: string; code: string; message: string };--function requestIdFor(generationKey: string, attempt: number): string {- const h = digest([generationKey, attempt]);- return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+/** One member's result in a committed batch receipt. */+export interface ConversationPageResult {+ slug: string;+ generation: string;+ status: 'committed' | 'skipped' | 'blocked';+ reason?: string;+ deleted: number;+ facts_inserted: number;+ page_outcome: 'complete' | 'non_extractable' | null;+ newest_end: string | null;}+export interface Generation { key: string; revision: string; pageId: number }+const receiptFix = (requestId: string) => readFix('Reads the conversation facts request\'s durable receipt: its state, outcome and recorded error, read-only.',{ argv: ['gbrain', 'write-request', '--', requestId] });-/**- * Before any model work for one page: resolve its generation and find what- * this principal already admitted for it. Throws `revision_conflict` when the- * page moved since the caller read it.- */-export async function startConversationGeneration(engine: BrainEngine, authority: MaintenanceAuthority,- config: GBrainConfig, input: ConversationGenerationInput): Promise<GenerationStart> {+/** The page's generation as it is now; throws `revision_conflict` when it moved since the caller read it. */+export async function conversationGeneration(engine: BrainEngine, authority: MaintenanceAuthority,+ input: { slug: string; page: Page; versionToken: string; since: string | null; segmentLimit: number }): Promise<Generation> {const sourceId = authority.writer.sourceId;const snapshot = await engine.readPageSnapshot(input.slug, { sourceId });if (!snapshot || snapshot.page.id !== input.page.id || snapshot.page.knowledge_revision !== input.page.knowledge_revision) {@@ -149,48 +165,55 @@ export async function startConversationGeneration(engine: BrainEngine, authorityconst key = digest(['conversation-facts', CONVERSATION_FACTS_PROTOCOL, authority.writer.sourceIncarnation, snapshot.page.id,snapshot.revision, input.versionToken, CONVERSATION_EXTRACTOR_VERSION, input.since, input.segmentLimit,base?.id == null ? null : Number(base.id)]);- const generation: Generation = { key, revision: snapshot.revision, pageId: snapshot.page.id, input };- let reuse: ConversationFactsIntent | null = null;- for (let attempt = 0; attempt < MAX_GENERATION_ATTEMPTS; attempt++) {- const requestId = requestIdFor(key, attempt);- const prior = await getWriteRequest(engine, authority.writer.principal, requestId);- if (!prior) return reuse ? { kind: 'resubmit', generation, attempt, intent: reuse } : { kind: 'extract', generation, attempt };- if (!isTerminal(prior)) {- await authorizeStoredRequest(engine, prior);- const wait = authority.wait!;- const row = wait.observe(await waitForWrite(engine, prior, config, wait.ms()));- if (!isTerminal(row)) return { kind: 'pending', requestId };- if (row.state === 'committed') return { kind: 'settled', receipt: writeResponse(row) };- reuse = null;- if (!classifyFailure(row, attempt)) return blocked(row, requestId);- if (!REEXTRACT_CODES.has(row.error_code ?? '')) reuse = storedIntent(row);- continue;- }- if (prior.state === 'committed') return { kind: 'settled', receipt: writeResponse(prior) };- if (!classifyFailure(prior, attempt)) return blocked(prior, requestId);- reuse = REEXTRACT_CODES.has(prior.error_code ?? '') ? null : storedIntent(prior);- }- const last = requestIdFor(key, MAX_GENERATION_ATTEMPTS - 1);- return { kind: 'blocked', requestId: last, code: 'attempts_exhausted',- message: `${MAX_GENERATION_ATTEMPTS} requests for this page generation ended without committing; no model call runs again until the page changes. Read the last receipt: gbrain write-request -- ${last}` };+ return { key, revision: snapshot.revision, pageId: snapshot.page.id };}-/** True when the failed request may be retried under the next attempt. */-function classifyFailure(row: WriteRequest, attempt: number): boolean {- return attempt + 1 < MAX_GENERATION_ATTEMPTS && !DETERMINISTIC_CODES.has(row.error_code ?? '');+function batchRequestId(sourceIncarnation: string, pages: ReadonlyArray<Pick<ConversationPageEntry, 'generation' | 'attempt'>>): string {+ const h = digest(['conversation-facts-batch-v1', sourceIncarnation, pages.map(p => `${p.generation}:${p.attempt}`).sort()]);+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;}-function blocked(row: WriteRequest, requestId: string): GenerationStart {- const code = row.error_code ?? row.state;- return { kind: 'blocked', requestId, code,- message: `request ${requestId} ended ${row.state} (${code}) for this page generation, so no model call runs again until the page changes. Read the receipt: gbrain write-request -- ${requestId}` };+/** What this writer's unsettled and failed batch requests say about one generation. */+interface GenerationHistory {+ /** An admitted batch that has not settled yet. */+ pending: { id: string; attempt: number } | null;+ /** Failed batches holding this generation: their row id, error code and the member's attempt. */+ failed: Array<{ id: string; requestId: string; code: string; attempt: number }>;}-function storedIntent(row: WriteRequest): ConversationFactsIntent | null {- const intent = row.intent as ConversationFactsIntent | null;- return !row.compacted && intent?.kind === CONVERSATION_FACTS_INTENT && Array.isArray(intent.rows) ? intent : null;+/**+ * The writer's unsettled and failed (not yet compacted) conversation-facts+ * batches of this source, by member generation. One read per run: the+ * request slug is the anchor, so only these batches are read, and only their+ * members' keys leave the database.+ */+export async function loadGenerationIndex(engine: BrainEngine, authority: MaintenanceAuthority): Promise<Map<string, GenerationHistory>> {+ const rows = await engine.executeRaw<{ id: string; request_id: string; state: string; error_code: string | null; members: Array<{ generation: string; attempt: number }> | null }>(+ `SELECT r.id::text AS id, r.request_id::text AS request_id, r.state, r.error_code,+ (SELECT jsonb_agg(jsonb_build_object('generation', p->>'generation', 'attempt', (p->>'attempt')::int)) FROM jsonb_array_elements(r.intent->'pages') p) AS members+ FROM persistence_requests r+ WHERE r.principal_kind=$1 AND r.principal_id=$2 AND r.source_id=$3 AND r.slug=$4 AND r.operation='submit_job'+ AND r.state<>'committed' AND NOT r.compacted+ ORDER BY r.sequence`,+ [authority.writer.principal.kind, authority.writer.principal.id, authority.writer.sourceId, ANCHOR_SLUG]);+ const index = new Map<string, GenerationHistory>();+ for (const row of rows) {+ for (const member of row.members ?? []) {+ const history = index.get(member.generation) ?? { pending: null, failed: [] };+ if (!isTerminal(row as unknown as WriteRequest)) history.pending = { id: row.id, attempt: Number(member.attempt) };+ else history.failed.push({ id: row.id, requestId: row.request_id, code: row.error_code ?? row.state, attempt: Number(member.attempt) });+ index.set(member.generation, history);+ }+ }+ return index;}+/** The stored entry of `generation` in the failed batch `id`, for a resubmission without model work. */+async function storedEntry(engine: BrainEngine, id: string, generation: string): Promise<ConversationPageEntry | null> {+ const [row] = await engine.executeRaw<{ entry: ConversationPageEntry | null }>(`SELECT p AS entry FROM persistence_requests r, jsonb_array_elements(r.intent->'pages') p+ WHERE r.id=$1::uuid AND NOT r.compacted AND p->>'generation'=$2 LIMIT 1`, [id, generation]);+ return row?.entry && Array.isArray(row.entry.rows) ? row.entry : null;+}/** The largest frozen batch `segments` segments can produce, in intent bytes. */export function estimateConversationIntentBytes(segments: number, embedding: FactEmbeddingSignature | null): number {const perRow = ROW_BYTES + (embedding ? embedding.dimensions * DIMENSION_BYTES : 0);@@ -209,8 +232,8 @@ export async function conversationIntentByteLimit(engine: BrainEngine): Promise<* OUTSTANDING_ADMISSION_SHARE of their limit. The writer is the local CLI* principal the user's own CLI writes share, so the last 20% stays theirs:* reserved receipt bytes free only when receipts compact (after the retention- * window), request ids never. `needed` is the run's planned admissions up- * front, 1 before each page.+ * window), request ids never. `needed` is the run's planned batch requests+ * up front, 1 before each new batch; the suggested `--limit` is in pages.*/export async function assertConversationAdmissionHeadroom(engine: BrainEngine, authority: MaintenanceAuthority, needed = 1): Promise<void> {const limits = await readJournalLimits(engine);@@ -235,7 +258,7 @@ export async function assertConversationAdmissionHeadroom(engine: BrainEngine, afor (const r of cumulative) {const ceiling = share(r.limit);if (r.used + needed * r.per <= ceiling) continue;- const room = Math.max(0, Math.floor((ceiling - r.used) / r.per));+ const room = Math.max(0, Math.floor((ceiling - r.used) / r.per)) * batchCaps.factPages;const planned = needed > 1 ? `${needed} planned` : 'the next';throw catalogueError('maintenance_backpressure',`Conversation fact extraction stopped before admitting ${planned} request(s): this writer's ${r.resource} would pass 80% of its limit (${r.used} used of ${r.limit}).`,@@ -245,13 +268,15 @@ export async function assertConversationAdmissionHeadroom(engine: BrainEngine, a}/**- * The admissions a run plans: the named pages, or every page of the- * conversation types (`opts.types`, else all) that has no active outcome yet- * (`--force`: every such page), capped by `--limit`.+ * The batch requests a run plans: its pages (the named pages, or every page+ * of the conversation types, `opts.types` else all, that has no active+ * outcome yet; `--force`: every such page; capped by `--limit`), counted as+ * fact pages, BATCH_CAPS.factPages per request.*/async function plannedAdmissions(engine: BrainEngine, sourceId: string,opts: { slugs?: string[]; slug?: string; limit?: number; force?: boolean; types?: readonly AllowedType[] }): Promise<number> {- if (opts.slugs) return opts.slugs.length;+ const requests = (pages: number) => Math.max(1, Math.ceil(pages / batchCaps.factPages));+ if (opts.slugs) return requests(opts.slugs.length);if (opts.slug) return 1;const [row] = await engine.executeRaw<{ n: number | string }>(`SELECT count(*)::int AS n FROM pages pWHERE p.source_id=$1 AND p.deleted_at IS NULL AND p.type=ANY($2::text[])@@ -259,7 +284,7 @@ async function plannedAdmissions(engine: BrainEngine, sourceId: string,AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' AND f.source IN ($4,$5) AND f.expired_at IS NULL))`,[sourceId, pageTypesForAllowed(opts.types ?? ALLOWED_TYPES), opts.force === true, TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE]);const backlog = Number(row?.n ?? 0);- return Math.max(1, opts.limit ? Math.min(opts.limit, backlog) : backlog);+ return requests(opts.limit ? Math.min(opts.limit, backlog) : backlog);}function freezeRow(row: ConversationFactRow): FrozenConversationFact {@@ -274,65 +299,78 @@ function freezeRow(row: ConversationFactRow): FrozenConversationFact {};}-/** Builds the frozen intent for one generation attempt. */-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;++/** Freezes one page's rows into its entry for one generation attempt. */+export async function buildConversationPage(engine: BrainEngine, config: GBrainConfig,+ input: { slug: string; generation: Generation; attempt: number; versionToken: string; since: string | null; segmentLimit: number },+ rows: ConversationFactRow[], opts: { newestEnd: string | null; visibility: 'private' | 'world' }): Promise<ConversationPageEntry> {// 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: signature, rows: rows.map(row => freezeRow(keep(row) ? { ...row, embedding_model: signature!.model } : { ...row, embedding: null })),+ slug: input.slug, page_id: input.generation.pageId, expected_revision: input.generation.revision, version_token: input.versionToken,+ extractor_version: CONVERSATION_EXTRACTOR_VERSION, generation: input.generation.key, attempt: input.attempt,+ selectors: { since: input.since, segment_limit: input.segmentLimit }, complete: rows.some(row => OUTCOME_SOURCES.has(row.source)),+ newest_end: opts.newestEnd, visibility: opts.visibility, embedding: signature,+ rows: rows.map(row => freezeRow(keep(row) ? { ...row, embedding_model: signature!.model } : { ...row, embedding: null })),};}/**- * Submits one generation attempt and returns its committed receipt. A- * request still pending after the job's wait throws `write_pending`.+ * Submits one batch request carrying `pages` and returns its committed+ * receipt (`pages`: one ConversationPageResult per member). A request still+ * pending after the job's wait throws `write_pending`.*/-export async function submitConversationIntent(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,- start: { generation: Generation; attempt: number }, intent: ConversationFactsIntent): Promise<Record<string, unknown>> {+export async function submitConversationPages(engine: BrainEngine, authority: MaintenanceAuthority, pages: ConversationPageEntry[]): Promise<Record<string, unknown>> {+ const intent: ConversationFactsIntent = { kind: CONVERSATION_FACTS_INTENT, protocol: CONVERSATION_FACTS_PROTOCOL, expected_revision: null, pages };const limit = await conversationIntentByteLimit(engine);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.principal_intent_bytes (the user's call).`);+ throw opError('request_too_large', 'The frozen fact batch exceeds the request size limit; the pages\' prior facts were kept.',+ `The batch of ${pages.map(p => p.slug).join(', ')} is ${bytes} bytes, over the ${limit}-byte limit for one request, so nothing was submitted. 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));+ return submitDatabaseMaintenanceIntent(engine, authority, ANCHOR_SLUG, intent, batchRequestId(authority.writer.sourceIncarnation, pages));}function invalid(row: WriteRequest, cause: string): OperationError {return opError('invalid_params', 'The conversation facts request is malformed.',- `Request ${row.request_id} for ${row.slug} in source ${row.source_id} ${cause}, so nothing changed. Run gbrain extract-conversation-facts --source-id ${row.source_id} --slug ${row.slug} again; a new page generation submits a fresh batch.`,+ `Request ${row.request_id} in source ${row.source_id} ${cause}, so nothing changed. Run gbrain extract-conversation-facts --source-id ${row.source_id} again; its pages submit fresh batches.`,{ fix: receiptFix(row.request_id) });}+/** The batch envelope; a malformed envelope fails the whole request (deterministic). */function validateIntent(row: WriteRequest): ConversationFactsIntent {const p = row.intent as ConversationFactsIntent | null;if (!p || p.kind !== CONVERSATION_FACTS_INTENT || p.protocol !== CONVERSATION_FACTS_PROTOCOL) throw invalid(row, 'carries a protocol this gbrain version does not publish (likely queued by another release)');- if (!Array.isArray(p.rows) || typeof p.version_token !== 'string' || typeof p.generation !== 'string' || Number(p.page_id) !== Number(row.page_id)) {- throw invalid(row, 'does not name its page, version and rows');+ if (row.slug !== ANCHOR_SLUG || row.page_id !== null || !Array.isArray(p.pages) || !p.pages.length) throw invalid(row, 'does not carry a batch of pages');+ const slugs = p.pages.map(entry => entry?.slug);+ if (slugs.some(slug => typeof slug !== 'string' || !slug || slug === ANCHOR_SLUG) || new Set(slugs).size !== slugs.length) throw invalid(row, 'names a page twice or names no page');+ return p;+}++/** Why one member's frozen rows cannot be published, or null when they can. Deterministic: a retry fails the same way. */+function entryProblem(entry: ConversationPageEntry): string | null {+ if (!Array.isArray(entry.rows) || typeof entry.version_token !== 'string' || typeof entry.generation !== 'string' || !Number.isSafeInteger(Number(entry.page_id))) {+ return 'the entry does not name its page, version and rows';}- if (p.visibility !== 'private' && p.visibility !== 'world') throw invalid(row, 'names an unknown fact visibility');- const outcomes = p.rows.filter(fact => OUTCOME_SOURCES.has(fact.source));- if (outcomes.length !== (p.complete ? 1 : 0)) throw invalid(row, p.complete ? 'does not carry exactly one page outcome' : 'carries a page outcome in a partial batch');- for (const fact of p.rows) {+ if (entry.visibility !== 'private' && entry.visibility !== 'world') return 'it names an unknown fact visibility';+ const outcomes = entry.rows.filter(fact => OUTCOME_SOURCES.has(fact.source));+ if (outcomes.length !== (entry.complete ? 1 : 0)) return entry.complete ? 'it does not carry exactly one page outcome' : 'it carries a page outcome in a partial batch';+ for (const fact of entry.rows) {if (typeof fact.fact !== 'string' || !fact.fact.trim() || typeof fact.source !== 'string' || !fact.source.startsWith(CONVERSATION_FACTS_SOURCE_PREFIX)|| !ALL_FACT_KINDS.includes((fact.kind ?? 'fact') as never) || (fact.source_session != null && !String(fact.source_session).startsWith(CONVERSATION_FACTS_SOURCE_PREFIX))|| Number.isNaN(Date.parse(fact.valid_from)) || (fact.valid_until != null && Number.isNaN(Date.parse(fact.valid_until)))) {- throw invalid(row, 'carries a row outside the conversation extractor\'s provenance');+ return 'a row falls outside the conversation extractor\'s provenance or fact kinds';+ }+ if (OUTCOME_SOURCES.has(fact.source) && fact.source_session !== `${fact.source}:${entry.slug}:${entry.version_token}`) return 'it carries an outcome for another page version';+ if (fact.embedding && (!entry.embedding || fact.embedding.length !== entry.embedding.dimensions || !fact.embedding.every(Number.isFinite))) {+ return 'a vector does not match its embedding signature';}- if (OUTCOME_SOURCES.has(fact.source) && fact.source_session !== `${fact.source}:${row.slug}:${p.version_token}`) throw invalid(row, 'carries an outcome for another page version');}- return p;+ return null;}-/** Canonical slugs for entity slugs that became aliases of a live page since extraction. */async function mergedEntities(tx: BrainEngine, sourceId: string, slugs: string[]): Promise<Map<string, string>> {if (!slugs.length) return new Map();@@ -385,47 +423,73 @@ export async function clearConversationFacts(db: BrainEngine, sourceId: string,return Number(expired?.count ?? 0) + Number(deleted?.count ?? 0);}-/** Preparer for `managed_maintenance_conversation_facts`: a database-only publication on the page key. */++type VersionTokenOf = (db: BrainEngine, page: Page) => Promise<string>;++/**+ * Under the lock, one member on its own: skipped when its page was deleted,+ * replaced or moved; blocked (a durable not-extractable outcome naming the+ * reason, prior facts kept) when its rows cannot be published; replaced+ * otherwise. Never throws for one member's state.+ */+async function applyEntry(tx: BrainEngine, row: WriteRequest, entry: ConversationPageEntry, signature: FactEmbeddingSignature | null,+ versionTokenOf: VersionTokenOf): Promise<ConversationPageResult & { vectors_dropped: number }> {+ const base = { slug: entry.slug, generation: entry.generation, deleted: 0, facts_inserted: 0, page_outcome: null, newest_end: null, vectors_dropped: 0 };+ const page = await tx.getPage(entry.slug, { sourceId: row.source_id });+ if (!page || page.id !== Number(entry.page_id)) return { ...base, status: 'skipped', reason: 'page_identity_changed' };+ const token = await versionTokenOf(tx, page);+ if (page.knowledge_revision !== entry.expected_revision || token !== entry.version_token) return { ...base, status: 'skipped', reason: 'revision_conflict' };+ const problem = entryProblem(entry);+ if (problem) {+ const [top] = await tx.executeRaw<{ n: number | string | null }>('SELECT max(row_num) AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, entry.slug]);+ const blocked: ConversationFactRow = { fact: 'EXTRACTION_NOT_APPLICABLE', kind: 'fact', entity_slug: null, source: NON_EXTRACTABLE_AUDIT_SOURCE,+ source_session: `${NON_EXTRACTABLE_AUDIT_SOURCE}:${entry.slug}:${token}`, confidence: 1.0, notability: 'low',+ context: stampExtractorVersion(`scanned, not extractable: blocked: ${problem} (request ${row.request_id})`),+ row_num: top?.n == null ? 0 : Number(top.n) + 1, source_markdown_slug: entry.slug };+ const { inserted } = await tx.insertFacts([blocked], { source_id: row.source_id }); // gbrain-allow-direct-insert: the durable blocked outcome of a conversation page whose frozen rows failed validation, inside its receipted batch publication+ if (inserted !== 1) throw opError('storage_error', 'A blocked conversation outcome was not written; the batch rolled back.',+ `Request ${row.request_id} could not record that ${entry.slug} in source ${row.source_id} is blocked, so none of its pages changed. Run the extraction again; report this if it repeats.`,+ { fix: receiptFix(row.request_id) });+ return { ...base, status: 'blocked', reason: problem, page_outcome: 'non_extractable' };+ }+ const vectors = !!signature && !!entry.embedding && signature.model === entry.embedding.model && signature.dimensions === entry.embedding.dimensions;+ const merges = await mergedEntities(tx, row.source_id, entry.rows.map(fact => fact.entity_slug).filter((s): s is string => !!s));+ const rows = entry.rows.map(fact => ({+ ...fact, visibility: entry.visibility, entity_slug: fact.entity_slug ? merges.get(fact.entity_slug) ?? fact.entity_slug : null,+ valid_from: new Date(fact.valid_from), valid_until: fact.valid_until ? new Date(fact.valid_until) : null,+ embedding: vectors && fact.embedding ? new Float32Array(fact.embedding) : null,+ embedding_model: vectors && fact.embedding ? entry.embedding!.model : null,+ }));+ const { deleted } = await replaceConversationFacts(tx, row.source_id, entry.slug, rows);+ const outcome = entry.rows.find(fact => OUTCOME_SOURCES.has(fact.source));+ return { ...base, status: 'committed', deleted, facts_inserted: rows.filter(fact => !OUTCOME_SOURCES.has(fact.source)).length,+ page_outcome: outcome ? (outcome.source === TERMINAL_AUDIT_SOURCE ? 'complete' : 'non_extractable') : null, newest_end: entry.newest_end,+ vectors_dropped: vectors ? 0 : entry.rows.filter(fact => fact.embedding).length };+}++/** Preparer for `managed_maintenance_conversation_facts`: a database-only batch publication holding every member's page key. */export async function prepareConversationFactsPublication(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {const p = validateIntent(row);const { currentConversationVersionToken } = await import('../../commands/extract-conversation-facts.ts');- const pageChanged = (message: string) => opError('page_identity_changed', message,- `Page ${row.slug} in source ${row.source_id} changed before its conversation facts were published, so request ${row.request_id} wrote nothing and the prior facts stay. The next extraction run reads the current page.`,- { fix: readFix(`Shows which page holds ${row.slug} now and its revision.`, { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug] }) });- const check = async (db: BrainEngine, lock: boolean) => {+ const authorize = async (db: BrainEngine) => {await authorizeWrite(db, row.authority, 'submit_job', row.slug);- const page = await db.getPage(row.slug, { sourceId: row.source_id });- if (!page || page.id !== Number(row.page_id)) throw pageChanged('The conversation page was deleted or replaced before its facts were published.');- if (page.knowledge_revision !== p.expected_revision || await currentConversationVersionToken(db, page) !== p.version_token) {- throw opError('revision_conflict', 'The conversation page changed during fact extraction; its prior facts were kept.',- `Page ${row.slug} in source ${row.source_id} changed after its facts were extracted (request ${row.request_id}), so its prior facts were kept. The next extraction run extracts from the current page.`,- { fix: receiptFix(row.request_id) });- }- if (p.rows.some(fact => fact.embedding)) {- await assertManagedFactsEmbedding(db, config, p.embedding, lock);- if (p.rows.some(fact => fact.embedding && (fact.embedding.length !== p.embedding!.dimensions || !fact.embedding.every(Number.isFinite)))) {- throw opError('embedding_configuration', 'Frozen conversation fact vectors do not match their embedding signature.',- `A vector in request ${row.request_id} is not a finite ${p.embedding!.dimensions}-dimension vector of ${p.embedding!.model}, so none of the page's facts were published. The next extraction run embeds under the current model.`,- { fix: receiptFix(row.request_id) });- }- }+ for (const entry of p.pages) await authorizeWrite(db, row.authority, 'submit_job', entry.slug);};- await check(engine, false);- return { observedRevision: p.expected_revision, noop: true,- validate: tx => check(tx, true),+ await authorize(engine);+ return { observedRevision: null, noop: true, additionalPageKeys: p.pages.map(entry => ({ sourceId: row.source_id, slug: entry.slug })),+ validate: authorize,apply: async tx => {- const merges = await mergedEntities(tx, row.source_id, p.rows.map(fact => fact.entity_slug).filter((s): s is string => !!s));- const rows = p.rows.map(fact => ({- ...fact, visibility: p.visibility, entity_slug: fact.entity_slug ? merges.get(fact.entity_slug) ?? fact.entity_slug : null,- valid_from: new Date(fact.valid_from), valid_until: fact.valid_until ? new Date(fact.valid_until) : null,- embedding: fact.embedding ? new Float32Array(fact.embedding) : null,- embedding_model: fact.embedding ? p.embedding?.model ?? null : null,- }));- const { deleted, inserted } = await replaceConversationFacts(tx, row.source_id, row.slug, rows);- const outcome = p.rows.find(fact => OUTCOME_SOURCES.has(fact.source));- return { status: 'completed', deleted, inserted, facts_inserted: rows.filter(fact => !OUTCOME_SOURCES.has(fact.source)).length,- complete: p.complete, page_outcome: outcome ? (outcome.source === TERMINAL_AUDIT_SOURCE ? 'complete' : 'non_extractable') : null,- newest_end: p.newest_end, extractor_version: p.extractor_version, generation: p.generation, entities_merged: merges.size };+ const signature = p.pages.some(entry => entry.rows?.some(fact => fact.embedding)) ? await resolveManagedFactsEmbedding(tx, config, true) : null;+ const pages: ConversationPageResult[] = [];+ let dropped = 0;+ for (const entry of p.pages) {+ const { vectors_dropped, ...result } = await applyEntry(tx, row, entry, signature, currentConversationVersionToken);+ dropped += vectors_dropped;+ pages.push(result);+ }+ const count = (status: ConversationPageResult['status']) => pages.filter(page => page.status === status).length;+ return { status: 'completed', pages, committed: count('committed'), skipped: count('skipped'), blocked: count('blocked'),+ facts_inserted: pages.reduce((n, page) => n + page.facts_inserted, 0), ...(dropped ? { vectors_dropped: dropped } : {}) };} };}@@ -434,30 +498,44 @@ export interface ManagedConversationPublisher {engine: BrainEngine;authority: MaintenanceAuthority;config: GBrainConfig;- /** The facts embedding signature frozen batches carry (null: no vectors). */+ /** The facts embedding signature frozen entries carry (null: no vectors). */embedding: FactEmbeddingSignature | null;+ /** The writer's unsettled and failed batches by member generation, read once per run. */+ index: Map<string, GenerationHistory>;+ /** Unsettled batches this run already waited for, by request row id. */+ settled: Map<string, WriteRequest>;+ /** The batch being filled, and its entries' intent bytes. */+ batch: ConversationPageEntry[];+ bytes: number;}-/** The run counters a managed page publication books into. */+/** The run counters a managed batch publication books into. */export interface ManagedRunCounters {- pages_processed: number; pages_marked_non_extractable: number; pages_skipped_too_large: number;+ pages_processed: number; pages_marked_non_extractable: number; pages_skipped_too_large: number; pages_failed: number;orphan_facts_cleaned: number; facts_inserted: number; pages_pending?: number; pages_blocked?: number;}interface ManagedRunState {managed: ManagedConversationPublisher | null;+ sourceId: string;segmentLimit: number;factVisibility: 'private' | 'world';result: ManagedRunCounters;+ /** The run's per-page checkpoint ends, keyed `${sourceId}|${slug}`. */+ cpMap: Map<string, string>;}interface PageSnapshot { page: Page; versionToken: string }+export interface ManagedPageStart { generation: Generation; attempt: number; since: string | null }++const log = (line: string) => process.stderr.write(`[extract-conversation-facts] ${line}\n`);/*** 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.+ * resolve the facts embedding signature, check that the planned batch+ * requests fit the writer's request capacity, and read its unsettled and+ * failed batches.*/export async function managedConversationPublisher(engine: BrainEngine, sourceId: string,opts: { dryRun?: boolean; slugs?: string[]; slug?: string; limit?: number; force?: boolean; types?: readonly AllowedType[] }): Promise<ManagedConversationPublisher | null> {@@ -465,89 +543,149 @@ export async function managedConversationPublisher(engine: BrainEngine, sourceIdconst authority = (await maintenancePreflight(engine, sourceId))!;const config = loadConfig() ?? { engine: engine.kind };await assertConversationAdmissionHeadroom(engine, authority, await plannedAdmissions(engine, sourceId, opts));- return { engine, authority, config, embedding: await resolveManagedFactsEmbedding(engine, config) };+ return { engine, authority, config, embedding: await resolveManagedFactsEmbedding(engine, config),+ index: await loadGenerationIndex(engine, authority), settled: new Map(), batch: [], bytes: 0 };+}++async function settledRequest(m: ManagedConversationPublisher, id: string): Promise<WriteRequest> {+ const cached = m.settled.get(id);+ if (cached) return cached;+ const prior = (await getWriteRequestById(m.engine, id))!;+ await authorizeStoredRequest(m.engine, prior);+ const wait = m.authority.wait!;+ const row = wait.observe(await waitForWrite(m.engine, prior, m.config, wait.ms()));+ m.settled.set(id, row);+ return row;}/*** 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+ * without the model when this writer already admitted it in a batch* (replayed, resubmitted, pending or blocked), or when its largest possible- * batch cannot fit one request. Returns the generation to extract into+ * entry 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!;+): Promise<{ done: { newEndIso: null } } | { start: ManagedPageStart }> {+ const m = state.managed!;const { page } = snapshot;- const start = await startConversationGeneration(engine, authority, config, {+ const done = { done: { newEndIso: null } } as const;+ const generation = await conversationGeneration(m.engine, m.authority, {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 } };+ const history = m.index.get(generation.key) ?? { pending: null, failed: [] };+ if (history.pending) {+ const row = await settledRequest(m, history.pending.id);+ if (!isTerminal(row)) {+ state.result.pages_pending = (state.result.pages_pending ?? 0) + 1;+ log(`${page.slug}: its batch request ${row.request_id} is accepted and still pending; rerun to confirm (no model call)`);+ return done;}- await assertConversationAdmissionHeadroom(engine, authority);- return { start };+ const result = row.state === 'committed' ? ((row.outcome?.pages ?? []) as ConversationPageResult[]).find(r => r.generation === generation.key) : undefined;+ if (result) {+ log(`${page.slug}: replaying its committed batch request ${row.request_id}; no model call`);+ bookPage(state, result);+ return done;+ }+ if (row.state !== 'committed') history.failed.push({ id: row.id, requestId: row.request_id, code: row.error_code ?? row.state, attempt: history.pending.attempt });+ history.pending = null;}- 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)) };+ const deterministic = history.failed.find(f => DETERMINISTIC_CODES.has(f.code));+ if (deterministic || history.failed.length >= MAX_GENERATION_ATTEMPTS) {+ const last = deterministic ?? history.failed.at(-1)!;+ state.result.pages_blocked = (state.result.pages_blocked ?? 0) + 1;+ log(`SKIP ${page.slug}: ${deterministic ? `its batch request ${last.requestId} failed (${last.code})` : `${MAX_GENERATION_ATTEMPTS} batch requests holding it failed`} at this page version, so no model call runs again until the page changes. Read the receipt: gbrain write-request -- ${last.requestId}`);+ return done;}- 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) };+ const attempt = history.failed.length ? Math.max(...history.failed.map(f => f.attempt)) + 1 : 0;+ const last = history.failed.at(-1);+ const stored = last && !REEXTRACT_CODES.has(last.code) ? await storedEntry(m.engine, last.id, generation.key) : null;+ if (!m.batch.length) await assertConversationAdmissionHeadroom(m.engine, m.authority);+ if (stored) {+ log(`${page.slug}: resubmitting its stored entry from failed batch request ${last!.requestId} (attempt ${attempt + 1}); no model call`);+ await enqueueEntry(state, { ...stored, attempt });+ return done;}- 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 } };+ const planned = state.segmentLimit > 0 ? Math.min(segments, state.segmentLimit) : segments;+ const estimate = estimateConversationIntentBytes(planned, m.embedding);+ const limit = await conversationIntentByteLimit(m.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;}- 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 };+ return { start: { generation, attempt, since: sinceIso ?? null } };+}++/** Freezes one extracted page into the run's batch; the batch publishes once a cap is reached (and at the end of the run). */+export async function enqueueManagedPage(state: ManagedRunState, snapshot: PageSnapshot, start: ManagedPageStart,+ rows: ConversationFactRow[], newestEnd: string | null): Promise<void> {+ const m = state.managed!;+ await enqueueEntry(state, await buildConversationPage(m.engine, m.config, { slug: snapshot.page.slug, generation: start.generation, attempt: start.attempt,+ versionToken: snapshot.versionToken, since: start.since, segmentLimit: state.segmentLimit }, rows, { newestEnd, visibility: state.factVisibility }));+}++async function enqueueEntry(state: ManagedRunState, entry: ConversationPageEntry): Promise<void> {+ const m = state.managed!;+ const bytes = jsonBytes(entry);+ const cap = Math.min(batchCaps.bytes, await conversationIntentByteLimit(m.engine) - 65_536);+ if (m.batch.length && m.bytes + bytes > cap) await flushManagedBatch(state);+ m.batch.push(entry);+ m.bytes += bytes;+ const factPages = m.batch.filter(e => e.rows.some(fact => !OUTCOME_SOURCES.has(fact.source))).length;+ if (m.batch.length >= batchCaps.pages || factPages >= batchCaps.factPages || m.bytes >= cap) await flushManagedBatch(state);+}++/** Books one member's committed-batch result into the run's counters. */+function bookPage(state: ManagedRunState, result: ConversationPageResult): void {+ state.result.orphan_facts_cleaned += Number(result.deleted ?? 0);+ state.result.facts_inserted += Number(result.facts_inserted ?? 0);+ if (result.status === 'skipped') {+ state.result.pages_failed++;+ log(`${result.slug} changed during extraction (${result.reason}); its prior facts were kept and it stays unfinished for the next run`);+ return;+ }+ if (result.status === 'blocked') {+ state.result.pages_blocked = (state.result.pages_blocked ?? 0) + 1;+ log(`SKIP ${result.slug}: blocked at this page version (${result.reason}); no model call runs again until the page changes`);+ return;}+ if (result.page_outcome === 'non_extractable') { state.result.pages_marked_non_extractable++; return; }state.result.pages_processed++;- return { newEndIso: typeof receipt.newest_end === 'string' ? receipt.newest_end : null };+ if (result.newest_end) state.cpMap.set(`${state.sourceId}|${result.slug}`, result.newest_end);}/**- * 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).+ * Publishes the run's current batch as one request and books each member.+ * A batch still pending after the job's wait leaves its pages pending (the+ * next run replays it, no model call); a failed batch leaves them unfinished+ * (the next run resubmits or blocks them from the stored request).*/-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 });+export async function flushManagedBatch(state: ManagedRunState, opts: { afterError?: boolean } = {}): Promise<void> {+ const m = state.managed;+ if (!m || !m.batch.length) return;+ // After a run-ending error the run's own error is the one reported; a flush failure only leaves the batch's pages unfinished.+ if (opts.afterError) return flushManagedBatch(state).catch((error: unknown) => {+ log(`the run's last batch did not publish (${error instanceof Error ? error.message : String(error)}); its pages stay unfinished`);+ });+ const pages = m.batch.splice(0);+ m.bytes = 0;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);+ const receipt = await submitConversationPages(m.engine, m.authority, pages);+ for (const result of receipt.pages as ConversationPageResult[]) bookPage(state, result);+ log(`published ${pages.length} page(s) in batch request ${String(receipt.request_id)} (${Number(receipt.committed ?? 0)} committed, ${Number(receipt.skipped ?? 0)} skipped, ${Number(receipt.blocked ?? 0)} blocked)`);} 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;+ if (!(error instanceof OperationError) || stopsRun(error)) throw error;+ const requestId = error.writeRequest?.request_id;+ if (error.code === 'write_pending') {+ state.result.pages_pending = (state.result.pages_pending ?? 0) + pages.length;+ log(`batch request ${requestId ?? ''} with ${pages.length} page(s) is accepted and still pending; rerun to confirm (the rerun replays it, no model call)`);+ return;+ }+ state.result.pages_failed += pages.length;+ log(`batch request ${requestId ?? ''} with ${pages.length} page(s) failed (${error.code}): ${error.message}; the next run ${DETERMINISTIC_CODES.has(error.code) ? 'blocks them until they change' : 'resubmits their stored entries without model calls'}`);}}-/** 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/src/core/repair/conversation-labels.ts b/src/core/repair/conversation-labels.tsindex 6960b83590..de1719f7c2 100644--- a/src/core/repair/conversation-labels.ts+++ b/src/core/repair/conversation-labels.ts@@ -59,6 +59,10 @@ import { LEGACY_TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUimport { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';export const CONVERSATION_LABELS_INTENT = 'managed_maintenance_conversation_label_retire';+/** The request slug of every label-retire batch: a dot-led segment, which no page slug may have. */+export const LABELS_ANCHOR_SLUG = '.maintenance/conversation-labels';+/** Pages per label-retire batch request (one receipt, one request id). */+export const LABEL_BATCH_PAGES = 25;const SEGMENT_SOURCE = 'cli:extract-conversation-facts';/** The default context the pre-fix extractor wrote for an undated page's segment. */export const EPOCH_SEGMENT_MARKER = 'segment 1970-01-01';@@ -86,7 +90,6 @@ export interface LabelPage {source_id: string;slug: string;page_id: number;- request_id: string;include_ambiguous: boolean;scope: string[];facts: Array<Pick<LabelFactCandidate, 'id' | 'class' | 'reason' | 'fact_hash'>>;@@ -97,7 +100,7 @@ export interface LabelPage {segments: number;}-interface PageItem extends RepairItem { page: LabelPage; hash: string; last: boolean }+interface BatchItem extends RepairItem { pages: LabelPage[]; request_id: string; hash: string; last: boolean }interface CandidateRow {id: number | string; source_id: string; slug: string; fact: string; context: string | null; entity_slug: string | null; visibility: string;@@ -166,8 +169,8 @@ async function activeMarker(db: BrainEngine, sourceId: string, slug: string): Prreturn rows.length > 0;}-function requestIdFor(hash: string, page: Pick<LabelPage, 'source_id' | 'slug'>, attempt: number): string {- const h = digest(['conversation-labels-request-v1', hash, page.source_id, page.slug, attempt]);+function requestIdFor(hash: string, pages: Array<Pick<LabelPage, 'source_id' | 'slug'>>, attempt: number): string {+ const h = digest(['conversation-labels-batch-v1', hash, pages.map(p => `${p.source_id}\u0000${p.slug}`), attempt]);return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;}@@ -195,21 +198,26 @@ export function handoffCommands(pages: Array<Pick<LabelPage, 'source_id' | 'slugreturn commands;}-function pageItem(page: LabelPage, hash: string, index: number, last: boolean): PageItem {- return { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0,- action: `retire ${page.facts.length} label-misattributed fact(s); ${page.outcome.replaceAll('_', ' ')}`, page, hash, last };+/** The approved pages as batch items: up to LABEL_BATCH_PAGES pages of one source per item, in approved order. */+function batchItems(pages: LabelPage[], hash: string): BatchItem[] {+ const batches: LabelPage[][] = [];+ for (const page of pages) {+ const open = batches.at(-1);+ if (open && open.length < LABEL_BATCH_PAGES && open[0]!.source_id === page.source_id) open.push(page); else batches.push([page]);+ }+ return batches.map((batch, index) => ({ cursor: { phase: 0, id: index + 1 }, source_id: batch[0]!.source_id, slug: batch[0]!.slug, chars: 0,+ action: `retire ${batch.reduce((n, p) => n + p.facts.length, 0)} label-misattributed fact(s) on ${batch.length} page(s)`,+ pages: batch, request_id: requestIdFor(hash, batch, 0), hash, last: index === batches.length - 1 }));}-/** Pages of an approved set whose retirement already committed (or whose facts are all expired already). */-async function finishedPages(engine: BrainEngine, hash: string, pages: LabelPage[]): Promise<Set<string>> {- if (!pages.length) return new Set();- const committed = await engine.executeRaw<{ source_id: string; slug: string }>(`SELECT DISTINCT source_id, slug FROM persistence_requests- WHERE state='committed' AND operation='submit_job' AND request_id=ANY($1::uuid[])`, [pages.map(p => p.request_id)]);+/** Batches of an approved set whose retirement already committed (or whose facts are all expired already). */+async function finishedBatches(engine: BrainEngine, items: BatchItem[]): Promise<Set<string>> {+ if (!items.length) return new Set();+ const committed = new Set((await engine.executeRaw<{ request_id: string }>(`SELECT request_id::text AS request_id FROM persistence_requests+ WHERE state='committed' AND operation='submit_job' AND request_id=ANY($1::uuid[])`, [items.map(item => item.request_id)])).map(row => row.request_id));const active = new Set((await engine.executeRaw<{ id: number | string }>('SELECT id FROM facts WHERE id=ANY($1::bigint[]) AND expired_at IS NULL',- [pages.flatMap(p => p.facts.map(f => f.id))])).map(row => Number(row.id)));- const done = new Set(committed.map(row => `${row.source_id}\u0000${row.slug}`));- for (const page of pages) if (page.facts.every(f => !active.has(f.id))) done.add(`${page.source_id}\u0000${page.slug}`);- return done;+ [items.flatMap(item => item.pages.flatMap(p => p.facts.map(f => f.id)))])).map(row => Number(row.id)));+ return new Set(items.filter(item => committed.has(item.request_id) || item.pages.every(p => p.facts.every(f => !active.has(f.id)))).map(item => item.request_id));}export const conversationLabelsRepair: RepairHandler = {@@ -229,11 +237,11 @@ export const conversationLabelsRepair: RepairHandler = {if (approved.items.some(page => page.include_ambiguous !== includeAmbiguous || JSON.stringify(page.scope) !== scopeKey)) {throw previewChangedError(opts.expect, command);}- const done = await finishedPages(engine, opts.expect, approved.items);- const items = approved.items.map((page, index) => pageItem(page, opts.expect!, index, index === approved.items.length - 1))- .filter(item => afterCursor(item.cursor, after) && !done.has(`${item.source_id}\u0000${item.slug}`));+ const all = batchItems(approved.items, opts.expect);+ const done = await finishedBatches(engine, all);+ const items = all.filter(item => afterCursor(item.cursor, after) && !done.has(item.request_id));if (!items.length) await clearApprovedSet(engine, { command: 'conversation-labels', hash: opts.expect });- return { items, preview_hash: opts.expect, residuals: { already_retired_pages: approved.items.length - items.length },+ return { items, preview_hash: opts.expect, residuals: { already_retired_pages: all.filter(item => done.has(item.request_id)).reduce((n, item) => n + item.pages.length, 0) },details: { handoff: handoffCommands(approved.items) } };}const facts = await classifyLabelFacts(engine, scope.source_ids);@@ -245,7 +253,7 @@ export const conversationLabelsRepair: RepairHandler = {if (!page) {const current = (await engine.getPage(fact.slug, { sourceId: fact.source_id }))!;const decided = await currentOutcome(engine, current);- page = { source_id: fact.source_id, slug: fact.slug, page_id: current.id, request_id: '', include_ambiguous: includeAmbiguous, scope: scope.source_ids,+ page = { source_id: fact.source_id, slug: fact.slug, page_id: current.id, include_ambiguous: includeAmbiguous, scope: scope.source_ids,facts: [], outcome: decided.reason ? 'non_extractable' : await activeMarker(engine, fact.source_id, fact.slug) ? 'awaiting_reextraction' : 'cleaned',non_extractable_reason: decided.reason, version_token: decided.versionToken, segments: decided.segments };pages.set(key, page);@@ -255,15 +263,15 @@ export const conversationLabelsRepair: RepairHandler = {const sources = await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);const hash = previewHash({ kind: 'conversation-labels-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids, include_ambiguous: includeAmbiguous },- facts, pages: [...pages.values()].map(({ request_id: _r, ...page }) => page) });- const approved = [...pages.values()].map(page => ({ ...page, request_id: requestIdFor(hash, page, 0) }));+ facts, pages: [...pages.values()] });+ const approved = [...pages.values()];if (approved.length) await saveApprovedSet(engine, { command: 'conversation-labels', hash }, approved);const count = (klass: LabelFactClass) => facts.filter(f => f.class === klass).length;const awaiting = approved.filter(p => p.outcome === 'awaiting_reextraction');const listing: RepairListing[] = facts.map(fact => ({ item: `${fact.source_id}:${fact.slug}#${fact.id}`,class: fact.class === 'excluded' ? `excluded:${fact.reason}` : fact.class, detail: DETAILS[fact.reason] ?? fact.reason }));return {- items: approved.map((page, index) => pageItem(page, hash, index, index === approved.length - 1)), preview_hash: hash, listing,+ items: batchItems(approved, hash), preview_hash: hash, listing,residuals: { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded'),non_extractable_pages: approved.filter(p => p.outcome === 'non_extractable').length, awaiting_reextraction_pages: awaiting.length,awaiting_segments: awaiting.reduce((n, p) => n + p.segments, 0) },@@ -274,16 +282,16 @@ export const conversationLabelsRepair: RepairHandler = {};},async apply(ctx, entry): Promise<RepairItemOutcome> {- const { page, hash, last } = entry as PageItem;+ const item = entry as BatchItem;const result = await managedPersistenceEnabled(ctx.engine)- ? await retireManaged(ctx.engine, ctx.config, page, hash)+ ? await retireManaged(ctx.engine, ctx.config, item): await maintenanceTransaction(ctx.engine, async tx => {- await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);- return retirePageFacts(tx, page, hash);+ await tx.lockPageKeys(item.pages.map(page => ({ sourceId: page.source_id, slug: page.slug })));+ return retireBatch(tx, item.pages, item.hash);});- if (last) await clearApprovedSet(ctx.engine, { command: 'conversation-labels', hash });+ if (item.last) await clearApprovedSet(ctx.engine, { command: 'conversation-labels', hash: item.hash });if (!result.retired.length) return { applied: false, outcome: 'changed_since_preview', reason: 'every approved fact changed since the preview' };- return { applied: true, outcome: result.outcome, detail: { retired: result.retired.length,+ return { applied: true, outcome: 'retired', detail: { retired: result.retired.length, pages: result.pages,...(result.changed.length ? { changed_since_preview: result.changed } : {}) } };},render(details) {@@ -302,31 +310,36 @@ export const conversationLabelsRepair: RepairHandler = {};interface RetireResult { retired: number[]; changed: number[]; outcome: LabelPageOutcome }+interface BatchResult { retired: number[]; changed: number[]; pages: Record<string, LabelPageOutcome | 'changed_since_preview'> }++/** Every page of one batch under its lock (the caller holds every page key). */+async function retireBatch(tx: BrainEngine, pages: LabelPage[], hash: string): Promise<BatchResult> {+ const result: BatchResult = { retired: [], changed: [], pages: {} };+ for (const page of pages) {+ const one = await retirePageFacts(tx, page, hash);+ result.retired.push(...one.retired);+ result.changed.push(...one.changed);+ result.pages[page.slug] = one.retired.length ? one.outcome : 'changed_since_preview';+ }+ return result;+}-async function retireManaged(engine: BrainEngine, config: Parameters<typeof waitForWrite>[2], page: LabelPage, hash: string): Promise<RetireResult> {- const unchanged: RetireResult = { retired: [], changed: page.facts.map(f => f.id), outcome: page.outcome };- const authority = (await maintenancePreflight(engine, page.source_id))!;+async function retireManaged(engine: BrainEngine, config: Parameters<typeof waitForWrite>[2], item: BatchItem): Promise<BatchResult> {+ const authority = (await maintenancePreflight(engine, item.source_id))!;for (let attempt = 0; ; attempt++) {- const requestId = attempt === 0 ? page.request_id : requestIdFor(hash, page, attempt);+ const requestId = attempt === 0 ? item.request_id : requestIdFor(item.hash, item.pages, attempt);const prior = await getWriteRequest(engine, authority.writer.principal, requestId);if (prior && isTerminal(prior) && prior.state !== 'committed') continue;- try {- let receipt: Record<string, unknown>;- if (prior) {- await authorizeStoredRequest(engine, prior);- receipt = writeResponse(await waitForWrite(engine, prior, config));- } else {- const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });- if (!snapshot || snapshot.page.id !== page.page_id) return unchanged;- receipt = await submitDatabaseMaintenanceIntent(engine, authority, page.slug,- { kind: CONVERSATION_LABELS_INTENT, expected_revision: snapshot.revision, preview_hash: hash, page }, requestId);- }- return { retired: (receipt.retired as number[] | undefined) ?? [], changed: (receipt.changed_since_preview as number[] | undefined) ?? [],- outcome: (receipt.page_outcome as LabelPageOutcome | undefined) ?? page.outcome };- } catch (error) {- if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return unchanged;- throw error;+ let receipt: Record<string, unknown>;+ if (prior) {+ await authorizeStoredRequest(engine, prior);+ receipt = writeResponse(await waitForWrite(engine, prior, config));+ } else {+ receipt = await submitDatabaseMaintenanceIntent(engine, authority, LABELS_ANCHOR_SLUG,+ { kind: CONVERSATION_LABELS_INTENT, expected_revision: null, preview_hash: item.hash, pages: item.pages }, requestId);}+ return { retired: (receipt.retired as number[] | undefined) ?? [], changed: (receipt.changed_since_preview as number[] | undefined) ?? [],+ pages: (receipt.pages as BatchResult['pages'] | undefined) ?? {} };}}@@ -368,28 +381,27 @@ async function retirePageFacts(tx: BrainEngine, page: LabelPage, hash: string):return result;}-/** Preparer for `managed_maintenance_conversation_label_retire`: a database-only publication on the page key. */+/** Preparer for `managed_maintenance_conversation_label_retire`: a database-only batch publication holding every page's key. */export async function prepareConversationLabelRetirement(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {- const intent = row.intent as { page?: LabelPage; preview_hash?: unknown } | null;- const page = intent?.page;- if (!page || page.source_id !== row.source_id || page.slug !== row.slug || typeof intent?.preview_hash !== 'string' || !Array.isArray(page.facts)) {- throw opError('invalid_params', 'The conversation-labels intent does not name its page.',- `Request ${row.request_id} for ${row.slug} in source ${row.source_id} does not name the page and preview it retires, so nothing changed. Preview the repair again and apply the new preview after the user approves.`,- { fix: previewFix(row.source_id) });- }- const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });- if (!snapshot || snapshot.page.id !== Number(row.page_id)) {- throw opError('page_identity_changed', 'The conversation page was deleted or replaced before its label facts were retired.',- `Conversation page ${row.slug} in source ${row.source_id} was deleted or replaced after the preview, so request ${row.request_id} retired nothing. Preview the repair again.`,+ const intent = row.intent as { pages?: LabelPage[]; preview_hash?: unknown } | null;+ const pages = intent?.pages;+ if (row.slug !== LABELS_ANCHOR_SLUG || !Array.isArray(pages) || !pages.length || typeof intent?.preview_hash !== 'string'+ || pages.some(page => page?.source_id !== row.source_id || typeof page.slug !== 'string' || !Array.isArray(page.facts))) {+ throw opError('invalid_params', 'The conversation-labels intent does not name its pages.',+ `Request ${row.request_id} in source ${row.source_id} does not name the pages and preview it retires, so nothing changed. Preview the repair again and apply the new preview after the user approves.`,{ fix: previewFix(row.source_id) });}- await authorizeWrite(engine, row.authority, 'submit_job', row.slug);+ const authorize = async (db: BrainEngine) => {+ await authorizeWrite(db, row.authority, 'submit_job', row.slug);+ for (const page of pages) await authorizeWrite(db, row.authority, 'submit_job', page.slug);+ };+ await authorize(engine);const hash = intent!.preview_hash as string;- return { observedRevision: snapshot.revision, noop: true,- validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },+ return { observedRevision: null, noop: true, additionalPageKeys: pages.map(page => ({ sourceId: row.source_id, slug: page.slug })),+ validate: authorize,apply: async tx => {- const result = await retirePageFacts(tx, page, hash);- return { status: 'completed', preview_hash: hash, retired: result.retired, changed_since_preview: result.changed, page_outcome: result.outcome };+ const result = await retireBatch(tx, pages, hash);+ return { status: 'completed', preview_hash: hash, retired: result.retired, changed_since_preview: result.changed, pages: result.pages };} };}diff --git a/test/conversation-facts-managed.test.ts b/test/conversation-facts-managed.test.tsindex 75a4057cfc..1fd00f5151 100644--- a/test/conversation-facts-managed.test.ts+++ b/test/conversation-facts-managed.test.ts@@ -2,25 +2,27 @@* 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+ * Protects: pages publish in batch requests (caps split a run into several);+ * a crash after admission replays the stored batch with zero model calls; a+ * page whose rows fail validation is blocked inside its batch (one model+ * call across three runs); a page that moved or was recreated is skipped+ * inside its batch while the rest publish; --force and a partial-then-full+ * run start a new generation; the frozen batch round-trips every column+ * through JSONB; an embedding model change drops stale vectors, never the+ * batch; a lost insert fails the publication; the intent-bytes,+ * outstanding-request, receipt-byte 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.+ * hook (to stall publication), the maintenance wait and batch-cap test seams.*/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_FACTS_INTENT, DEFAULT_BATCH_CAPS, __setConversationBatchCapsForTests, buildConversationPage, conversationGeneration,+ replaceConversationFacts, submitConversationPages } 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';@@ -41,7 +43,7 @@ const transcript = (extra = '') => [`**Owner Example:** I will flag any launch date changes in the summary.${extra}`, '',].join('\n');-afterEach(() => { installFaultHook(undefined); });+afterEach(() => { installFaultHook(undefined); __setConversationBatchCapsForTests(null); });async function putPage(brain: ManagedBrain, content: string, slug = SLUG): Promise<void> {const current = await brain.engine.readPageSnapshot(slug, { sourceId: 'default' });@@ -52,11 +54,13 @@ async function putPage(brain: ManagedBrain, content: string, slug = SLUG): Promi}/** 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,+async function extract(engine: BrainEngine, calls: { n: number }, opts: { force?: boolean; segmentLimit?: number; fact?: Partial<ExtractedFact>;+ slugs?: string[]; onCall?: (turnText: string) => Promise<void> } = {}) {+ return runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: opts.slugs ?? [SLUG], sleepMs: 0, overrideDisabled: true,force: opts.force, segmentLimit: opts.segmentLimit,- extractor: async () => {+ extractor: async ({ turnText }) => {calls.n++;+ await opts.onCall?.(turnText);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];} });@@ -68,6 +72,15 @@ async function extractorRows(engine: BrainEngine) {FROM facts WHERE source_id='default' AND source_markdown_slug=$1 AND source LIKE 'cli:extract-conversation-facts%' ORDER BY row_num`, [SLUG]);}+const PROSE = (title: string) => ['---', `title: ${title}`, 'type: meeting', 'date: 2026-09-28', '---',+ '**Date:** 2026-09-28', '**Attendees:** Alice Example, Owner Example', '', '## Notes', 'Hiring, the support backlog and the launch dates.', ''].join('\n');+const titled = (title: string) => transcript().replace('title: Plan sync', `title: ${title}`);++async function factsOf(engine: BrainEngine, slug: string) {+ return (await engine.executeRaw<{ fact: string }>(`SELECT fact FROM facts WHERE source_id='default' AND source_markdown_slug=$1+ AND source LIKE 'cli:extract-conversation-facts%' AND expired_at IS NULL ORDER BY row_num`, [slug])).map(r => r.fact);+}+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]);@@ -108,50 +121,64 @@ for (const backend of testBackends()) {test(`${backend}: a crash after admission replays the stored batch with zero model calls`, async () => {await managedBrain(async brain => {const { engine } = brain;+ const OTHER = 'meetings/2026-09-29-plan-sync';await putPage(brain, transcript());+ await putPage(brain, titled('Plan sync two'), OTHER);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);+ const first = await extract(engine, calls, { slugs: [SLUG, OTHER] });+ expect(first).toMatchObject({ pages_pending: 2, facts_inserted: 0 });+ expect(calls.n).toBe(2);__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);+ // The first page waits for the batch and replays its receipt; the second is then complete already.+ const second = await extract(engine, calls, { slugs: [SLUG, OTHER] });+ expect(second).toMatchObject({ pages_processed: 1, pages_skipped_completed: 1, facts_inserted: 1 });+ expect(calls.n).toBe(2);} finally { release(); restore(); }- expect((await extractorRows(engine)).map(r => r.fact)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);+ expect(await factsOf(engine, SLUG)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);+ expect(await factsOf(engine, OTHER)).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);+ const third = await extract(engine, calls, { slugs: [SLUG, OTHER] });+ expect(third).toMatchObject({ pages_skipped_completed: 2 });+ expect(calls.n).toBe(2);}, { databaseUrl });}, 120_000);- test(`${backend}: a deterministic apply failure makes exactly one model call across three runs`, async () => {+ test(`${backend}: a page whose rows fail validation is blocked inside its batch: one model call across three runs`, async () => {await managedBrain(async brain => {const { engine } = brain;+ const GOOD = 'meetings/2026-09-29-plan-sync';await putPage(brain, transcript());+ await putPage(brain, titled('Plan sync two'), GOOD);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([]);+ let bad = true;+ const run = () => runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [SLUG, GOOD], sleepMs: 0, overrideDisabled: true,+ extractor: async ({ turnText }) => {+ calls.n++;+ const kind = bad && !turnText.includes('Plan sync two') ? 'not-a-kind' : 'commitment';+ return [{ fact: 'Owner Example sends the quarterly plan on Thursday', kind, confidence: 0.9, entity_slug: null, source: 'test' } as unknown as ExtractedFact];+ } });+ const first = await run();+ expect(first).toMatchObject({ pages_blocked: 1, pages_processed: 1, pages_failed: 0 });+ const second = await run();+ const third = await run();+ expect(calls.n).toBe(2);+ expect(second).toMatchObject({ pages_skipped_non_extractable: 1, pages_skipped_completed: 1 });+ expect(third).toMatchObject({ pages_skipped_non_extractable: 1, pages_skipped_completed: 1 });+ expect(await requests(engine)).toEqual([{ state: 'committed', error_code: null }]);+ expect(await factsOf(engine, SLUG)).toEqual(['EXTRACTION_NOT_APPLICABLE']);+ expect((await extractorRows(engine))[0]!.context).toContain('blocked:');// The page changes: a new generation extracts again.+ bad = false;await putPage(brain, transcript(' Thanks.'));- const fourth = await extract(engine, calls);+ const fourth = await run();expect(fourth).toMatchObject({ pages_processed: 1, facts_inserted: 1 });- expect(calls.n).toBe(2);+ expect(calls.n).toBe(3);}, { databaseUrl });}, 120_000);@@ -180,7 +207,7 @@ for (const backend of testBackends()) {}, { databaseUrl });}, 120_000);- test(`${backend}: an embedding model change without a dimension change is refused, and the retry extracts again`, async () => {+ test(`${backend}: an embedding model change without a dimension change drops the stale vectors, never the batch`, async () => {await managedBrain(async brain => {const { engine } = brain;await putPage(brain, transcript());@@ -188,36 +215,32 @@ for (const backend of testBackends()) {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 generation = await conversationGeneration(engine, authority, { slug: SLUG, page, versionToken, since: null, segmentLimit: 0 });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 entry = await buildConversationPage(engine, { engine: engine.kind }, { slug: SLUG, generation, attempt: 0, versionToken, since: null, segmentLimit: 0 },+ [{ 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) }],+ { newestEnd: null, visibility: 'private' });+ expect(entry.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([]);+ let receipt: Record<string, unknown>;+ try { receipt = await submitConversationPages(engine, authority, [entry]); }+ finally { await engine.setConfig('embedding_model', model!); }+ expect(receipt).toMatchObject({ state: 'committed', committed: 1, vectors_dropped: 1 });+ expect((await extractorRows(engine)).map(r => [r.fact, r.embedded])).toEqual([['A vector claim', false]]);}, { databaseUrl });}, 120_000);- test(`${backend}: a page recreated at the same slug refuses the stale batch`, async () => {+ test(`${backend}: a page recreated at the same slug is skipped inside its 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 generation = await conversationGeneration(engine, authority, { slug: SLUG, page, versionToken, since: null, segmentLimit: 0 });+ const entry = await buildConversationPage(engine, { engine: engine.kind }, { slug: SLUG, generation, attempt: 0, versionToken, since: null, segmentLimit: 0 },+ [{ fact: 'A stale claim', kind: 'fact', source: 'cli:extract-conversation-facts', row_num: 0, source_markdown_slug: SLUG }], { 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');@@ -225,12 +248,78 @@ for (const backend of testBackends()) {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');+ const receipt = await submitConversationPages(engine, authority, [entry]);+ expect(receipt).toMatchObject({ state: 'committed', committed: 0, skipped: 1 });+ expect((receipt.pages as Array<{ reason: string }>)[0]!.reason).toBe('page_identity_changed');expect(await extractorRows(engine)).toEqual([]);}, { databaseUrl });}, 120_000);+ test(`${backend}: a mixed batch publishes every page but the one that moved, which is skipped and re-extracted next run`, async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ const MOVED = 'meetings/2026-09-29-plan-sync', LAST = 'meetings/2026-09-30-plan-sync', NOTES = 'meetings/2026-09-28-notes';+ await putPage(brain, transcript());+ await putPage(brain, titled('Plan sync two'), MOVED);+ await putPage(brain, PROSE('Planning notes'), NOTES);+ await putPage(brain, titled('Plan sync three'), LAST);+ const calls = { n: 0 };+ let edited = false;+ const first = await extract(engine, calls, { slugs: [SLUG, MOVED, NOTES, LAST], onCall: async text => {+ // MOVED's entry is already in the batch when LAST is extracted; edit it before the batch publishes.+ if (!edited && text.includes('Plan sync three')) { edited = true; await putPage(brain, titled('Plan sync two').replace('Thursday', 'Friday'), MOVED); }+ } });+ expect(edited).toBe(true);+ expect(calls.n).toBe(3);+ expect(first).toMatchObject({ pages_processed: 2, pages_marked_non_extractable: 1, pages_failed: 1, facts_inserted: 2 });+ expect((await requests(engine)).map(r => r.state)).toEqual(['committed']);+ expect(await factsOf(engine, MOVED)).toEqual([]);+ expect(await factsOf(engine, NOTES)).toEqual(['EXTRACTION_NOT_APPLICABLE']);+ const second = await extract(engine, calls, { slugs: [SLUG, MOVED, NOTES, LAST] });+ expect(second).toMatchObject({ pages_processed: 1, pages_skipped_completed: 2, pages_skipped_non_extractable: 1 });+ expect(calls.n).toBe(4);+ expect(await factsOf(engine, MOVED)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);+ }, { databaseUrl });+ }, 120_000);++ test(`${backend}: a batch that failed retryably is resubmitted from its stored entries with zero model calls`, async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ await putPage(brain, transcript());+ let fail = true;+ installFaultHook(async point => { if (point === 'consumer:prepared' && fail) { fail = false; throw Object.assign(new Error('simulated owner crash'), { code: 'storage_error' }); } });+ const calls = { n: 0 };+ const first = await extract(engine, calls);+ expect(first.pages_processed).toBe(0);+ expect(calls.n).toBe(1);+ const failed = await requests(engine);+ expect(failed.map(r => r.state)).toEqual(['failed']);+ const second = await extract(engine, calls);+ expect(second).toMatchObject({ pages_processed: 1, facts_inserted: 1 });+ expect(calls.n).toBe(1);+ expect((await requests(engine)).map(r => r.state)).toEqual(['failed', 'committed']);+ expect(await factsOf(engine, SLUG)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);+ }, { databaseUrl });+ }, 120_000);++ test(`${backend}: the batch caps split a run into several requests`, async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ expect(DEFAULT_BATCH_CAPS).toEqual({ pages: 25, factPages: 10, bytes: 8 * 1024 * 1024 });+ const slugs = ['meetings/t1', 'meetings/p1', 'meetings/t2', 'meetings/p2', 'meetings/p3'];+ for (const slug of slugs) await putPage(brain, slug.includes('/t') ? titled(`Sync ${slug}`) : PROSE(`Notes ${slug}`), slug);+ __setConversationBatchCapsForTests({ pages: 2, factPages: 1 });+ const calls = { n: 0 };+ const result = await extract(engine, calls, { slugs });+ // [t1] (fact-page cap), [p1, t2] (page cap), [p2, p3] (page cap).+ expect(result).toMatchObject({ pages_processed: 2, pages_marked_non_extractable: 3, pages_failed: 0 });+ expect((await requests(engine)).map(r => r.state)).toEqual(['committed', 'committed', 'committed']);+ const members = await engine.executeRaw<{ n: number }>(`SELECT jsonb_array_length(intent->'pages')::int AS n FROM persistence_requests+ WHERE intent->>'kind'=$1 ORDER BY sequence`, [CONVERSATION_FACTS_INTENT]);+ expect(members.map(r => r.n)).toEqual([1, 2, 2]);+ }, { 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;@@ -308,6 +397,7 @@ for (const backend of testBackends()) {await managedBrain(async brain => {const { engine } = brain;for (const day of ['28', '29', '30']) await putPage(brain, transcript().replace('Plan sync', `Plan sync ${day}`), `meetings/2026-09-${day}-plan-sync`);+ __setConversationBatchCapsForTests({ factPages: 1 });await maintenancePreflight(engine, 'default');const [{ used }] = await engine.executeRaw<{ used: number }>("SELECT COALESCE(max(lifetime_ids),0)::int AS used FROM persistence_counters WHERE key LIKE 'principal:local_cli:%'");// 80% of the limit leaves room for one admission, not the three the run plans.diff --git a/test/repair-conversation-labels.test.ts b/test/repair-conversation-labels.test.tsindex c60babfd35..3686d7616c 100644--- a/test/repair-conversation-labels.test.ts+++ b/test/repair-conversation-labels.test.ts@@ -79,7 +79,7 @@ async function seed(engine: BrainEngine): Promise<Seeded> {}interface RepairJson { results: Array<{ affected: number; residuals: Record<string, number>; apply_command: string; applied: number; warnings?: string[];- listing?: Array<{ item: string; class: string }>; outcomes?: Record<string, number>; details?: { handoff?: string[]; pages?: Array<{ slug: string; outcome: string }> } }> }+ listing?: Array<{ item: string; class: string }>; outcomes?: Record<string, number>; outcome_items?: Array<{ item: string; outcome: string; detail?: Record<string, unknown> }>; details?: { handoff?: string[]; pages?: Array<{ slug: string; outcome: string }> } }> }async function capture(run: () => Promise<unknown>): Promise<{ out: string; exitCode: number | string | undefined }> {const lines: string[] = [];@@ -138,7 +138,9 @@ async function exercise(engine: BrainEngine, managed: boolean, seeded: Seeded):expect(await active(engine, seeded.evidenced)).toEqual(sorted(seeded.evidenced));// Approved apply: no model call, approved rows expired with the marker, markers expired, prose outcome written.const applied = await repair(engine, ['--apply', '--expect', hash, '--yes']);- expect(applied.results[0]!.outcomes).toEqual({ non_extractable: 1, awaiting_reextraction: 1 });+ // Both pages apply in one batch (one request, one receipt) with their own outcomes.+ expect(applied.results[0]!.outcomes).toEqual({ retired: 1 });+ expect(applied.results[0]!.outcome_items![0]!.detail).toMatchObject({ retired: 3, pages: { [PROSE]: 'non_extractable', [DATED]: 'awaiting_reextraction' } });expect(await active(engine, seeded.evidenced)).toEqual([]);expect(await active(engine, [...seeded.ambiguous, ...seeded.excluded])).toEqual(sorted([...seeded.ambiguous, ...seeded.excluded]));const [retired] = await engine.executeRaw<{ context: string }>('SELECT context FROM facts WHERE id=$1', [seeded.evidenced[0]]);@@ -149,7 +151,7 @@ async function exercise(engine: BrainEngine, managed: boolean, seeded: Seeded):expect(outcomeExtractorVersion(outcomes[1]!.context)).toBe(1);if (managed) {const requests = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE intent->>'kind'=$1", [CONVERSATION_LABELS_INTENT]);- expect(requests.map(r => r.state)).toEqual(['committed', 'committed']);+ expect(requests.map(r => r.state)).toEqual(['committed']);}expect((await conversationLabelFactsCheck(engine, ['default'])).status).toBe('ok');// Lifecycle: ordinary extraction re-extracts only the dated page; replacement keeps retired and referenced rows.diff --git a/test/write-attribution.test.ts b/test/write-attribution.test.tsindex 94347229d5..1398f48d79 100644--- a/test/write-attribution.test.ts+++ b/test/write-attribution.test.ts@@ -27,7 +27,7 @@ import { getWriteRequest } from '../src/core/persistence/journal.ts';import { submitRememberMutation, submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { maintenancePreflight } from '../src/core/persistence/prepared-maintenance.ts';-import { buildConversationIntent, startConversationGeneration, submitConversationIntent } from '../src/core/facts/conversation-publication.ts';+import { buildConversationPage, conversationGeneration, submitConversationPages } from '../src/core/facts/conversation-publication.ts';import { currentConversationVersionToken } from '../src/commands/extract-conversation-facts.ts';import type { Principal } from '../src/core/persistence/model.ts';import { renderFactsTable } from '../src/core/facts-fence.ts';@@ -288,11 +288,11 @@ describe('write attribution on a managed brain', () => {const authority = (await maintenancePreflight(engine, brain.sourceId))!;const current = (await engine.getPage(slug, { sourceId: brain.sourceId }))!;const versionToken = await currentConversationVersionToken(engine, current);- const start = await startConversationGeneration(engine, authority, brain.local.config, { slug, page: current, versionToken, since: null, segmentLimit: 0 });- if (start.kind !== 'extract') throw new Error(`unexpected generation state ${start.kind}`);- const intent = await buildConversationIntent(engine, brain.local.config, start, [{ fact: 'Derived example claim', kind: 'fact', notability: 'medium',- source: 'cli:extract-conversation-facts', entity_slug: slug, row_num: 0, source_markdown_slug: slug }], { complete: false, newestEnd: null, visibility: 'world' });- const receipt = await submitConversationIntent(engine, authority, slug, start, intent);+ const generation = await conversationGeneration(engine, authority, { slug, page: current, versionToken, since: null, segmentLimit: 0 });+ const entry = await buildConversationPage(engine, brain.local.config, { slug, generation, attempt: 0, versionToken, since: null, segmentLimit: 0 },+ [{ fact: 'Derived example claim', kind: 'fact', notability: 'medium', source: 'cli:extract-conversation-facts', entity_slug: slug, row_num: 0, source_markdown_slug: slug }],+ { newestEnd: null, visibility: 'world' });+ const receipt = await submitConversationPages(engine, authority, [entry]);const rows = await engine.executeRaw<RowActors>(`SELECT ${ROW_COLUMNS} FROM facts WHERE source_id=$1 AND fact='Derived example claim'`, [brain.sourceId]);expect(rows).toHaveLength(1);expect(created(rows[0])).toEqual(actor(await requestRow(brain, brain.local, receipt), brain.principals.local));