Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): managed conversation facts keep audit rows private, preflight lazily, and the backfill phase skips sources this host does not own
garrytan49dbcd0fbd47
diff --git a/TODOS.md b/TODOS.mdindex 6ac922d76b..0514d18b51 100644--- a/TODOS.md+++ b/TODOS.md@@ -41,7 +41,7 @@Context: the wave 9 follow-up wave (plan reviewed 2026-10-06; Garry approved every recommended decision on 2026-10-07). These are the items that wave deliberately leaves out.- [ ] **P3 — Stall detection for subagent turns, both transports.** **What:** `ai.chat.per_turn_timeout_ms` bounds a whole subagent turn (default 30 min) because neither transport streams, so a hung provider holds the turn for the full budget. Deferred from the wave 9 follow-ups (Decision 1) until GBRA-52 (#6066, which edits the Google instantiation in `ai/gateway.ts`) lands. **Fix:** cover both transports, never only one: (1) the default Anthropic-direct path (`makeSubagentHandler` in `src/core/minions/handlers/subagent.ts` calls `messages.create` on the Anthropic SDK client) moves to `messages.stream` with an idle timer; (2) the gateway path (non-Anthropic routes through `toolLoop`) moves to `streamText` with execute-less tools and `timeout.chunkMs`, raising the `ai` floor in `package.json` to `^6.0.174`. Measure first-chunk and between-chunk windows on current frontier routes before picking defaults (thinking routes can stay silent for minutes; a 120-300 s window kills legitimate reasoning). Add a stall error code with `fix.next`, an error-catalogue entry and a config override (for example `ai.chat.stall_timeout_ms`). **Effort:** M. **Priority:** P3.-- [ ] **P2 — Receipts for the pages, timeline and alias derived writers.** **What:** the wave 9 follow-ups put admitted persistence requests (receipts) on the managed-brain facts and takes writers it touches and add a coverage test that names every other guarded-table writer; the derived writers in `src/core/page-state/materialize.ts`, `src/core/timeline-extract.ts`, `src/commands/reindex-aliases.ts` and `src/core/mentions/pass.ts` still write on managed brains without one and are listed there with a TODO. **Fix:** admit a persistence request per derived batch (page revision as the CAS), then drop their TODO rows from the coverage table. **Effort:** M. **Priority:** P2.+- [ ] **P2 — Receipts for the pages, timeline and alias derived writers.** **What:** the wave 9 follow-ups put admitted persistence requests (receipts) on the managed-brain facts and takes writers it touches and add a coverage test that names every other guarded-table writer; the derived writers in `src/core/page-state/materialize.ts`, `src/core/timeline-extract.ts`, `src/commands/reindex-aliases.ts`, `src/core/mentions/pass.ts` and the `gbrain repair timeline-comments` row cleanup (`src/core/repair/timeline-comments.ts`, wave 12) still write on managed brains without one and are listed there with a TODO. **Fix:** admit a persistence request per derived batch (page revision as the CAS), then drop their TODO rows from the coverage table. **Effort:** M. **Priority:** P2.- [ ] **P2 — Production fail-closed receipt guard.** **What:** the receipt requirement (`gbrain.write_request` for facts and takes writes on managed brains) is enforced only in the contract-test harness plus the coverage table (Decision 10). **Fix:** once the coverage table lists no unreceipted writer, enforce it in the production guard function as well (fail closed; a function-only replace, no table lock), behind a `BEHAVIOR_CHANGES` row. **Effort:** S. **Priority:** P2.- [ ] **P3 — Owner delegation for every `gbrain repair` kind under a live serve.** **What:** while `gbrain serve` owns a PGLite brain, repair kinds that open the engine wait on its lock or refuse with stop, repair, restart. **Fix:** delegate each repair kind's preview and apply through the owner (as `takes remove` does), keeping preview hashes and `--expect` consent identical to the local path. **Effort:** M. **Priority:** P3.- [ ] **P3 — Typed `ShutdownInterruptedError` for cooperative handlers.** **What:** during worker shutdown only `UnrecoverableError` now burns an attempt (Decision 7); every other error from an in-process handler is still treated as a shutdown interruption, because cooperative handlers throw plain `Error`s (`subagent.ts`, `shell.ts`). **Fix:** have every cooperating handler throw a typed `ShutdownInterruptedError` on the shutdown abort, then take the requeue path only for that type so ordinary failures during a deploy burn an attempt. **Effort:** M. **Priority:** P3.diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.tsindex 98fe57acfe..71cfbd5e16 100644--- a/src/core/cycle/conversation-facts-backfill.ts+++ b/src/core/cycle/conversation-facts-backfill.ts@@ -61,6 +61,7 @@ import {import { ALLOWED_TYPES, type AllowedType } from '../facts/conversation-types.ts';import { conversationFactsCostCap } from '../facts/conversation-budget.ts';import { noPricingMessage } from '../budget/no-pricing.ts';+import { OperationError } from '../ops/contract.ts';/** Per-phase wrapper opts. */export interface ConversationFactsBackfillPhaseOpts {@@ -219,6 +220,7 @@ export async function runPhaseConversationFactsBackfill(let skippedByBrainWideWalltime = 0;let sourcesBudgetExhausted = 0;let sourcesWalltimeExhausted = 0;+ const sourcesNotOwned: string[] = [];let totalSpent = 0;const zeroResult = (): ExtractConversationFactsResult => ({@@ -347,6 +349,11 @@ export async function runPhaseConversationFactsBackfill(// is still cycle-runner control flow — propagate it rather than// downgrading it to a per-source failure record.throw err;+ } else if (err instanceof OperationError && err.code === 'owner_unavailable') {+ // Managed source owned by another host (or not activated here): its extraction publishes only on its owner,+ // like the fence_repair phase's skip. Reported, not counted as a failure.+ sourcesNotOwned.push(src.id);+ perSourceResults[src.id] = zeroResult();} else {// Per-source failure: record + continue with next source.perSourceResults[src.id] = {@@ -396,8 +403,8 @@ export async function runPhaseConversationFactsBackfill(resolution_errors: 0,sources_processed: 0,};- for (const r of Object.values(perSourceResults)) {- if (!r.error) totals.sources_processed++;+ for (const [id, r] of Object.entries(perSourceResults)) {+ if (!r.error && !sourcesNotOwned.includes(id)) totals.sources_processed++;totals.pages_processed += r.pages_processed;totals.pages_skipped += r.pages_skipped;totals.pages_skipped_unparsed += r.pages_skipped_unparsed;@@ -421,7 +428,8 @@ export async function runPhaseConversationFactsBackfill(const noPricing = [...new Map(Object.values(perSourceResults).flatMap((r) => r.budget_pricing ? [[r.budget_pricing.model, r.budget_pricing] as const] : [])).values()];const summary = `${totals.facts_inserted} facts inserted across ${totals.sources_processed}/${sources.length} sources, ~$${totalSpent.toFixed(4)} spent` +- noPricing.map((g) => `. ${noPricingMessage(g)}`).join('');+ noPricing.map((g) => `. ${noPricingMessage(g)}`).join('') ++ (sourcesNotOwned.length ? `. Skipped ${sourcesNotOwned.length} managed source(s) this host does not own (${sourcesNotOwned.join(', ')}); run the phase on their owner host` : '');return {phase: 'conversation_facts_backfill',@@ -451,6 +459,7 @@ export async function runPhaseConversationFactsBackfill(// #3627: per-source cap enforcement observability.sources_budget_exhausted: sourcesBudgetExhausted,sources_walltime_exhausted: sourcesWalltimeExhausted,+ sources_skipped_not_owner: sourcesNotOwned,no_pricing: noPricing,types: cfg.types,max_cost_usd: cfg.maxCostUsd,diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.tsindex ec0c1d782f..a789da9cbc 100644--- a/src/core/facts/conversation-publication.ts+++ b/src/core/facts/conversation-publication.ts@@ -455,7 +455,7 @@ async function applyEntry(tx: BrainEngine, row: WriteRequest, entry: Conversatioconst 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,+ ...fact, visibility: OUTCOME_SOURCES.has(fact.source) ? 'private' as const : 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,@@ -496,12 +496,10 @@ export async function prepareConversationFactsPublication(engine: BrainEngine, r/** A managed extraction run's publication context; null on an unmanaged brain or a dry run. */export interface ManagedConversationPublisher {engine: BrainEngine;- authority: MaintenanceAuthority;config: GBrainConfig;- /** The facts embedding signature frozen 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>;+ /** Resolves the run's publication context once, for the first page with managed work (`readyPublisher`). */+ prepare: () => Promise<ManagedPublisherRun>;+ run: Promise<ManagedPublisherRun> | null;/** Unsettled batches this run already waited for, by request row id. */settled: Map<string, WriteRequest>;/** The batch being filled, and its entries' intent bytes. */@@ -509,6 +507,17 @@ export interface ManagedConversationPublisher {bytes: number;}+interface ManagedPublisherRun {+ authority: MaintenanceAuthority;+ /** 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>;+}++/** Errors from resolving a run's publication context: they stop the run, not one page. */+const RUN_STOPPING = new WeakSet<object>();+/** 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_failed: number;@@ -531,28 +540,40 @@ export interface ManagedPageStart { generation: Generation; attempt: number; sinconst 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, check that the planned batch- * requests fit the writer's request capacity, and read its unsettled and- * failed batches.+ * On a managed brain (not a dry run, which writes and registers nothing),+ * the run's publisher. Once per run, at the first page with managed work and+ * before its model call, it preflights the maintenance authority, resolves+ * the facts embedding signature, checks that the planned batch requests fit+ * the writer's request capacity, and reads its unsettled and failed batches;+ * a failure there stops the run. A run with nothing to publish preflights+ * nothing, so a source whose owner is on another host is not reported failed.*/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> {if (opts.dryRun || !await managedPersistenceEnabled(engine)) return null;- const 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),- index: await loadGenerationIndex(engine, authority), settled: new Map(), batch: [], bytes: 0 };+ const prepare = async (): Promise<ManagedPublisherRun> => {+ const authority = (await maintenancePreflight(engine, sourceId))!;+ await assertConversationAdmissionHeadroom(engine, authority, await plannedAdmissions(engine, sourceId, opts));+ return { authority, embedding: await resolveManagedFactsEmbedding(engine, config), index: await loadGenerationIndex(engine, authority) };+ };+ return { engine, config, prepare, run: null, settled: new Map(), batch: [], bytes: 0 };+}++/** The run's publication context, resolved by its first page with managed work, so a run with nothing to publish never preflights. */+function readyPublisher(m: ManagedConversationPublisher): Promise<ManagedPublisherRun> {+ return m.run ??= m.prepare().catch((error: unknown) => {+ if (error && typeof error === 'object') RUN_STOPPING.add(error);+ throw error;+ });}-async function settledRequest(m: ManagedConversationPublisher, id: string): Promise<WriteRequest> {+async function settledRequest(m: ManagedConversationPublisher, r: ManagedPublisherRun, 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 wait = r.authority.wait!;const row = wait.observe(await waitForWrite(m.engine, prior, m.config, wait.ms()));m.settled.set(id, row);return row;@@ -568,14 +589,15 @@ async function settledRequest(m: ManagedConversationPublisher, id: string): Promexport async function startManagedPage(state: ManagedRunState, snapshot: PageSnapshot, sinceIso: string | undefined, segments: number,): Promise<{ done: { newEndIso: null } } | { start: ManagedPageStart }> {const m = state.managed!;+ const r = await readyPublisher(m);const { page } = snapshot;const done = { done: { newEndIso: null } } as const;- const generation = await conversationGeneration(m.engine, m.authority, {+ const generation = await conversationGeneration(m.engine, r.authority, {slug: page.slug, page, versionToken: snapshot.versionToken, since: sinceIso ?? null, segmentLimit: state.segmentLimit,});- const history = m.index.get(generation.key) ?? { pending: null, failed: [] };+ const history = r.index.get(generation.key) ?? { pending: null, failed: [] };if (history.pending) {- const row = await settledRequest(m, history.pending.id);+ const row = await settledRequest(m, r, 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)`);@@ -600,14 +622,14 @@ export async function startManagedPage(state: ManagedRunState, snapshot: PageSnaconst 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 (!m.batch.length) await assertConversationAdmissionHeadroom(m.engine, r.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;}const planned = state.segmentLimit > 0 ? Math.min(segments, state.segmentLimit) : segments;- const estimate = estimateConversationIntentBytes(planned, m.embedding);+ const estimate = estimateConversationIntentBytes(planned, r.embedding);const limit = await conversationIntentByteLimit(m.engine);if (estimate > limit) {state.result.pages_skipped_too_large++;@@ -671,7 +693,7 @@ export async function flushManagedBatch(state: ManagedRunState, opts: { afterErrconst pages = m.batch.splice(0);m.bytes = 0;try {- const receipt = await submitConversationPages(m.engine, m.authority, pages);+ const receipt = await submitConversationPages(m.engine, (await readyPublisher(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) {@@ -688,5 +710,6 @@ export async function flushManagedBatch(state: ManagedRunState, opts: { afterErr}/** 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');+ return (!!err && typeof err === 'object' && RUN_STOPPING.has(err))+ || (err instanceof OperationError && (err.code === 'maintenance_backpressure' || err.code === 'queue_capacity'));}diff --git a/test/conversation-facts-managed.test.ts b/test/conversation-facts-managed.test.tsindex 1fd00f5151..8b2fe1f2f4 100644--- a/test/conversation-facts-managed.test.ts+++ b/test/conversation-facts-managed.test.ts@@ -11,7 +11,8 @@* 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+ * model call; a source this host does not own preflights only when a page+ * needs work. 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), the maintenance wait and batch-cap test seams.@@ -415,6 +416,27 @@ for (const backend of testBackends()) {expect(calls.n).toBe(0);}, { databaseUrl });}, 120_000);++ test(`${backend}: a source owned by another host preflights nothing when no page needs work, and stops before any model call when one does`, async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ const other = 'meetings/2026-09-29-plan-sync';+ await putPage(brain, transcript());+ await putPage(brain, transcript().replace('Plan sync', 'Plan sync 29'), other);+ const calls = { n: 0 };+ expect(await extract(engine, calls)).toMatchObject({ pages_processed: 1, pages_failed: 0 });+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");+ await tx.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$1::uuid', [randomUUID()]);+ });+ expect(await extract(engine, calls)).toMatchObject({ pages_processed: 0, pages_failed: 0 });+ const error = await runExtractConversationFactsCore(engine, { sourceId: 'default', sleepMs: 0, overrideDisabled: true,+ extractor: async () => { calls.n++; return []; } }).then(() => null, (e: Error & { code?: string }) => e);+ expect(error?.code).toBe('owner_unavailable');+ expect(calls.n).toBe(1);+ expect(await factsOf(engine, other)).toEqual([]);+ }, { databaseUrl });+ }, 120_000);}test('a lost insert fails the replacement instead of committing a partial batch', async () => {diff --git a/test/persistence-local-only-ops.test.ts b/test/persistence-local-only-ops.test.tsindex 0538ea0390..ec62b557a7 100644--- a/test/persistence-local-only-ops.test.ts+++ b/test/persistence-local-only-ops.test.ts@@ -136,7 +136,8 @@ describe('localOnly skill administration through a resident owner', () => {const { extractTakes } = await import('../src/core/cycle/extract-takes.ts');const local = { slug, source_id: 'default', ...await extractTakes(engine, { source: 'db', slugs: [slug], sourceId: 'default', rebuild: true }) };expect(JSON.parse(rebuilt.stdout)).toEqual(JSON.parse(JSON.stringify(local)));- expect(local.takesUpserted).toBe(2);+ // A managed page already in sync admits no takes request (wave 9 follow-ups receipts), so neither rebuild rewrites its two rows.+ expect(local).toMatchObject({ pagesScanned: 1, pagesWithTakes: 1, takesUpserted: 0 });const missing = await cli(['takes', 'rebuild', 'notes/ipc-no-such-page', '--json']);expect(missing.code).toBe(1);expect(JSON.parse(missing.stdout)).toMatchObject({ pagesScanned: 0 });diff --git a/test/receipt-coverage.test.ts b/test/receipt-coverage.test.tsindex 4cbc942e9b..573ea0a946 100644--- a/test/receipt-coverage.test.ts+++ b/test/receipt-coverage.test.ts@@ -37,6 +37,7 @@ const RECEIPT_COVERAGE: Record<string, Coverage> = {'src/core/page-state/materialize.ts': { sites: 1, tables: ['pages'], todo: 'TODO(receipts): derived page materialization should publish as a maintenance intent' },'src/core/timeline-extract.ts': { sites: 1, tables: ['timeline_entries'], todo: 'TODO(receipts): timeline retraction should publish like managed_maintenance_timeline_extract' },'src/commands/reindex-aliases.ts': { sites: 1, tables: ['page_aliases', 'slug_aliases'], todo: 'TODO(receipts): reindex --aliases should publish per page as a maintenance intent' },+ 'src/core/repair/timeline-comments.ts': { sites: 1, tables: ['timeline_entries'], todo: 'TODO(receipts): gbrain repair timeline-comments row cleanup should publish per page as a maintenance intent' },'src/core/mentions/pass.ts': { sites: 1, tables: ['page_aliases'], todo: 'TODO(receipts): derived alias rows should publish per page as a maintenance intent' },'src/core/bootstrap/verify.ts': { sites: 1, tables: ['facts'], todo: 'TODO(receipts): bootstrap verify deletes its own probe facts without a request; publish the cleanup as a maintenance intent' },'src/core/cycle/concept-publication.ts': { sites: 1, tables: [], other: 'concept provenance links (links is not a guarded table)' },