Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(trust): extract-takes, loops extraction and the fence reconcile stamp page taint and pass the write gate (#5575 L1a-taint, ENG-3, B3)

garrytan17768e7a9878
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 872936e90f..42bd290f75 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -49,6 +49,8 @@ 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 { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';
+import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';
import type { WriteTrust } from '../trust/tier.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import {
@@ -365,6 +367,8 @@ export interface ExtractFactsResult {
/** Pages whose reconcile threw and rolled back; later pages still ran. */
pagesFailed: number;
warnings: string[];
+ /** #5575 B3: new fence rows the write gate flagged, held or rejected; present only when it did any. */
+ writeGate?: GateTally;
/** v0.35.5: phantom-redirect pre-pass counts. */
phantomsScanned: number;
phantomsRedirected: number;
@@ -456,6 +460,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 gateCfg = await derivedGateConfig(engine);
+ const gateTally = emptyGateTally();
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 = {
@@ -850,14 +856,22 @@ export async function runExtractFacts(
f.claim_metric ?? null, f.claim_value ?? null, f.claim_unit ?? null, f.claim_period ?? null],
);
}
- const inserted = inserts.length === 0
- ? { inserted: 0 }
+ // #5575 B3: each new fence row passes the write gate at the page's tier (an owner page never runs it).
+ const decisions = inserts.map(f => decideFactWrite(f, { sourceId, slug, payload: { ...f, embedding: null }, input: derivedGateInput(derivation.trust), cfg: gateCfg }));
+ for (const d of decisions) if (d.action !== 'insert') await applyGateDecision(tx, d, { table: 'facts', sourceId }, async () => null, gateTally);
+ const allowed = inserts.filter((_, i) => decisions[i].action === 'insert');
+ const flags = decisions.filter(d => d.action === 'insert');
+ const inserted = allowed.length === 0
+ ? { inserted: 0, ids: [] as number[] }
: await tx.insertFacts( // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB
- inserts.map(f => ({ ...f, superseded_by_row: undefined })),
+ allowed.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));
+ for (const [i, id] of inserted.ids.entries()) {
+ await recordTaintEdges(tx, { table: 'facts', id, sourceId }, derivation.inputs);
+ if (inserted.ids.length === allowed.length && await recordFlaggedRow(tx, flags[i], { table: 'facts', id, sourceId }) !== null) gateTally.flagged++;
+ }
+ const insertedRows = new Set(allowed.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))]);
@@ -953,6 +967,7 @@ export async function runExtractFacts(
});
}
+ if (gateTally.flagged || gateTally.held || gateTally.rejected) result.writeGate = gateTally;
return result;
}
diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.ts
index 04726712f4..30dc37066f 100644
--- a/src/core/cycle/extract-takes.ts
+++ b/src/core/cycle/extract-takes.ts
@@ -31,7 +31,11 @@ import type { BrainEngine, TakeBatchInput } from '../engine.ts';
import { parseTakesFence, TAKES_FENCE_BEGIN, type ParsedTake } from '../takes-fence.ts';
import { walkMarkdownFiles } from '../../commands/extract.ts';
import { takesPreparation } from '../takes-write.ts';
-import { withCoordinatedWrite } from '../persistence/context.ts';
+import { withCoordinatedWrite, withWriteTrust } from '../persistence/context.ts';
+import { derivedWriteTrust, recordTaintEdges } from '../trust/taint.ts';
+import { storedTrustTier } from '../trust/tier.ts';
+import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';
+import { decideTakeWrite, recordFlaggedRow } from '../write-gate-store.ts';
import { maintenanceAttribution, maintenanceTransaction } from '../persistence/attribution.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
@@ -75,6 +79,8 @@ export interface ExtractTakesResult {
* there's no on-disk file to point at).
*/
failedFiles: Array<{ path: string; error: string }>;
+ /** #5575 B3: new rows the write gate flagged, held or rejected; present only when it did any. */
+ writeGate?: GateTally;
}
/**
@@ -134,6 +140,48 @@ function parsedTakeToBatchInput(pageId: number, t: ParsedTake): TakeBatchInput {
const BATCH_SIZE = 100;
+/**
+ * #5575 I2/B3: takes rows restate their page's fence (no model), so each row
+ * takes its page's tier capped at operator_curated (a projection) and passes
+ * the write gate at that tier (an owner page never runs it). Rows of pages
+ * with different tiers commit in separate transactions; `inTx` writes one
+ * page's rows inside the caller's coordinated transaction instead.
+ */
+async function upsertProjectedTakes(engine: BrainEngine, rows: TakeBatchInput[], result: ExtractTakesResult, inTx?: BrainEngine): Promise<number> {
+ if (!rows.length) return 0;
+ const db = inTx ?? engine;
+ const pages = new Map((await db.executeRaw<{ id: number; source_id: string; slug: string; trust_tier: string | null }>(
+ 'SELECT id,source_id,slug,trust_tier FROM pages WHERE id=ANY($1::int[])', [[...new Set(rows.map(r => r.page_id))]]))
+ .map(page => [Number(page.id), { ...page, input: { table: 'pages' as const, id: Number(page.id), tier: storedTrustTier(page.trust_tier) } }]));
+ const cfg = await derivedGateConfig(db);
+ const tally = result.writeGate ?? emptyGateTally();
+ let upserted = 0;
+ for (const tier of new Set(rows.map(r => pages.get(r.page_id)?.input.tier ?? 'unknown'))) {
+ const group = rows.filter(r => (pages.get(r.page_id)?.input.tier ?? 'unknown') === tier);
+ const inputs = [...new Set(group.map(r => pages.get(r.page_id)).filter(p => !!p))].map(p => p!.input);
+ const trust = derivedWriteTrust({ channel: 'derive:takes_fence', inputs, projection: true });
+ const write = async (tx: BrainEngine) => {
+ const decisions = group.map(r => decideTakeWrite({ claim: r.claim, source: r.source }, { sourceId: pages.get(r.page_id)?.source_id ?? 'default',
+ slug: pages.get(r.page_id)?.slug ?? null, payload: { ...r }, input: derivedGateInput(trust), cfg }));
+ for (const [i, d] of decisions.entries()) if (d.action !== 'insert') await applyGateDecision(tx, d, { table: 'takes', sourceId: pages.get(group[i].page_id)?.source_id ?? 'default' }, async () => null, tally);
+ const allowed = group.filter((_, i) => decisions[i].action === 'insert');
+ const flags = decisions.filter(d => d.action === 'insert');
+ const count = allowed.length ? await tx.addTakesBatch(allowed) : 0;
+ for (const [i, r] of allowed.entries()) {
+ const page = pages.get(r.page_id);
+ const [take] = await tx.executeRaw<{ id: number }>('SELECT id FROM takes WHERE page_id=$1 AND row_num=$2', [r.page_id, r.row_num]);
+ if (!take || !page) continue;
+ await recordTaintEdges(tx, { table: 'takes', id: Number(take.id), sourceId: page.source_id }, [page.input]);
+ if (await recordFlaggedRow(tx, flags[i], { table: 'takes', id: Number(take.id), sourceId: page.source_id }) !== null) tally.flagged++;
+ }
+ return count;
+ };
+ upserted += inTx ? await withWriteTrust(inTx, trust, () => write(inTx)) : await maintenanceTransaction(engine, write, trust);
+ }
+ if (tally.flagged || tally.held || tally.rejected) result.writeGate = tally;
+ return upserted;
+}
+
async function flushBatch(
engine: BrainEngine,
buffer: TakeBatchInput[],
@@ -144,8 +192,7 @@ async function flushBatch(
if (dryRun) {
result.takesUpserted += buffer.length;
} else {
- const inserted = await maintenanceTransaction(engine, tx => tx.addTakesBatch(buffer));
- result.takesUpserted += inserted;
+ result.takesUpserted += await upsertProjectedTakes(engine, buffer, result);
}
buffer.length = 0;
}
@@ -320,7 +367,7 @@ async function reextractCoordinated(
if (!page) return;
const takes = await reconcilePageTakes(tx, page, slug, rebuild, false, result);
if (takes.length === 0) return;
- result.takesUpserted += await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(page.id, t)));
+ result.takesUpserted += await upsertProjectedTakes(tx, takes.map(t => takesPreparation.toCanonicalBatchInput(page.id, t)), result, tx);
}, attribution));
}
diff --git a/src/core/facts/managed-fact-write.ts b/src/core/facts/managed-fact-write.ts
index 8f827aeae4..f5dd9c8af2 100644
--- a/src/core/facts/managed-fact-write.ts
+++ b/src/core/facts/managed-fact-write.ts
@@ -3,6 +3,7 @@ import type { FactsBackstopCtx } from './backstop.ts';
import type { FenceInputFact } from './fence-write.ts';
import type { ExtractedFact } from './extract.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import type { TaintInput, WriteTrust } from '../trust/tier.ts';
import { prepareManagedFactsSession, publishManagedFacts, resolveManagedFactsEmbedding, resumeManagedFacts } from '../persistence/facts-maintenance.ts';
function factsContext(engine: BrainEngine, sourceId: string, requestIntent: Record<string, unknown>, sessionId: string | null = null): FactsBackstopCtx {
@@ -24,7 +25,7 @@ export async function managedFactWritePreflight(engine: BrainEngine, sourceId: s
* replays its receipt. Returned ids follow input order.
*/
export async function publishManagedEntityFacts(engine: BrainEngine, sourceId: string, entity: string | null,
- facts: FenceInputFact[], options: { supersede?: boolean; attributeFallback?: boolean } = {}): Promise<{ inserted: number; duplicate: number; superseded: number; ids: number[] }> {
+ facts: FenceInputFact[], options: { supersede?: boolean; attributeFallback?: boolean; derivation?: { trust: WriteTrust; inputs: readonly TaintInput[] } } = {}): Promise<{ inserted: number; duplicate: number; superseded: number; ids: number[] }> {
const out = { inserted: 0, duplicate: 0, superseded: 0, ids: new Array<number>(facts.length) };
for (const visibility of ['private', 'world'] as const) {
const positions = facts.flatMap((fact, i) => fact.visibility === visibility ? [i] : []);
@@ -34,7 +35,7 @@ export async function publishManagedEntityFacts(engine: BrainEngine, sourceId: s
...(options.attributeFallback ? { attribute_fallback: true } : {}),
facts: group.map(f => [f.fact, f.kind, f.source, f.notability, f.confidence ?? 1, f.validFrom?.toISOString() ?? null,
f.validUntil?.toISOString() ?? null, f.sessionId, f.context ?? null]) }, group[0].sessionId);
- const session = (await prepareManagedFactsSession(ctx, { turnText: '' }))!;
+ const session = (await prepareManagedFactsSession(ctx, { turnText: '' }, options.derivation))!;
let result = await resumeManagedFacts(engine, session);
if (!result) {
const signature = await resolveManagedFactsEmbedding(engine, session.config);
diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.ts
index 7cf54496d3..c7969b1279 100644
--- a/src/core/facts/write-single.ts
+++ b/src/core/facts/write-single.ts
@@ -25,6 +25,9 @@
import type { BrainEngine, FactInsertStatus, NewFact } from '../engine.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { recordTaintEdges } from '../trust/taint.ts';
+import type { TaintInput, WriteTrust } from '../trust/tier.ts';
+import { recordFlaggedRow, type GatedRowDecision } from '../write-gate-store.ts';
const DEDUP_THRESHOLD = 0.95;
const DEDUP_CANDIDATE_LIMIT = 5;
@@ -61,6 +64,10 @@ export interface SingleFactInput {
validUntil?: Date | null;
sessionId?: string | null;
confidence?: number;
+ /** #5575 I2: a deriver's taint (e.g. loops extraction from an email page); the new row gets its tier and input edges. */
+ derivation?: { trust: WriteTrust; inputs: readonly TaintInput[] };
+ /** #5575 B3: the caller's write-gate decision (an `insert`); a flag records its receipt on the new row. */
+ gate?: GatedRowDecision;
}
export interface SingleFactResult {
@@ -135,7 +142,7 @@ export async function writeSingleFact(
const { publishManagedEntityFacts } = await import('./managed-fact-write.ts');
const written = await publishManagedEntityFacts(engine, sourceId, resolvedSlug, [{ fact: factText, kind, notability: 'medium',
source: input.provenance, visibility, confidence: input.confidence ?? 1.0, validFrom: new Date(), validUntil,
- embedding, embedding_model: embeddingModel, sessionId: input.sessionId ?? null }], { supersede: true, attributeFallback: true });
+ embedding, embedding_model: embeddingModel, sessionId: input.sessionId ?? null }], { supersede: true, attributeFallback: true, derivation: input.derivation });
const [stored] = await engine.executeRaw<{ entity_slug: string | null }>('SELECT entity_slug FROM facts WHERE id=$1', [written.ids[0]]);
return { id: written.ids[0], status: written.superseded ? 'superseded' : written.inserted ? 'inserted' : 'duplicate', entity_slug: stored?.entity_slug ?? null,
valid_until: validUntil, degraded_dedup: degradedDedup };
@@ -213,8 +220,10 @@ export async function writeSingleFact(
embedding,
embedding_model: embedding ? embeddingModel : null,
sessionId: input.sessionId ?? null,
+ ...(input.gate ? { gate: input.gate } : {}),
},
],
+ input.derivation,
);
if (result.fenceWriteFailed) {
@@ -249,10 +258,15 @@ export async function writeSingleFact(
// tree unusable) → DB-only path below.
}
- const inserted = await maintenanceTransaction(engine, tx => tx.insertFact(newFact, { // gbrain-allow-direct-insert: writeSingleFact legacy path for unparented / thin-client / stub-guarded facts (mirrors the pipeline's fallback buckets)
- source_id: sourceId,
- ...(supersedeId !== null ? { supersedeId } : {}),
- }));
+ const inserted = await maintenanceTransaction(engine, async tx => {
+ const row = await tx.insertFact(newFact, { // gbrain-allow-direct-insert: writeSingleFact legacy path for unparented / thin-client / stub-guarded facts (mirrors the pipeline's fallback buckets)
+ source_id: sourceId,
+ ...(supersedeId !== null ? { supersedeId } : {}),
+ });
+ if (row.status !== 'duplicate' && input.derivation) await recordTaintEdges(tx, { table: 'facts', id: row.id, sourceId }, input.derivation.inputs);
+ if (row.status !== 'duplicate' && input.gate) await recordFlaggedRow(tx, input.gate, { table: 'facts', id: row.id, sourceId });
+ return row;
+ }, input.derivation?.trust);
return {
id: inserted.id,
diff --git a/src/core/google/loops-extract.ts b/src/core/google/loops-extract.ts
index af4e834d15..192edd4e41 100644
--- a/src/core/google/loops-extract.ts
+++ b/src/core/google/loops-extract.ts
@@ -29,6 +29,10 @@ import { managedFactWritePreflight } from '../facts/managed-fact-write.ts';
import { loadSuppressions, upsertOpenLoop, type LoopType } from '../loops/loops-store.ts';
import { isCalendarSystemMail, isNoiseSender, sha8 } from './google-render.ts';
import { bareAddress, type GmailMessageMeta, type GmailThreadData } from './types.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { deriveTrust } from '../trust/taint.ts';
+import { applyGateDecision, derivedGateConfig, derivedGateInput } from '../trust/derived-gate.ts';
+import { decideFactWrite } from '../write-gate-store.ts';
export const LOOPS_EXTRACT_JOB = 'loops_extract';
/**
@@ -414,6 +418,10 @@ export async function runLoopsExtract(
const loopIds: number[] = [];
const messageDate = typeof fm.date === 'string' ? fm.date : new Date().toISOString();
+ // #5575 I2/B3: the model read only this email page, so its commitment facts carry the page's tier
+ // (a connector page is external_untrusted) and pass the write gate at that tier.
+ const derivation = await deriveTrust(engine, [{ table: 'pages', id: page.id }], { channel: 'derive:loops' });
+ const gateCfg = await derivedGateConfig(engine);
for (const c of extraction.commitments) {
const loopType: LoopType =
@@ -423,17 +431,24 @@ export async function runLoopsExtract(
// Projection 1 — facts row (fence-first, deduped/superseding).
let factId: number | null = null;
try {
- const { writeSingleFact } = await import('../facts/write-single.ts');
- const result = await writeSingleFact(engine, payload.sourceId, {
+ const fact = {
fact: c.text,
provenance: `email thread "${(page.title ?? '').slice(0, 80)}" (${payload.slug})`,
- kind: 'commitment',
+ kind: 'commitment' as const,
entity: counterpartyRef,
- visibility: 'private',
+ visibility: 'private' as const,
validUntil: c.due_iso ? new Date(`${c.due_iso}T23:59:59Z`) : null,
confidence: 0.85,
- });
- factId = result.id;
+ };
+ const gate = decideFactWrite({ fact: fact.fact, source: fact.provenance },
+ { sourceId: payload.sourceId, slug: counterpartyRef, payload: fact, input: derivedGateInput(derivation.trust), cfg: gateCfg });
+ if (gate.action !== 'insert') {
+ // A held or rejected commitment writes no fact; the loop row below still records it for the owner.
+ await maintenanceTransaction(engine, tx => applyGateDecision(tx, gate, { table: 'facts', sourceId: payload.sourceId }, async () => null));
+ } else {
+ const { writeSingleFact } = await import('../facts/write-single.ts');
+ factId = (await writeSingleFact(engine, payload.sourceId, { ...fact, derivation, gate })).id;
+ }
} catch (err) {
// The loop row still lands; the facts projection is best-effort, but its
// failure is logged. Slug, source and a bounded error only: the