Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): managed conversation facts and the receipted fence reconcile declare their page taint and pass the write gate (#5575 L1a-taint)
garrytanb0c8ab2fa5b4
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 8510930e39..811781917d 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -32,7 +32,7 @@ src/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refasrc/core/context/retrieval-reflex.ts resolveEntitiesToPointers 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 fix wave 11 #6195: multi-word weak n-gram norms and the weak-title arm call (logic in weakTitleHits)src/core/cycle.ts runCycle 1279 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts); +6 #6188: fence_repair phase dispatch block (logic in cycle/fence-repair.ts); +2 fix wave 12 #6242: lease-set result and the maintenance-busy skip call (logic in skipBrainWidePhases and cycle/lock-set.ts)src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 790 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts); +1 #5031: per-run page-atom title memo for the case-insensitive adoption fallback-src/core/cycle/extract-facts.ts runExtractFacts 380 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); -129 wave 9 follow-ups (receipts): the page reconcile plan and writes moved into planFenceReconcile/reconcileWrites/writeFenceReconcile, shared with the managed preparer; +2 #6264 (landed alongside): ontology observations never gate the unfenced-rows count; +2 #6259 (landed alongside): a quarantined page projects no fence facts+src/core/cycle/extract-facts.ts runExtractFacts 381 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); -129 wave 9 follow-ups (receipts): the page reconcile plan and writes moved into planFenceReconcile/reconcileWrites/writeFenceReconcile, shared with the managed preparer; +2 #6264 (landed alongside): ontology observations never gate the unfenced-rows count; +2 #6259 (landed alongside): a quarantined page projects no fence facts; +1 #5575 I2 (L1a-taint): the run result sums the write-gate tally each page reconcile returnssrc/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/propose-takes.ts ProposeTakesPhase.process 429 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout)src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 490 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts)diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 1d41440c8b..9d0763af51 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -52,7 +52,7 @@ import { isTerminal, type WriteRequest } from '../persistence/model.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { withWriteTrust } from '../persistence/context.ts';import { deriveTrust, recordTaintEdges } from '../trust/taint.ts';-import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';+import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, mergeGateTally, type GateTally } from '../trust/derived-gate.ts';import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';import { authorizeWrite } from '../persistence/authority.ts';import { digest } from '../persistence/digest.ts';@@ -445,7 +445,8 @@ function reconcileWrites(plan: FenceReconcilePlan) {/** One page's reconcile writes, inside a transaction that holds the page key. */async function writeFenceReconcile(tx: BrainEngine, sourceId: string, slug: string, plan: FenceReconcilePlan,- writes: ReturnType<typeof reconcileWrites>, signal?: AbortSignal, tally: GateTally = emptyGateTally()): Promise<{ inserted: number; updated: number; warnings: string[] }> {+ writes: ReturnType<typeof reconcileWrites>, signal?: AbortSignal): Promise<{ inserted: number; updated: number; warnings: string[]; write_gate?: GateTally }> {+ const tally = emptyGateTally();// #5575 I2: the fence rows restate the page (no model), so every write here is at the page's tier, capped at operator_curated.const derivation = await deriveTrust(tx, [{ table: 'pages', sourceId, slug }], { channel: 'derive:facts_fence', projection: true });return withWriteTrust(tx, derivation.trust, async () => {@@ -479,7 +480,7 @@ async function writeFenceReconcile(tx: BrainEngine, sourceId: string, slug: striconst linked = await syncSupersession(tx, sourceId, slug, plan.extracted, plan.chain, insertedRows);signal?.throwIfAborted();const updated = new Set([...plan.updates.map(f => f.row_num), ...linked.changed.filter(row => !insertedRows.has(row))]);- return { inserted: inserted.inserted, updated: updated.size, warnings: linked.warnings };+ return { inserted: inserted.inserted, updated: updated.size, warnings: linked.warnings, ...(mergeGateTally(tally, undefined) ? { write_gate: tally } : {}) };});}@@ -545,10 +546,8 @@ export async function prepareFenceFactsReconcile(engine: BrainEngine, row: Writeif (vector) { fact.embedding = new Float32Array(vector.vector); fact.embedding_model = vector.model; }}const writes = reconcileWrites(plan);- const tally = emptyGateTally();- const written = await writeFenceReconcile(tx, row.source_id, row.slug, plan, writes, undefined, tally);+ const written = await writeFenceReconcile(tx, row.source_id, row.slug, plan, writes);return { status: 'completed', ...written, deleted: writes.detach.length + writes.expireInPlace.length, deferred: writes.deferInserts,- ...(tally.flagged || tally.held || tally.rejected ? { write_gate: tally } : {}),warnings: [...warnings, ...written.warnings] };} };}@@ -745,7 +744,6 @@ export async function runExtractFacts(// preflighted on the first page that needs a write, so a run with nothing// to change never needs one; an unacceptable caller still refuses first.const managed = await maintenanceCallerPreflight(engine, sourceId);- const gateTally = emptyGateTally();let authority: Promise<MaintenanceAuthority | null> | undefined;const managedAuthority = () => managed ? authority ??= maintenancePreflight(engine, sourceId) : Promise.resolve(null);const result: ExtractFactsResult = {@@ -1021,7 +1019,7 @@ export async function runExtractFacts(if (watermark && !await lockReconcileRevision(tx, sourceId, slug, page.knowledge_revision ?? null)) return null;const current = await tx.getPage(slug, { sourceId });if (!current || current.compiled_truth !== page.compiled_truth || current.timeline !== page.timeline) return null;- const written = await writeFenceReconcile(tx, sourceId, slug, plan, writes, opts.signal, gateTally);+ const written = await writeFenceReconcile(tx, sourceId, slug, plan, writes, opts.signal);if (watermark && !deferInserts) await settleFactsReconcile(tx, sourceId, slug, 'complete', page.knowledge_revision ?? null);return written;});@@ -1046,7 +1044,7 @@ export async function runExtractFacts(result.factsDeleted += outcome.deleted ?? detach.length + expireInPlace.length;// resolveSupersededByRow prefixes each message with the slug + row.for (const w of outcome.warnings) result.warnings.push(w);- if (outcome.write_gate) { gateTally.flagged += outcome.write_gate.flagged; gateTally.held += outcome.write_gate.held; gateTally.rejected += outcome.write_gate.rejected; }+ if (outcome.write_gate) result.writeGate = mergeGateTally(result.writeGate, outcome.write_gate);return (outcome.deferred ?? deferInserts) ? 'deferred' : 'complete';};@@ -1115,7 +1113,6 @@ export async function runExtractFacts(});}- if (gateTally.flagged || gateTally.held || gateTally.rejected) result.writeGate = gateTally;return result;}diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.tsindex 4936384bc3..72d3fb61ea 100644--- a/src/core/facts/conversation-publication.ts+++ b/src/core/facts/conversation-publication.ts@@ -71,6 +71,11 @@ import { waitForWrite } from '../persistence/service.ts';import { catalogueError } from '../error-catalogue.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';+import { withWriteTrust } from '../persistence/context.ts';+import { conversationDerivation } from '../persistence/derived-facts.ts';+import { recordTaintEdges } from '../trust/taint.ts';+import { applyGateDecision, derivedGateConfig, derivedGateInput } from '../trust/derived-gate.ts';+import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';export const CONVERSATION_FACTS_INTENT = 'managed_maintenance_conversation_facts';export const CONVERSATION_FACTS_PROTOCOL = 1;@@ -386,18 +391,18 @@ async function mergedEntities(tx: BrainEngine, sourceId: string, slugs: string[]* 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 }> {+ rows: Array<Omit<ConversationFactRow, 'row_num' | 'source_markdown_slug'>>): Promise<{ deleted: number; inserted: number; ids: number[] }> {const deleted = await clearConversationFacts(tx, sourceId, slug);- if (!rows.length) return { deleted, inserted: 0 };+ if (!rows.length) return { deleted, inserted: 0, ids: [] };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)+ const { inserted, ids } = 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, inserted };+ return { deleted, inserted, ids };}/** Context marker `gbrain repair conversation-labels` appends to the rows it retires. */@@ -459,9 +464,21 @@ async function applyEntry(tx: BrainEngine, row: WriteRequest, entry: Conversatioembedding: 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);+ // #5575 I2/B3: the rows carry the conversation page's tier and pass the write gate at it; outcome audit rows are not gated.+ const derivation = await conversationDerivation(tx, row.source_id, entry.slug);+ const cfg = await derivedGateConfig(tx);+ const decisions = rows.map(fact => OUTCOME_SOURCES.has(fact.source) ? null : decideFactWrite(fact,+ { sourceId: row.source_id, slug: entry.slug, payload: { ...fact, embedding: null }, input: derivedGateInput(derivation.trust, row.id), cfg }));+ for (const d of decisions) if (d && d.action !== 'insert') await applyGateDecision(tx, d, { table: 'facts', sourceId: row.source_id }, async () => null);+ const kept = rows.filter((_, i) => decisions[i]?.action !== 'hold' && decisions[i]?.action !== 'reject');+ const flags = decisions.filter(d => d?.action !== 'hold' && d?.action !== 'reject');+ const { deleted, ids } = await withWriteTrust(tx, derivation.trust, () => replaceConversationFacts(tx, row.source_id, entry.slug, kept));+ for (const [i, id] of ids.entries()) {+ await recordTaintEdges(tx, { table: 'facts', id, sourceId: row.source_id }, derivation.inputs);+ if (flags[i] && ids.length === kept.length) await recordFlaggedRow(tx, flags[i]!, { table: 'facts', id, sourceId: row.source_id });+ }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,+ return { ...base, status: 'committed', deleted, facts_inserted: kept.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 };}diff --git a/src/core/trust/derived-gate.ts b/src/core/trust/derived-gate.tsindex 91405cdf3f..ff071cb951 100644--- a/src/core/trust/derived-gate.ts+++ b/src/core/trust/derived-gate.ts@@ -27,6 +27,11 @@ export function derivedGateInput(trust: WriteTrust, requestId?: string | null):/** What one run's gate did, for the run result. */export interface GateTally { flagged: number; held: number; rejected: number }export const emptyGateTally = (): GateTally => ({ flagged: 0, held: 0, rejected: 0 });+/** Sums two tallies; undefined while nothing was flagged, held or rejected (a run result shows the field only when the gate acted). */+export function mergeGateTally(into: GateTally | undefined, from: GateTally | undefined): GateTally | undefined {+ const sum = { flagged: (into?.flagged ?? 0) + (from?.flagged ?? 0), held: (into?.held ?? 0) + (from?.held ?? 0), rejected: (into?.rejected ?? 0) + (from?.rejected ?? 0) };+ return sum.flagged || sum.held || sum.rejected ? sum : undefined;+}/*** Applies one decision inside the writer's transaction: `insert` runs the