Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): facts derivers carry the source page's taint (#5575 L1a-taint, ENG-3, CEO-1, ENG-7)
garrytan10527529b74b
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 40ac8075fe..4490c27f5d 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -235,7 +235,7 @@ or a physical projection that leaves attribution untouched):- `src/core/embed-facts.ts` (1): embedding columns only (physical projection).- `src/core/embedding-dim-check.ts` (1): embedding columns only (physical projection).- `src/core/extract/receipt-writer.ts` (1): the extraction receipt page runs in `maintenanceTransaction`.-- `src/core/facts/backstop.ts` (3): the facts backstop's DB-only fallbacks insert each fact in `maintenanceTransaction`; managed brains publish through the facts request preparer.+- `src/core/facts/backstop.ts` (1): the facts backstop's DB-only fallbacks insert each fact through one helper, in `maintenanceTransaction` at the extraction's derived tier; managed brains publish through the facts request preparer.- `src/core/facts/derivation-inputs.ts` (3): `hideDerivedRows` expires derived facts, deactivates derived takes and soft-deletes derived pages inside the purge's coordinated transaction, attributed to the purge request.- `src/core/facts/fence-write.ts` (2): the markdown-first fence reconcile insert and its page body mirror each run in `maintenanceTransaction`.- `src/core/facts/forget.ts` (4): the legacy fence expiry, withdrawal and strike-through each run in `maintenanceTransaction` (nested inside a caller's coordinated write, they keep its actor).diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 906d75cf6c..872936e90f 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -47,6 +47,9 @@ import { existsSync, readFileSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';import { managedDerivedFactsPreflight, withDerivedFactsWrite } from '../persistence/derived-facts.ts';+import { withWriteTrust } from '../persistence/context.ts';+import { deriveTrust, recordTaintEdges } from '../trust/taint.ts';+import type { WriteTrust } from '../trust/tier.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import {resolveSupersededByRow,@@ -453,8 +456,8 @@ export async function runExtractFacts(// Managed brains reconcile the same way, but each database write commits// inside the coordinator's source capability under the page key.const managed = await managedDerivedFactsPreflight(engine, sourceId);- const transact = <T>(slugs: string[], fn: (tx: BrainEngine) => Promise<T>): Promise<T> =>- managed ? withDerivedFactsWrite(engine, sourceId, slugs, fn) : maintenanceTransaction(engine, fn);+ const transact = <T>(slugs: string[], fn: (tx: BrainEngine) => Promise<T>, trust?: WriteTrust): Promise<T> =>+ managed ? withDerivedFactsWrite(engine, sourceId, slugs, tx => trust ? withWriteTrust(tx, trust, () => fn(tx)) : fn(tx)) : maintenanceTransaction(engine, fn, trust);const result: ExtractFactsResult = {pagesScanned: 0,pagesWithFacts: 0,@@ -813,6 +816,8 @@ export async function runExtractFacts(result.warnings.push(`${slug}: destructive fact reconciliation deferred; existing vectors preserved until embedding succeeds`);}+ // #5575 I2: the fence rows restate the page (no model): they take its tier, capped at operator_curated.+ const derivation = await deriveTrust(engine, [{ table: 'pages', id: page.id }], { channel: 'derive:facts_fence', projection: true });const apply = async () => {try {return await transact([slug], async tx => {@@ -851,13 +856,14 @@ export async function runExtractFacts(inserts.map(f => ({ ...f, superseded_by_row: undefined })),{ source_id: sourceId },);+ for (const id of (inserted as { ids?: number[] }).ids ?? []) await recordTaintEdges(tx, { table: 'facts', id, sourceId }, derivation.inputs);const insertedRows = new Set(inserts.map(f => f.row_num));const linked = await syncSupersession(tx, sourceId, slug, extracted, chain, insertedRows);opts.signal?.throwIfAborted();const updated = new Set([...updates.map(f => f.row_num), ...linked.changed.filter(row => !insertedRows.has(row))]);if (watermark && !deferInserts) await settleFactsReconcile(tx, sourceId, slug, 'complete', page.knowledge_revision ?? null);return { inserted: inserted.inserted, updated: updated.size, warnings: linked.warnings };- });+ }, derivation.trust);} catch (error) {if (!isAborted(opts.signal)) throw error;result.warnings.push(`${slug}: fact reconciliation cancelled; transaction rolled back`);diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 8fd21257b3..a7ad0e3e55 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -55,6 +55,8 @@ import { appendContextNote, type InferredVia } from './subject-infer.ts';import { inferenceNote, inferMissingSubjects } from './subject-infer-write.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import type { FactNotabilityFilter } from './notability-filter.ts';+import { intentContentOrigin } from '../trust/channel.ts';+import { readTaintInputs, derivedWriteTrust, recordTaintEdges } from '../trust/taint.ts';// The notability-filter vocabulary lives in notability-filter.ts; re-exported for existing importers.export { NOTABILITY_FILTERS, coerceNotabilityFilter, type FactNotabilityFilter } from './notability-filter.ts';@@ -190,6 +192,23 @@ const DEDUP_CANDIDATE_LIMIT = 5;* on every put_page in a long-running brain.*/const _warnedKeys = new Set<string>();++/**+ * #5575 I2: the extractor's context is the source page (or the page a turn+ * came from) plus the caller's turn text, so the facts' tier is the page's+ * stored tier capped at agent_written, lowered by the caller's content+ * origin. The facts-absorb job carries the page tier, never its runner's+ * identity. A `sourceSlug` that names no page adds no input.+ */+async function factsDerivation(ctx: FactsBackstopCtx, input: PipelineInput) {+ const inputs = (await readTaintInputs(ctx.engine, [...new Set([input.pageSlug, ctx.sourceSlug].filter((s): s is string => !!s))]+ .map(slug => ({ table: 'pages' as const, sourceId: ctx.sourceId, slug }))))+ .filter(i => typeof i.id === 'number' || i.id === `${ctx.sourceId}:${input.pageSlug}`);+ const lowered = intentContentOrigin(ctx.requestIntent);+ const trust = derivedWriteTrust({ channel: input.pageSlug ? 'derive:facts_backstop' : 'derive:extract_facts', inputs,+ lowerTo: lowered ? [lowered] : [], requestId: ctx.persistenceRequestId ?? null });+ return { trust, inputs };+}function warnOnce(key: string, msg: string): void {if (_warnedKeys.has(key)) return;_warnedKeys.add(key);@@ -611,7 +630,8 @@ async function runPipelineBodyInner(}const { prepareManagedFactsSession, resumeManagedFacts, publishManagedFacts, resolveManagedFactsEmbedding,assertManagedFactsEmbedding } = await import('../persistence/facts-maintenance.ts');- const managed = await prepareManagedFactsSession(ctx, input);+ const derivation = await factsDerivation(ctx, input);+ const managed = await prepareManagedFactsSession(ctx, input, derivation);if (managed) {const replay = await resumeManagedFacts(ctx.engine, managed);if (replay) return replay;@@ -682,6 +702,12 @@ async function runPipelineBodyInner(if (!managed) await assertAmbientCaptureAdmissible(ctx.engine, ctx.source);if (managed) return withCaptureDrops(dropped, facts.length || !dropped.length ? await publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug) : null);+ // Every DB-only insert below: one attributed transaction at the derived tier, with input edges for a new row.+ const insertDerivedFact = (newFact: NewFact) => maintenanceTransaction(ctx.engine, async tx => {+ const result = await tx.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: the facts backstop's DB-only fallbacks (unparented / thin-client facts, stub-guard or unresolvable targets, a declined fence lane)+ if (result.status !== 'duplicate') await recordTaintEdges(tx, { table: 'facts', id: result.id, sourceId: ctx.sourceId }, derivation.inputs);+ return result;+ }, derivation.trust);let inserted = 0;let duplicate = dropped.length;let superseded = 0;@@ -817,7 +843,7 @@ async function runPipelineBodyInner(valid_from: factEventTime(f, ctx),context: annotateUnverifiedResolution(ctx.sourceSlug ?? input.pageSlug ?? null, resolutionSource, f.entity_inferred),};- const result = await maintenanceTransaction(ctx.engine, tx => tx.insertFact(newFact, { source_id: ctx.sourceId })); // gbrain-allow-direct-insert: legacy DB-only fallback for unparented / thin-client facts (no entity page to fence onto)+ const result = await insertDerivedFact(newFact); // legacy DB-only fallback for unparented / thin-client facts (no entity page to fence onto)fact_ids.push(result.id);if (result.status === 'inserted') inserted += 1;else if ((result.status as FactInsertStatus) === 'duplicate') duplicate += 1;@@ -867,6 +893,7 @@ async function runPipelineBodyInner(ctx.engine,{ sourceId: ctx.sourceId, localPath, slug, resolutionSource: groupResolutionSource },inputFacts,+ derivation,);if (result.fenceWriteFailed) {@@ -904,7 +931,7 @@ async function runPipelineBodyInner(valid_from: factEventTime(f, ctx),context: ctx.sourceSlug ?? input.pageSlug ?? null,};- const legacyResult = await maintenanceTransaction(ctx.engine, tx => tx.insertFact(newFact, { source_id: ctx.sourceId })); // gbrain-allow-direct-insert: stub-guard / unresolvable-target fallback for unprefixed or fallback-resolved entity slugs (no fenceable page or usable tree)+ const legacyResult = await insertDerivedFact(newFact); // stub-guard / unresolvable-target fallback for unprefixed or fallback-resolved entity slugs (no fenceable page or usable tree)fact_ids.push(legacyResult.id);if (legacyResult.status === 'inserted') inserted += 1;else if ((legacyResult.status as FactInsertStatus) === 'duplicate') duplicate += 1;@@ -937,7 +964,7 @@ async function runPipelineBodyInner(valid_from: factEventTime(f, ctx),context: ctx.sourceSlug ?? input.pageSlug ?? null,};- const legacyResult = await maintenanceTransaction(ctx.engine, tx => tx.insertFact(newFact, { source_id: ctx.sourceId })); // gbrain-allow-direct-insert: DB-only fallback when the fence lane declined the write (write_through opt-out race / localPath echo)+ const legacyResult = await insertDerivedFact(newFact); // DB-only fallback when the fence lane declined the write (write_through opt-out race / localPath echo)fact_ids.push(legacyResult.id);if (legacyResult.status === 'inserted') inserted += 1;else if ((legacyResult.status as FactInsertStatus) === 'duplicate') duplicate += 1;diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex e5498a12fe..15562a804c 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -56,6 +56,9 @@ import { logStubGuardEvent } from './stub-guard-audit.ts';import { isFactWithdrawn } from './withdrawal.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';+import { withTrustKeep } from '../persistence/context.ts';+import { recordTaintEdges } from '../trust/taint.ts';+import type { TaintInput, WriteTrust } from '../trust/tier.ts';/** Resolved source binding for the entity page. */export interface FenceTarget {@@ -288,6 +291,8 @@ export async function writeFactsToFence(engine: BrainEngine,target: FenceTarget,facts: FenceInputFact[],+ /** #5575 I2: a deriver's taint; the new rows get its tier and input edges. Unmanaged path only. */+ derivation?: { trust: WriteTrust; inputs: readonly TaintInput[] },): Promise<FenceWriteResult> {if (await managedPersistenceEnabled(engine)) {// The coordinator owns the canonical file on a managed brain: publish the@@ -523,9 +528,9 @@ export async function writeFactsToFence(const reparsed = parseMarkdown(tmpBody, `${target.slug}.md`);const existing = await engine.getPage(target.slug, { sourceId: target.sourceId });if (existing) {- await maintenanceTransaction(engine, tx => tx.refreshPageBody(target.slug, target.sourceId,+ await maintenanceTransaction(engine, tx => withTrustKeep(tx, ['pages'], () => tx.refreshPageBody(target.slug, target.sourceId,sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),- existing.content_hash || contentHash(existing)));+ existing.content_hash || contentHash(existing))));}} catch (err) {// The file is committed; the page cache stays stale until the next@@ -554,7 +559,11 @@ export async function writeFactsToFence(source_session: facts[i].sessionId,}));- const result = await maintenanceTransaction(engine, tx => tx.insertFacts(enriched, { source_id: target.sourceId })); // gbrain-allow-direct-insert: writeFactsToFence is the markdown-first reconcile path; runs only after the atomic fence write commits+ const result = await maintenanceTransaction(engine, async tx => {+ const inserted = await tx.insertFacts(enriched, { source_id: target.sourceId }); // gbrain-allow-direct-insert: writeFactsToFence is the markdown-first reconcile path; runs only after the atomic fence write commits+ for (const id of derivation ? inserted.ids : []) await recordTaintEdges(tx, { table: 'facts', id, sourceId: target.sourceId }, derivation!.inputs);+ return inserted;+ }, derivation?.trust);// v0.46 (#3014) — an unresolvable `superseded by #N` reference (self// / dangling / struck target) leaves superseded_by NULL; log it rather// than swallow it. The row still lands (expired_at set for struckdiff --git a/src/core/persistence/derived-facts.ts b/src/core/persistence/derived-facts.tsindex 86360c3e21..9117ab1611 100644--- a/src/core/persistence/derived-facts.ts+++ b/src/core/persistence/derived-facts.ts@@ -3,7 +3,8 @@ import type { Action } from '../agent-output.ts';import { opError } from '../ops/contract.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';-import { withCoordinatedWrite } from './context.ts';+import { withCoordinatedWrite, withWriteTrust } from './context.ts';+import { deriveTrust, recordTaintEdges } from '../trust/taint.ts';import { maintenanceAttribution, maintenanceTransaction } from './attribution.ts';import { currentVerifiedLocalWriter } from './identity.ts';import { managedPersistenceEnabled } from './ownership.ts';@@ -54,6 +55,21 @@ export async function withDerivedFactsWrite<T>(engine: BrainEngine, sourceId: st}, attribution));}+/**+ * #5575 I2: the conversation fact extractor's context is the page alone, so+ * its rows carry the page's stored tier capped at agent_written (an+ * own-session transcript import is agent_written, a third-party one+ * external_untrusted) and an edge to the page.+ */+const conversationDerivation = (engine: BrainEngine, sourceId: string, slug: string) =>+ deriveTrust(engine, [{ table: 'pages', sourceId, slug }], { channel: 'derive:conversation_facts' });++/** Edges for the fact ids a batch insert returned (`{ ids }`); other results (deletes, counts) record none. */+async function recordInsertedEdges(tx: BrainEngine, sourceId: string, result: unknown, inputs: Awaited<ReturnType<typeof conversationDerivation>>['inputs']) {+ const ids = (result as { ids?: unknown } | null)?.ids;+ for (const id of Array.isArray(ids) ? ids : []) await recordTaintEdges(tx, { table: 'facts', id: Number(id), sourceId }, inputs);+}+/*** Legacy writers run in one maintenance transaction on unmanaged brains. On a* managed brain the page must still be live under its lock, so rows are never@@ -61,14 +77,16 @@ export async function withDerivedFactsWrite<T>(engine: BrainEngine, sourceId: st*/export async function writeDerivedFacts<T>(engine: BrainEngine, sourceId: string, slug: string,fn: (db: BrainEngine) => Promise<T>): Promise<T> {- if (!await managedPersistenceEnabled(engine)) return maintenanceTransaction(engine, fn);+ const { trust, inputs } = await conversationDerivation(engine, sourceId, slug);+ const write = async (db: BrainEngine) => { const result = await fn(db); await recordInsertedEdges(db, sourceId, result, inputs); return result; };+ if (!await managedPersistenceEnabled(engine)) return maintenanceTransaction(engine, write, trust);return withDerivedFactsWrite(engine, sourceId, [slug], async tx => {const [page] = await tx.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);if (!page) {throw opError('page_not_found', 'The page was deleted during fact extraction; nothing was written.',`Page ${slug} in source ${sourceId} was deleted while its facts were extracted, so nothing was written. No action is needed unless the page should still exist.`);}- return fn(tx);+ return withWriteTrust(tx, trust, () => write(tx));});}@@ -94,7 +112,12 @@ export async function replaceDerivedFactsForPage(engine: BrainEngine, sourceId:`WITH del AS (DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND source LIKE $3 RETURNING 1)SELECT COUNT(*)::text AS count FROM del`, [sourceId, slug, `${input.sourcePrefix}%`]);const rows = await input.build(tx);- const { inserted } = rows.length ? await tx.insertFacts(rows, { source_id: sourceId }) : { inserted: 0 }; // gbrain-allow-direct-insert: managed replacement of a page's derived fact batch inside the coordinator transaction that deleted the prior batch+ const { trust, inputs } = await conversationDerivation(tx, sourceId, slug);+ const { inserted } = rows.length ? await withWriteTrust(tx, trust, async () => {+ const result = await tx.insertFacts(rows, { source_id: sourceId }); // gbrain-allow-direct-insert: managed replacement of a page's derived fact batch inside the coordinator transaction that deleted the prior batch+ await recordInsertedEdges(tx, sourceId, result, inputs);+ return result;+ }) : { inserted: 0 };return { deleted: Number(deleted?.count ?? 0), inserted };});}diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex f5b84b2963..174e120325 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -30,6 +30,8 @@ import { digest, requireUuid, sha256 } from './digest.ts';import { isTerminal, type WriteAuthority, type WriteRequest } from './model.ts';import type { WriteReceipt } from './types.ts';import { assertAmbientCaptureAdmissible, captureGateLaneForSource } from '../facts/capture-sources.ts';+import { declareDerivation, type DerivationDeclaration } from '../trust/taint.ts';+import type { TaintInput, WriteTrust } from '../trust/tier.ts';export interface ManagedFactsResult {inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; write_requests: WriteReceipt[];@@ -54,6 +56,8 @@ export interface ManagedFactIntent extends Record<string, unknown> {embedding?: FactEmbeddingSignature | null;/** #6091: the ambient capture lane (`hook:*`, `sweep:*`) the facts came from; admission re-checks its gate. */capture_source?: string;+ /** #5575 I2: the extraction's taint, declared at prompt-build time (trust/taint.ts). */+ derivation?: DerivationDeclaration;}export interface ManagedFactsSession {authority: WriteAuthority; binding: WorktreeBinding | null; config: GBrainConfig;@@ -64,6 +68,7 @@ export interface ManagedFactsSession {fileRefusalRetry?: boolean;/** #6091: set when the facts come from an ambient capture lane. */captureSource?: string;+ derivation?: DerivationDeclaration;}/** #6048: follow-up batches one input-keyed extraction may admit for file-check refusals. */@@ -153,7 +158,7 @@ export async function assertManagedFactsEmbedding(engine: BrainEngine, config: G}export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,- input: { turnText: string; pageSlug?: string }): Promise<ManagedFactsSession | null> {+ input: { turnText: string; pageSlug?: string }, derivation?: { trust: WriteTrust; inputs: readonly TaintInput[] }): Promise<ManagedFactsSession | null> {const engine = ctx.engine;if (!(await managedPersistenceEnabled(engine))) return null;assertPersistenceAccepting(engine);@@ -254,7 +259,8 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,batchKey, inputDigest, origin, originalRequestId: ctx.persistenceRequestId ?? null,completionRequestId: ctx.requestId ? requireUuid(ctx.requestId) : managedFactRequestId(batchKey, '__managed_facts_complete__'),fileRefusalRetry: ctx.reAdmitFileRefusals === true && seed === inputDigest,- ...(captureGateLaneForSource(ctx.source) ? { captureSource: ctx.source } : {}) };+ ...(captureGateLaneForSource(ctx.source) ? { captureSource: ctx.source } : {}),+ ...(derivation ? { derivation: declareDerivation(derivation.trust, derivation.inputs) } : {}) };const prior = await getWriteRequest(engine, authority.principal, session.completionRequestId);if (prior) await validateManagedFactsCompletion(engine, session, prior);return session;@@ -403,6 +409,7 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFembedding: session.embedding ?? null, ...(options.supersede ? { supersede: true as const } : {}),...(options.attributeFallback ? { attribute_fallback: true as const } : {}),...(session.captureSource ? { capture_source: session.captureSource } : {}),+ ...(session.derivation ? { derivation: session.derivation } : {}),...(snapshot ? { expected_revision: snapshot.revision } : {}), facts: group } });}return collectManagedFacts(engine, session, await admitManagedFactsBatch(engine, session, inputs, embedded, ctx.abortSignal));diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex d1e63ee7cb..3320a820b8 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -20,6 +20,8 @@ import type { ManagedFactIntent, FrozenExtractedFact } from './facts-maintenanceimport { assertManagedFactsEmbedding } from './facts-maintenance.ts';import { normalizeTargetFences } from '../fence-repair/import-step.ts';import { pageFencesNormalized } from '../fence-repair/report.ts';+import { declaredWriteTrust, derivedWriteTrust, readDerivationDeclaration, readTaintInputs, recordTaintEdges } from '../trust/taint.ts';+import { minTrust, type TaintInput, type WriteTrust } from '../trust/tier.ts';const requestFix = (row: WriteRequest): Action => row.principal_kind === 'local_cli'? readFix(`Reads fact request ${row.request_id}'s durable receipt: its state and recorded error, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] })@@ -46,6 +48,22 @@ function thawFact(fact: FrozenExtractedFact): NewFact & { entity_slug: string |embedding: fact.embedding ? new Float32Array(fact.embedding) : null };}+/**+ * #5575 I2: extracted facts publish at the extraction's declared taint, never+ * above the source page's current tier (an intent queued before tiers derives+ * from its origin page alone). Undefined when neither exists: the request's+ * channel tier applies.+ */+async function managedFactsTrust(engine: BrainEngine, p: ManagedFactIntent): Promise<{ trust: WriteTrust; inputs: Array<Pick<TaintInput, 'table' | 'id'>> } | undefined> {+ const declaration = readDerivationDeclaration(p.derivation);+ if (!declaration && !p.origin) return undefined;+ const page = p.origin ? await readTaintInputs(engine, [{ table: 'pages', id: p.origin.pageId }]) : [];+ const live = derivedWriteTrust({ channel: declaration?.origin.channel ?? 'derive:facts_backstop', inputs: page, requestId: p.originalRequestId });+ if (!declaration) return { trust: live, inputs: page };+ const declared = declaredWriteTrust(declaration);+ return { trust: { tier: minTrust(declared.tier, live.tier), origin: declared.origin }, inputs: declaration.inputs };+}+export async function prepareManagedFactsMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {const p = row.intent as ManagedFactIntent | null;if (!p || !['managed_facts_entity', 'managed_facts_complete'].includes(p.kind) || row.operation !== 'extract_facts'@@ -157,6 +175,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writvisibility: canonical.visibility ?? entry.fact.visibility, entity_slug: row.slug,embedding: entry.fact.embedding, source_session: entry.fact.source_session };}+ const taint = await managedFactsTrust(engine, p);let page: PreparedMutation | undefined;if (snapshot && entries.some(entry => entry.rowNum !== undefined)) {page = await preparePageMutation(engine, { ...row, intent: { ...p,@@ -165,6 +184,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ`Entity page ${row.slug} changed while its ## Facts table was being prepared, so none of these facts were published.`);}return { observedRevision: snapshot?.revision ?? null, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), noop: entries.every(entry => entry.duplicateId !== null || entry.duplicateOf !== undefined),+ ...(taint ? { trust: taint.trust } : {}),additionalPageKeys, validate: async tx => {await validate(tx, true);await page?.validate?.(tx);@@ -190,6 +210,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writids.push(result.ids[0]);} else ids.push((await tx.insertFact(entry.fact, { source_id: row.source_id })).id);inserted++;+ if (taint) await recordTaintEdges(tx, { table: 'facts', id: ids[ids.length - 1], sourceId: row.source_id }, taint.inputs);if (entry.supersedes) {await tx.executeRaw('UPDATE facts SET expired_at=COALESCE(expired_at,now()),superseded_by=$3 WHERE id=$1 AND source_id=$2',[entry.supersedes.id, row.source_id, ids[ids.length - 1]]);diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 8ec1a251f1..b9e080cb88 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -23,7 +23,6 @@ import { nativeLockCapability } from './native-lock.ts';import { assertPhysicalRoot } from './physical-root.ts';import { isConnectorSourceKind } from './connector-identity.ts';import { MaintenanceWriteWait } from './maintenance-wait.ts';-import { withTrustKeep } from './context.ts';import { declaredWriteTrust, lowerToDerivedTier, readDerivationDeclaration, recordTaintEdges, type DerivationDeclaration } from '../trust/taint.ts';export interface MaintenanceAuthority {@@ -344,8 +343,8 @@ export async function applyPreservingTakeResolutions(tx: BrainEngine, pageId: nu* #5575 I2: a maintenance intent that carries a derivation declaration* publishes at the declared tier (never above agent_written), lowers its* derived row when the publication changed no content column, and records- * the complete input edges (ENG-7). A consolidation rewrites the entity- * page's takes fence without authoring the page, so the page keeps its tier.+ * the complete input edges (ENG-7). A consolidation's takes fence edit+ * keeps the entity page's tier (page-prepare's fence-edit rule).*/export async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {const prepared = await prepareMaintenanceKind(engine, row, config);@@ -354,7 +353,7 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Writeconst trust = declaredWriteTrust(declaration);const consolidation = row.intent?.kind === 'managed_maintenance_consolidate';return { ...prepared, trust, apply: async (tx, preimage) => {- const outcome = consolidation ? await withTrustKeep(tx, ['pages'], () => prepared.apply(tx, preimage)) : await prepared.apply(tx, preimage);+ const outcome = await prepared.apply(tx, preimage);const [derived] = consolidation ? (outcome.take_id ? [{ table: 'takes' as const, id: Number(outcome.take_id) }] : []): (await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [row.source_id, row.slug])).map(page => ({ table: 'pages' as const, id: Number(page.id) }));