Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(facts): receipted managed conversation facts publication with generation identity
time-attack015a9e7d0644
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 4643e946af..80a0413bc5 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1460,6 +1460,16 @@ More: [docs/guides/repair.md#legacy-jobs-active](../../docs/guides/repair.md#leg|---|---|---|---|---|---|---|| Another process holds the lock this command needs. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### maintenance_backpressure++<a id="maintenance_backpressure"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Managed maintenance stopped admitting requests because this writer's outstanding requests reached 80% of its limit; nothing more was submitted. | Each page of a maintenance run publishes as its own request. Stopping well below principalOutstanding leaves room for the writer's other work and keeps a slow consumer from turning the run into refused admissions. | Wait briefly, then retry the same request (writes: reuse the same request_id). Run: gbrain sources writer status --source '{source_id}' --json | agent | `repeat the read that failed` | 12 | yes |++More: [docs/guides/write-refusals.md#maintenance_backpressure](../../docs/guides/write-refusals.md#maintenance_backpressure)+### managed_pull_skipped<a id="managed_pull_skipped"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 6158f62dfb..957b1214ce 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -69,6 +69,7 @@ of making a duplicate.| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. || <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). || <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |+| <a id="maintenance_backpressure"></a>`maintenance_backpressure` (exit 12) | `maintenance_backpressure` | A managed maintenance run (`gbrain extract-conversation-facts`, its cycle phase or job) publishes each page as its own request. Before each page's model work it checks this CLI writer's outstanding requests; at 80% of `persistence.limits.principalOutstanding` it stops admitting, so a slow or absent consumer cannot turn the run into refused admissions. Pages already published keep their facts and nothing is half-written. | Read the pending requests with `gbrain sources writer status --source <id> --json`. A resident `gbrain serve`, or the next CLI run, publishes them; once they settle, rerun the same command. Raising `persistence.limits.principalOutstanding` is the user's call. |### Other error codesdiff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 45dd2001a1..d44ee34af1 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -75,8 +75,23 @@ import {type ExtractedFact,} from '../core/facts/extract.ts';import { configureGatewayIfUninitialized, isAvailable, withBudgetTracker } from '../core/ai/gateway.ts';-import { managedDerivedFactsPreflight, replaceDerivedFactsForPage, writeDerivedFacts } from '../core/persistence/derived-facts.ts';+import { writeDerivedFacts } from '../core/persistence/derived-facts.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';+import { maintenancePreflight, type MaintenanceAuthority } from '../core/persistence/prepared-maintenance.ts';+import { loadConfig, type GBrainConfig } from '../core/config.ts';+import { OperationError } from '../core/ops/contract.ts';+import { resolveManagedFactsEmbedding } from '../core/persistence/facts-maintenance.ts';+import {+ assertConversationAdmissionHeadroom,+ buildConversationIntent,+ conversationIntentByteLimit,+ estimateConversationIntentBytes,+ startConversationGeneration,+ submitConversationIntent,+ type ConversationFactRow,+ type GenerationStart,+} from '../core/facts/conversation-publication.ts';+import type { FactEmbeddingSignature } from '../core/facts/extract.ts';import { 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';@@ -100,7 +115,7 @@ import { assertFactsEmbeddingDimMatchesConfig } from '../core/embedding-dim-checimport { writeReceipt, shortRunId } from '../core/extract/receipt-writer.ts';import { upsertExtractRollup, classifyRunStop } from '../core/extract/rollup-writer.ts';import { ALLOWED_TYPES, ALLOWED_TYPE_ALIASES, isConversationFactsEligiblePage, pageTypesForAllowed, requireParseableConversationFlag, type AllowedType } from '../core/facts/conversation-types.ts';-import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE } from '../core/facts/audit-sources.ts';+import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE, stampExtractorVersion } from '../core/facts/audit-sources.ts';import { resolveDefaultVisibility, type FactVisibility } from '../core/facts/visibility.ts';import {emptySaveTimeResolutionCounts,@@ -354,6 +369,10 @@ export interface ExtractConversationFactsResult {fallback_slugify_count: number;/** Entity values kept raw after a best-effort resolution failure. */resolution_errors: number;+ /** Managed brains: pages whose publication was accepted but is still pending (retried next run). */+ pages_pending?: number;+ /** Managed brains: pages whose extraction generation is blocked until the page changes (no model call). */+ pages_blocked?: number;budget_exhausted?: boolean;budget_reason?: BudgetReason;budget_model?: string;@@ -746,8 +765,13 @@ interface ExtractCoreState {result: ExtractConversationFactsResult;engine: BrainEngine;sourceId: string;- /** Managed brain: a page's rows are buffered and replace the prior batch in one coordinator transaction. */+ /** Managed brain: a page's rows are buffered and replace the prior batch in one receipted request. */managed: boolean;+ /** Managed brain, not a dry run: the maintenance authority its requests publish under. */+ authority: MaintenanceAuthority | null;+ config: GBrainConfig;+ /** Managed brain: the facts embedding signature frozen batches carry (null: no vectors). */+ embedding: FactEmbeddingSignature | null;dryRun: boolean;sleepMs: number;segmentLimit: number;@@ -944,28 +968,99 @@ async function snapshotIsCurrent(return currentSnapshot.versionToken === snapshot.versionToken;}+/** The parser-input version token of `page` as it is now (the managed preparer's recheck). */+export async function currentConversationVersionToken(engine: BrainEngine, page: Page): Promise<string> {+ return (await preparePageSnapshot(engine, page)).versionToken;+}+/**- * Managed publication: under the page lock the page must still be the same- * row at the same revision with the same parser input the batch came from.- * Counts the replaced prior batch as cleaned and returns the rows inserted.+ * Managed brains, before any model work for one page: resolve its extraction+ * generation and settle it without the model when this writer already+ * admitted a request for it (replayed, resubmitted, pending or blocked), or+ * when its largest possible batch cannot fit one request. Returns the+ * generation to extract into otherwise.*/-async function replacePageFacts(+async function startManagedPage(state: ExtractCoreState,snapshot: ConversationPageSnapshot,- build: (tx: BrainEngine) => Promise<Array<NewFact & { row_num: number; source_markdown_slug: string }>>,-): Promise<number> {+ sinceIso: string | undefined,+ segments: number,+): Promise<{ done: { newEndIso: string | null } } | { start: Extract<GenerationStart, { kind: 'extract' }> }> {+ const authority = state.authority!;const { page } = snapshot;- const { deleted, inserted } = await replaceDerivedFactsForPage(state.engine, state.sourceId, page.slug, {- sourcePrefix: 'cli:extract-conversation-facts',- isCurrent: async tx => {- const current = await tx.getPage(page.slug, { sourceId: state.sourceId });- return !!current && current.id === page.id && current.knowledge_revision === page.knowledge_revision &&- (await preparePageSnapshot(tx, current)).versionToken === snapshot.versionToken;- },- build,+ const start = await startConversationGeneration(state.engine, authority, state.config, {+ slug: page.slug, page, versionToken: snapshot.versionToken, since: sinceIso ?? null, segmentLimit: state.segmentLimit,});- state.result.orphan_facts_cleaned += deleted;- return inserted;+ if (start.kind === 'extract') {+ const planned = state.segmentLimit > 0 ? Math.min(segments, state.segmentLimit) : segments;+ const estimate = estimateConversationIntentBytes(planned, state.embedding);+ const limit = await conversationIntentByteLimit(state.engine);+ if (estimate > limit) {+ state.result.pages_skipped_too_large++;+ process.stderr.write(`[extract-conversation-facts] SKIP ${page.slug}: up to ${planned} segment(s) could freeze a ${estimate}-byte batch, over the ${limit}-byte request limit; its prior facts were kept and no model call ran. Narrow it with --slug ${page.slug} --segment-limit <n>\n`);+ return { done: { newEndIso: null } };+ }+ await assertConversationAdmissionHeadroom(state.engine, authority);+ return { start };+ }+ if (start.kind === 'resubmit') {+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: resubmitting the stored batch of this page generation (attempt ${start.attempt + 1}); no model call\n`);+ await assertConversationAdmissionHeadroom(state.engine, authority);+ return { done: settleManagedReceipt(state, page.slug, await submitConversationIntent(state.engine, authority, page.slug, start, start.intent)) };+ }+ if (start.kind === 'settled') {+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: this page generation was already published; replaying its receipt, no model call\n`);+ return { done: settleManagedReceipt(state, page.slug, start.receipt) };+ }+ if (start.kind === 'pending') {+ state.result.pages_pending = (state.result.pages_pending ?? 0) + 1;+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: request ${start.requestId} for this page is accepted and still pending; rerun to confirm (no model call)\n`);+ return { done: { newEndIso: null } };+ }+ state.result.pages_blocked = (state.result.pages_blocked ?? 0) + 1;+ process.stderr.write(`[extract-conversation-facts] SKIP ${page.slug}: ${start.message}\n`);+ return { done: { newEndIso: null } };+}++/** Books a committed managed receipt into the run's counters. */+function settleManagedReceipt(state: ExtractCoreState, slug: string, receipt: Record<string, unknown>): { newEndIso: string | null } {+ state.result.orphan_facts_cleaned += Number(receipt.deleted ?? 0);+ state.result.facts_inserted += Number(receipt.facts_inserted ?? 0);+ if (receipt.page_outcome === 'non_extractable') {+ state.result.pages_marked_non_extractable++;+ return { newEndIso: null };+ }+ state.result.pages_processed++;+ const newest = typeof receipt.newest_end === 'string' ? receipt.newest_end : null;+ if (newest) state.cpMap.set(cpMapKey(state.sourceId, slug), newest);+ return { newEndIso: newest };+}++/**+ * Managed publication of one page's frozen batch as a receipted request.+ * Returns the fact rows inserted, or null when the request is accepted but+ * still pending after the job's wait (the page stays unfinished).+ */+async function publishManagedBatch(+ state: ExtractCoreState,+ snapshot: ConversationPageSnapshot,+ start: Extract<GenerationStart, { kind: 'extract' }>,+ rows: ConversationFactRow[],+ newestEnd: string | null,+): Promise<number | null> {+ const complete = rows.some(row => row.source === TERMINAL_AUDIT_SOURCE || row.source === NON_EXTRACTABLE_AUDIT_SOURCE);+ const intent = await buildConversationIntent(state.engine, state.config, start, rows,+ { complete, newestEnd, visibility: state.factVisibility });+ try {+ const receipt = await submitConversationIntent(state.engine, state.authority!, snapshot.page.slug, start, intent);+ state.result.orphan_facts_cleaned += Number(receipt.deleted ?? 0);+ return Number(receipt.facts_inserted ?? 0);+ } catch (error) {+ if (!(error instanceof OperationError) || error.code !== 'write_pending') throw error;+ state.result.pages_pending = (state.result.pages_pending ?? 0) + 1;+ process.stderr.write(`[extract-conversation-facts] ${snapshot.page.slug}: its facts were accepted and are still pending; rerun to confirm (the rerun replays them, no model call)\n`);+ return null;+ }}async function processPage(@@ -1055,8 +1150,7 @@ async function processPage(// #5025 / N2: undated time-only turns, a single email or a prose// meeting/email page end in a not-extractable outcome instead of// epoch-dated facts or a rescan every run.- const skip = conversationSkip(page, body, parseResult, messages, { llmFallback: Boolean(state.llmFallbackModel), managed: state.managed });- const terminalSkip = skip?.durable ? skip : null;+ const skip = conversationSkip(page, body, parseResult, messages, { llmFallback: Boolean(state.llmFallbackModel) });if (skip) {process.stderr.write(`[extract-conversation-facts] SKIP ${page.slug}: ${skip.message}\n`);messages = [];@@ -1069,15 +1163,15 @@ async function processPage(const segments = splitIntoSegments(messages, { gapMinutes, sinceIso });if (segments.length === 0) {state.result.pages_skipped++;- if (!declinedUnrecognizedSpeaker && !terminalSkip) {+ if (!declinedUnrecognizedSpeaker && !skip) {if (messages.length === 0) state.result.pages_skipped_unparsed++;else if (allSegments.length === 0) state.result.pages_skipped_insufficient_turns++;else state.result.pages_skipped_since++;}if (!state.dryRun &&- (parseResult.phase !== 'no_match' || terminalSkip !== null) &&- allSegments.length === 0 && !(skip && !skip.durable) &&+ (parseResult.phase !== 'no_match' || skip !== null) &&+ allSegments.length === 0 &&// #4136 — a decline must stay NON-TERMINAL. The audit row is keyed by// a content versionToken and skips the page on every future run; a// declined page must retry once the parser learns the label instead.@@ -1085,14 +1179,15 @@ async function processPage(// orphan cleanup below until the page re-extracts.)!declinedUnrecognizedSpeaker) {- const reason = terminalSkip?.reason ?? (messages.length === 0+ const reason = skip?.reason ?? (messages.length === 0? 'no conversation messages found': 'fewer than two eligible messages');if (await snapshotIsCurrent(state.engine, state.sourceId, snapshot)) {- if (state.managed) {- await replacePageFacts(state, snapshot, async tx => [- nonExtractableAuditFact(page.slug, await peekRowNumStart(tx, state.sourceId, page.slug), snapshot.versionToken, reason),- ]);+ if (state.authority) {+ const managed = await startManagedPage(state, snapshot, sinceIso, 0);+ if ('done' in managed) return managed.done;+ const row = nonExtractableAuditFact(page.slug, 0, snapshot.versionToken, reason);+ if (await publishManagedBatch(state, snapshot, managed.start, [row], null) === null) return { newEndIso: null };} else {state.result.orphan_facts_cleaned += await deleteOrphanFactsForPage(state.engine, state.sourceId, page.slug);const rowNum = await peekRowNumStart(state.engine, state.sourceId, page.slug);@@ -1112,12 +1207,19 @@ async function processPage(return { newEndIso: null };}+ let managedStart: Extract<GenerationStart, { kind: 'extract' }> | null = null;+ if (state.authority) {+ const managed = await startManagedPage(state, snapshot, sinceIso, segments.length);+ if ('done' in managed) return managed.done;+ managedStart = managed.start;+ }+// D11: delete-orphans-first replay safety. Wipes any facts written by// a prior crashed / killed / partial run for this (sourceId, slug)// pair before we re-extract. The lock we hold (D2 + D12 refreshing// lock above the caller) guarantees no other worker is writing to// this page right now, so the DELETE+INSERT pair is safe. A managed brain- // keeps the prior batch until replacePageFacts swaps it atomically below.+ // keeps the prior batch until its receipted request replaces it below.const cleaned = state.managed ? 0 : await deleteOrphanFactsForPage(state.engine, state.sourceId, page.slug);if (cleaned > 0) {state.result.orphan_facts_cleaned += cleaned;@@ -1264,9 +1366,10 @@ async function processPage(return { newEndIso: null };}- if (state.managed && newestEnd !== null) {- pageInsertedTotal = await replacePageFacts(state, snapshot, async () => managedRows) -- managedRows.filter(row => row.source === TERMINAL_AUDIT_SOURCE).length;+ if (managedStart && newestEnd !== null) {+ const inserted = await publishManagedBatch(state, snapshot, managedStart, managedRows, newestEnd);+ if (inserted === null) return { newEndIso: null };+ pageInsertedTotal = inserted;state.result.facts_inserted += pageInsertedTotal;}@@ -1301,6 +1404,7 @@ function terminalAuditFact(source_session: outcomeSession(TERMINAL_AUDIT_SOURCE, slug, versionToken),confidence: 1.0,notability: 'low',+ context: stampExtractorVersion(null),row_num: rowNum,source_markdown_slug: slug,};@@ -1324,7 +1428,7 @@ function nonExtractableAuditFact(),confidence: 1.0,notability: 'low',- context: `scanned, not extractable: ${reason}`,+ context: stampExtractorVersion(`scanned, not extractable: ${reason}`),row_num: rowNum,source_markdown_slug: slug,};@@ -1349,7 +1453,13 @@ export async function runExtractConversationFactsCore(if (!sourceId) {throw new Error('runExtractConversationFactsCore: opts.sourceId is required');}- const managed = await managedDerivedFactsPreflight(engine, sourceId);+ // A managed brain publishes each page's batch as a receipted maintenance+ // request; the authority is preflighted once, before any model work. A dry+ // run writes nothing and registers nothing.+ const managed = await managedPersistenceEnabled(engine);+ const authority = managed && !opts.dryRun ? await maintenancePreflight(engine, sourceId) : null;+ const config = loadConfig() ?? { engine: engine.kind };+ if (authority) await assertConversationAdmissionHeadroom(engine, authority, opts.slugs?.length ?? (opts.slug ? 1 : opts.limit ?? 1));const result: ExtractConversationFactsResult = {pages_considered: 0,@@ -1434,6 +1544,9 @@ export async function runExtractConversationFactsCore(engine,sourceId,managed,+ authority,+ config,+ embedding: authority ? await resolveManagedFactsEmbedding(engine, config) : null,dryRun,sleepMs,segmentLimit,@@ -1540,7 +1653,7 @@ export async function runExtractConversationFactsCore(try {await processPageWithLock(page);} catch (error) {- if (isAbortError(error) || error instanceof BudgetExhausted) throw error;+ if (isAbortError(error) || error instanceof BudgetExhausted || stopsRun(error)) throw error;recordPageFailure(result, sourceId, slug, error);}}@@ -1612,11 +1725,11 @@ export async function runExtractConversationFactsCore(workers,signal,onItem: (page) => processPageWithLock(page),- onError: (error) => (isAbortError(error) ? 'abort' : 'continue'),+ onError: (error) => (isAbortError(error) || stopsRun(error) ? 'abort' : 'continue'),failureLabel: (page) => page.slug,});const cancellation = poolResult.failures.find((failure) =>- isAbortError(failure.error),+ isAbortError(failure.error) || stopsRun(failure.error),);if (cancellation) throw cancellation.error;if (signal?.aborted) {@@ -2082,6 +2195,8 @@ export async function runExtractConversationFacts(aggregate.facts_inserted += perSource.facts_inserted;aggregate.fallback_slugify_count += perSource.fallback_slugify_count;aggregate.resolution_errors += perSource.resolution_errors;+ if (perSource.pages_pending) aggregate.pages_pending = (aggregate.pages_pending ?? 0) + perSource.pages_pending;+ if (perSource.pages_blocked) aggregate.pages_blocked = (aggregate.pages_blocked ?? 0) + perSource.pages_blocked;if (perSource.budget_exhausted) anyBudgetExhausted = true;if (perSource.budget_reason === 'no_pricing') unpricedModels.add(perSource.budget_model ?? 'unknown model');if (perSource.budget_pricing) pricingGuidance.set(perSource.budget_pricing.model, perSource.budget_pricing);@@ -2142,6 +2257,12 @@ export async function runExtractConversationFacts(if (aggregate.pages_failed > 0) {console.error(` Failed ${aggregate.pages_failed} page(s); they remain unfinished and will retry.`);}+ if (aggregate.pages_pending) {+ console.log(` ${aggregate.pages_pending} page(s) were accepted and are still pending; rerun the same command to confirm them (no model call).`);+ }+ if (aggregate.pages_blocked) {+ console.log(` ${aggregate.pages_blocked} page(s) are blocked at their current version after a request failed; they are retried only once the page changes (each SKIP line names the receipt).`);+ }if (aggregate.pages_llm_fallback > 0) {console.log(` Parsed ${aggregate.pages_llm_fallback} page(s) with the opt-in LLM fallback.`);}@@ -2207,6 +2328,11 @@ function recordPageFailure(result: ExtractConversationFactsResult, sourceId: strprocess.stderr.write(`[extract-conversation-facts] ${slug} failed (${reason}) and stays unfinished; retry: gbrain extract-conversation-facts --source-id ${sourceId} --slug ${slug}\n`);}+/** Managed admission backpressure and exhausted request ids stop the whole run, not one page. */+function stopsRun(err: unknown): boolean {+ return err instanceof OperationError && (err.code === 'maintenance_backpressure' || err.code === 'queue_capacity');+}+export function isAbortError(err: unknown): boolean {if (!(err instanceof Error)) return false;return err.name === 'AbortError' || /aborted|cancell?ed/i.test(err.message);diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex b0db478ed7..9185a25899 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -49,6 +49,7 @@ export const ERROR_CATALOGUE = {source_checkout_missing: { code: 'recovery_required', docs: 'docs/guides/write-refusals.md#source_checkout_missing' },managed_pull_skipped: { code: 'managed_pull_skipped', docs: 'docs/guides/write-refusals.md#managed_pull_skipped' },no_pricing: { code: 'no_pricing', docs: 'docs/guides/write-refusals.md#no_pricing' },+ maintenance_backpressure: { code: 'maintenance_backpressure', docs: 'docs/guides/write-refusals.md#maintenance_backpressure' },// F0 `gbrain sources refresh` (worktree-wide coordinated ff-only refresh).refresh_not_managed: { code: 'refresh_not_managed', docs: 'docs/guides/write-refusals.md#refresh_not_managed' },refresh_not_owner: { code: 'refresh_not_owner', docs: 'docs/guides/write-refusals.md#refresh_not_owner' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex c035264c34..83bcc4386d 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -215,6 +215,7 @@ export const CODES = {local_conflict: { class: 'caller', summary: "A local file or registration conflicts with the requested change." },lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },managed_pull_skipped: { class: 'retryable', summary: "The managed pull was skipped." },+ maintenance_backpressure: { class: 'retryable', summary: "Managed maintenance stopped admitting requests because this writer's outstanding requests reached 80% of its limit; nothing more was submitted.", why: "Each page of a maintenance run publishes as its own request. Stopping well below principalOutstanding leaves room for the writer's other work and keeps a slow consumer from turning the run into refused admissions.", docs: 'docs/guides/write-refusals.md#maintenance_backpressure', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the pending requests holding this writer's capacity, read-only.", requires_exclusive: false }, exit: 12 },membership_inactive: { class: 'caller', summary: "The shared-skills enrollment epoch was left or superseded.", docs: 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment' },membership_not_found: { class: 'caller', summary: "This principal has no shared-skills membership with that installation id.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },method_not_allowed: { class: 'caller', summary: "The HTTP method is not allowed on this endpoint." },diff --git a/src/core/facts/audit-sources.ts b/src/core/facts/audit-sources.tsindex a987e9c473..196591f4c1 100644--- a/src/core/facts/audit-sources.ts+++ b/src/core/facts/audit-sources.ts@@ -43,3 +43,27 @@ export const AUDIT_ROW_SOURCES = [NON_EXTRACTABLE_AUDIT_SOURCE,LEGACY_TERMINAL_AUDIT_SOURCE,] as const;++/**+ * Decision 8 (wave 9 follow-ups): the conversation parser + extractor+ * semantic version. Bump it when a parser or extractor change alters what an+ * already-scanned page yields. New outcome rows carry it in their `context`+ * (`extractor_version=<n>`) and a managed publication carries it in its+ * generation identity. An outcome recorded under an older version stays+ * fresh: nothing reopens automatically; doctor counts it as stale.+ */+export const CONVERSATION_EXTRACTOR_VERSION = 1;++const EXTRACTOR_VERSION_RE = /(?:^|; )extractor_version=(\d+)$/;++/** The outcome row context with the current extractor version stamped on it. */+export function stampExtractorVersion(context: string | null | undefined): string {+ const stamp = `extractor_version=${CONVERSATION_EXTRACTOR_VERSION}`;+ return context ? `${context}; ${stamp}` : stamp;+}++/** The extractor version an outcome row was recorded under, or null for a row older than the stamp. */+export function outcomeExtractorVersion(context: string | null | undefined): number | null {+ const match = context ? EXTRACTOR_VERSION_RE.exec(context) : null;+ return match ? Number(match[1]) : null;+}diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.tsnew file mode 100644index 0000000000..ea6ebf7a32--- /dev/null+++ b/src/core/facts/conversation-publication.ts@@ -0,0 +1,363 @@+/**+ * Receipted publication of one conversation page's derived facts on a managed+ * brain (wave 9 follow-ups, item 1).+ *+ * `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.+ *+ * Generation identity. A request 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.+ *+ * 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.+ */+import type { BrainEngine, NewFact } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import type { Page } from '../types.ts';+import type { PreparedMutation } from '../persistence/coordinator.ts';+import type { WriteRequest } from '../persistence/model.ts';+import type { FrozenExtractedFact } from '../persistence/facts-maintenance.ts';+import type { FactEmbeddingSignature } from './extract.ts';+import { ALL_FACT_KINDS } from '../engine.ts';+import { isTerminal } from '../persistence/model.ts';+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 { assertLifetimeIdHeadroom, getWriteRequest } 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 { submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';+import { waitForWrite, writeResponse } from '../persistence/service.ts';+import { catalogueError } from '../error-catalogue.ts';+import { CONVERSATION_EXTRACTOR_VERSION, NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUDIT_SOURCE } from './audit-sources.ts';++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';+export const MAX_GENERATION_ATTEMPTS = 3;+/** Admission stops once the principal's outstanding requests reach this share of `principalOutstanding`. */+export const OUTSTANDING_ADMISSION_SHARE = 0.8;+/** 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. */+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. */+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. */+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). */+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;+ page_id: number;+ version_token: string;+ extractor_version: number;+ generation: string;+ selectors: { since: string | null; segment_limit: number };+ /** True when the batch 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;+ visibility: 'private' | 'world';+ embedding: FactEmbeddingSignature | null;+ rows: FrozenConversationFact[];+}++export interface ConversationGenerationInput {+ slug: string;+ page: Page;+ versionToken: string;+ since: string | null;+ segmentLimit: number;+}++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)}`;+}++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> {+ 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) {+ throw opError('revision_conflict', 'The conversation page changed before extraction started; nothing was submitted.',+ `Page ${input.slug} in source ${sourceId} changed or was replaced after it was read, so no model work ran for it. The next run extracts the current page.`);+ }+ const [base] = await engine.executeRaw<{ id: number | string | null }>(+ `SELECT max(id) AS id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%'`,+ [sourceId, input.slug]);+ const 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}` };+}++/** 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 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}` };+}++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 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);+ return 16_384 + (segments * MAX_FACTS_PER_SEGMENT + 1) * perRow;+}++/** The byte ceiling one conversation facts request may carry on this brain. */+export async function conversationIntentByteLimit(engine: BrainEngine): Promise<number> {+ const limits = await readJournalLimits(engine);+ return Math.min(limits.principalIntentBytes, limits.brainIntentBytes, PERSISTENCE_IPC_MAX_BYTES);+}++/**+ * Before a page's model work: stop the run once this principal's outstanding+ * requests reach OUTSTANDING_ADMISSION_SHARE of its limit, and refuse when+ * its permanent request ids cannot cover `needed` more admissions.+ */+export async function assertConversationAdmissionHeadroom(engine: BrainEngine, authority: MaintenanceAuthority, needed = 1): Promise<void> {+ const limits = await readJournalLimits(engine);+ const [counter] = await engine.executeRaw<{ outstanding_count: number | string }>(+ 'SELECT outstanding_count FROM persistence_counters WHERE key=$1', [principalKey(authority.writer.principal)]);+ const outstanding = Number(counter?.outstanding_count ?? 0);+ const ceiling = Math.max(1, Math.floor(limits.principalOutstanding * OUTSTANDING_ADMISSION_SHARE));+ if (outstanding >= ceiling) {+ throw catalogueError('maintenance_backpressure',+ `Conversation fact extraction stopped admitting: ${outstanding} of this writer's ${limits.principalOutstanding} outstanding requests are still pending.`,+ `Let the pending requests settle (gbrain sources writer status --source ${authority.writer.sourceId} --json shows them; a resident gbrain serve or the next CLI run publishes them), then rerun the same command. Pages already published keep their facts.`);+ }+ await assertLifetimeIdHeadroom(engine, authority.writer.principal, needed);+}++function freezeRow(row: ConversationFactRow): FrozenConversationFact {+ return {+ fact: row.fact, kind: row.kind ?? 'fact', entity_slug: row.entity_slug ?? null, context: row.context ?? null,+ valid_from: (row.valid_from ?? new Date()).toISOString(), valid_until: row.valid_until ? row.valid_until.toISOString() : null,+ source: row.source, source_session: row.source_session ?? null, confidence: row.confidence ?? 1.0,+ notability: row.notability ?? 'medium', embedding: row.embedding ? Array.from(row.embedding) : null,+ embedding_model: row.embedding ? row.embedding_model ?? null : null,+ claim_metric: row.claim_metric ?? null, claim_value: row.claim_value ?? null, claim_unit: row.claim_unit ?? null,+ claim_period: row.claim_period ?? null, event_type: row.event_type ?? null, attributed_to: row.attributed_to ?? null,+ };+}++/** 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;+ const embedded = rows.some(row => row.embedding);+ return {+ kind: CONVERSATION_FACTS_INTENT, protocol: CONVERSATION_FACTS_PROTOCOL, expected_revision: generation.revision,+ page_id: generation.pageId, version_token: generation.input.versionToken, extractor_version: CONVERSATION_EXTRACTOR_VERSION,+ generation: generation.key, selectors: { since: generation.input.since, segment_limit: generation.input.segmentLimit },+ complete: opts.complete, newest_end: opts.newestEnd, visibility: opts.visibility,+ embedding: embedded ? await resolveManagedFactsEmbedding(engine, config) : null, rows: rows.map(freezeRow),+ };+}++/**+ * Submits one generation attempt and returns its committed receipt. 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>> {+ 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.principalIntentBytes (the user's call).`);+ }+ return submitDatabaseMaintenanceIntent(engine, authority, slug, intent, requestIdFor(start.generation.key, start.attempt));+}++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.`,+ { fix: receiptFix(row.request_id) });+}++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 (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 (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');+ }+ 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;+}++/** 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();+ const rows = await tx.executeRaw<{ alias_slug: string; canonical_slug: string }>(`SELECT a.alias_slug, a.canonical_slug FROM slug_aliases a+ WHERE a.source_id=$1 AND a.alias_slug=ANY($2::text[])+ AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=a.source_id AND p.slug=a.alias_slug AND p.deleted_at IS NULL)+ AND EXISTS (SELECT 1 FROM pages c WHERE c.source_id=a.source_id AND c.slug=a.canonical_slug AND c.deleted_at IS NULL)`, [sourceId, [...new Set(slugs)]]);+ return new Map(rows.map(row => [row.alias_slug, row.canonical_slug]));+}++/**+ * The page's replacement under its lock: deletes the prior extractor rows+ * and inserts `rows` numbered above every remaining fact row of the page.+ * Shared by the managed apply and the unmanaged writer.+ */+export async function replaceConversationFacts(tx: BrainEngine, sourceId: string, slug: string,+ rows: Array<Omit<ConversationFactRow, 'row_num' | 'source_markdown_slug'>>): Promise<{ deleted: number; inserted: number }> {+ const [deleted] = await tx.executeRaw<{ count: string }>(+ `WITH del AS (DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' RETURNING 1)+ SELECT COUNT(*)::text AS count FROM del`, [sourceId, slug]);+ if (!rows.length) return { deleted: Number(deleted?.count ?? 0), inserted: 0 };+ 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', [sourceId, slug]);+ const start = top?.n == null ? 0 : Number(top.n) + 1;+ const { inserted } = await tx.insertFacts(rows.map((fact, i) => ({ ...fact, row_num: start + i, source_markdown_slug: slug })), { source_id: sourceId }); // gbrain-allow-direct-insert: a conversation page's derived fact batch replaced under its page lock (inside the receipted publication on a managed brain)+ if (inserted !== rows.length) {+ throw opError('storage_error', 'A conversation fact insert was lost; the page\'s prior facts were kept.',+ `Only ${inserted} of ${rows.length} fact rows of ${slug} in source ${sourceId} were inserted, so the replacement rolled back. Run the extraction for the page again; report this if it repeats.`);+ }+ return { deleted: Number(deleted?.count ?? 0), inserted };+}++/** Preparer for `managed_maintenance_conversation_facts`: a database-only publication on the 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) => {+ 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) });+ }+ }+ };+ await check(engine, false);+ return { observedRevision: p.expected_revision, noop: true,+ validate: tx => check(tx, true),+ 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 };+ } };+}diff --git a/src/core/facts/conversation-skip.ts b/src/core/facts/conversation-skip.tsindex de60c996a5..d58c4c703f 100644--- a/src/core/facts/conversation-skip.ts+++ b/src/core/facts/conversation-skip.ts@@ -13,13 +13,10 @@* configured. Other speaker-less pages stay retryable (a later parser* may learn their format).*- * On a managed brain the single-email and prose outcomes are not durable:- * recording them would turn a page that wrote nothing into a derived-facts- * write without a persistence receipt, so those pages stay retryable there.- * A multi-message email thread on a managed brain is skipped the same way:- * replacing a page's conversation facts has no receipted publication path- * yet, so it writes nothing and is retried (TODOS.md, managed conversation- * facts).+ * Every outcome is durable on managed brains too: a managed brain publishes+ * the outcome row as a receipted maintenance request+ * (facts/conversation-publication.ts), and a multi-message email thread is+ * extracted like any other conversation.*/import { looksLikeMeetingNotes } from '../conversation-parser/builtins.ts';import { deriveDateContext } from '../conversation-parser/parse.ts';@@ -30,12 +27,10 @@ import { ALLOWED_TYPE_ALIASES } from './conversation-types.ts';const PROSE_PAGE_TYPES = new Set([...ALLOWED_TYPE_ALIASES.meeting, ...ALLOWED_TYPE_ALIASES.email]);export interface ConversationSkip {- /** Recorded on the not-extractable audit row when durable. */+ /** Recorded on the not-extractable audit row. */reason: string;/** The operator-facing line: what happened and what reopens the page. */message: string;- /** False: skipped this run, nothing recorded, retried next run. */- durable: boolean;}export function conversationSkip(@@ -43,20 +38,12 @@ export function conversationSkip(body: string,parse: Pick<ParseResult, 'phase' | 'matched_pattern_id'>,messages: ReadonlyArray<{ timestamp: string }>,- opts: { llmFallback: boolean; managed: boolean },+ opts: { llmFallback: boolean },): ConversationSkip | null {if (messages.length > 0 && deriveDateContext({ page }).source === 'epoch_default' && messages.some((m) => m.timestamp.startsWith('1970-01-01T'))) {return {reason: 'no page date to place message times',message: 'no page date to place message times (they would read 1970-01-01); add a date: to the page frontmatter to extract it',- durable: true,- };- }- if (opts.managed && messages.length > 1 && parse.matched_pattern_id === 'email-thread-heading') {- return {- reason: `an email thread in this ${page.type} page`,- message: `an email thread in this ${page.type} page; managed brains do not extract email-thread conversation facts yet (no receipted publication path); skipped`,- durable: false,};}let reason: string | null = null;@@ -66,7 +53,5 @@ export function conversationSkip(reason = `no speaker turns in this ${page.type} page (prose, not a transcript)`;}if (!reason) return null;- return opts.managed- ? { reason, message: `${reason}; skipped`, durable: false }- : { reason, message: `${reason}; not extractable until the page changes`, durable: true };+ return { reason, message: `${reason}; not extractable until the page changes` };}