Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(trust): facts derivers pass the row-level write gate at their declared tier (#5575 L1a-taint, B3, ENG-18)

garrytan4bdec2067257
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 45dd2001a1..56c11b1a23 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -75,7 +75,7 @@ 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 { insertDerivedFacts, managedDerivedFactsPreflight, replaceDerivedFactsForPage, writeDerivedFacts } from '../core/persistence/derived-facts.ts';
import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason, type NoPricingGuidance } from '../core/budget/budget-tracker.ts';
import { noPricingMessage } from '../core/budget/no-pricing.ts';
@@ -1222,7 +1222,7 @@ async function processPage(
if (state.managed) {
managedRows.push(...rows);
} else {
- const ins = await writeDerivedFacts(state.engine, state.sourceId, page.slug, db => db.insertFacts(rows, { source_id: state.sourceId })); // gbrain-allow-direct-insert: canonical bulk extraction path for conversation pages — fences-as-system-of-record doesn't apply because conversations don't carry `## Facts` fences (the chat-log shape is the source-of-truth)
+ const ins = await insertDerivedFacts(state.engine, state.sourceId, page.slug, rows); // canonical bulk extraction path for conversation pages (no `## Facts` fence: the chat log is the source of truth), through the write gate
pageInsertedTotal += ins.inserted;
state.result.facts_inserted += ins.inserted;
}
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index a7ad0e3e55..5e39ac06b8 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -57,6 +57,8 @@ 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';
+import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';
+import { decideFactWrite } from '../write-gate-store.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';
@@ -523,6 +525,8 @@ export async function runFactsPipeline(
/** Set when the LLM extraction step failed non-transport-fatally (see runPipelineWithBody). */
skipped_reason?: import('./extract.ts').ExtractFailureReason;
write_requests?: WriteReceipt[];
+ /** #5575 B3: rows the write gate flagged, held or rejected (unmanaged path). */
+ write_gate?: GateTally;
}> {
return runPipelineWithBody({
turnText,
@@ -544,7 +548,7 @@ async function runPipeline(
parsedPage: ParsedPageInput,
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {
+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally }> {
return runPipelineWithBody(
{
turnText: parsedPage.compiled_truth,
@@ -591,7 +595,7 @@ async function runPipelineWithBody(
input: PipelineInput,
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {
+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally }> {
// #4210: outside a withBudgetTracker scope (extract_facts op, sweep,
// put_page backstop, checkpoint harvest, file/code import) the gateway's
// chat/embed calls were budget no-ops — real spend, zero audit rows.
@@ -618,7 +622,7 @@ async function runPipelineBodyInner(
input: PipelineInput,
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {
+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally }> {
const { extractFactsFromTurnWithOutcome, FactsExtractionError } = await import('./extract.ts');
const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');
const { cosineSimilarity } = await import('./classify.ts');
@@ -702,16 +706,29 @@ 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;
const fact_ids: number[] = [...dropped];
+ // #5575 B3: every row passes the write gate at the extraction's declared tier (ENG-18). The extractor
+ // rewrites strict injection hits to [redacted], so such a row is also gated on the source text.
+ const gateCfg = await derivedGateConfig(ctx.engine);
+ const gateInput = derivedGateInput(derivation.trust, ctx.persistenceRequestId);
+ const write_gate = emptyGateTally();
+ const decideFact = (row: { fact: string; context?: string | null; source?: string | null }, slug: string | null, payload: Record<string, unknown>) =>
+ decideFactWrite({ ...row, source_text: row.fact.includes('[redacted]') ? input.turnText : null },
+ { sourceId: ctx.sourceId, slug, payload: { ...payload, embedding: null }, input: gateInput, cfg: gateCfg });
+ // Every DB-only insert: one attributed transaction at the derived tier, gated, with input edges for a new row.
+ const insertDerivedFact = (newFact: NewFact) => maintenanceTransaction(ctx.engine, tx =>
+ applyGateDecision(tx, decideFact(newFact, newFact.entity_slug ?? null, { ...newFact }), { table: 'facts', sourceId: ctx.sourceId }, async () => {
+ 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)
+ fact_ids.push(result.id);
+ if (result.status === 'inserted') inserted += 1;
+ else if ((result.status as FactInsertStatus) === 'duplicate') { duplicate += 1; return null; }
+ else superseded += 1;
+ await recordTaintEdges(tx, { table: 'facts', id: result.id, sourceId: ctx.sourceId }, derivation.inputs);
+ return result.id;
+ }, write_gate), derivation.trust);
// Cathedral 5: slugs whose fence-write actually inserted a fact this run.
const fencedSlugs = new Set<string>();
@@ -774,7 +791,7 @@ async function runPipelineBodyInner(
}
if (survived.length === 0) {
- return { inserted, duplicate, superseded, fact_ids, entity_slugs: [] };
+ return { inserted, duplicate, superseded, fact_ids, entity_slugs: [], write_gate };
}
// Phase 2: group survived facts by resolved entity_slug. Facts with
@@ -843,11 +860,7 @@ async function runPipelineBodyInner(
valid_from: factEventTime(f, ctx),
context: annotateUnverifiedResolution(ctx.sourceSlug ?? input.pageSlug ?? null, resolutionSource, f.entity_inferred),
};
- 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;
- else superseded += 1;
+ await insertDerivedFact(newFact); // legacy DB-only fallback for unparented / thin-client facts (no entity page to fence onto)
}
if (localPath === null) {
@@ -879,6 +892,14 @@ async function runPipelineBodyInner(
embedding_model: f.embedding_model ?? null, attributedTo: f.attributed_to ?? undefined,
sessionId: f.source_session ?? null,
}));
+ // #5575 B3: gate before the fence write; a held or rejected row reaches neither the fence nor a fallback below.
+ const decisions = inputFacts.map(fact => decideFact(fact, slug, { ...fact }));
+ if (decisions.some(d => d.action !== 'insert')) await maintenanceTransaction(ctx.engine, async tx => {
+ for (const d of decisions) if (d.action !== 'insert') await applyGateDecision(tx, d, { table: 'facts', sourceId: ctx.sourceId }, async () => null, write_gate);
+ });
+ const kept = group.filter((_, i) => decisions[i].action === 'insert');
+ const keptFacts = inputFacts.flatMap((fact, i) => decisions[i].action === 'insert' ? [{ ...fact, gate: decisions[i] }] : []);
+ if (!keptFacts.length) continue;
// #4108 fail-closed on mixed provenance: one fallback-minted ref in the
// group means the slug's existence is unproven — block the whole group.
@@ -892,7 +913,7 @@ async function runPipelineBodyInner(
const result = await writeFactsToFence(
ctx.engine,
{ sourceId: ctx.sourceId, localPath, slug, resolutionSource: groupResolutionSource },
- inputFacts,
+ keptFacts,
derivation,
);
@@ -915,7 +936,7 @@ async function runPipelineBodyInner(
// file is created. This also keeps blocked slugs out of
// fencedSlugs, so fallback-minted slugs never reach the
// entity_slugs checkpoint/link manifests downstream.
- for (const { f } of group) {
+ for (const { f } of kept) {
const newFact: NewFact = {
fact: f.fact,
kind: f.kind,
@@ -931,11 +952,7 @@ async function runPipelineBodyInner(
valid_from: factEventTime(f, ctx),
context: ctx.sourceSlug ?? input.pageSlug ?? null,
};
- 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;
- else superseded += 1;
+ await insertDerivedFact(newFact); // stub-guard / unresolvable-target fallback for unprefixed or fallback-resolved entity slugs (no fenceable page or usable tree)
}
continue;
}
@@ -948,7 +965,7 @@ async function runPipelineBodyInner(
'facts:fence-write-unexpected-fallback',
`[facts] writeFactsToFence returned legacyFallback for slug=${slug} despite localPath being set — routing to DB-only inserts.`,
);
- for (const { f } of group) {
+ for (const { f } of kept) {
const newFact: NewFact = {
fact: f.fact,
kind: f.kind,
@@ -964,11 +981,7 @@ async function runPipelineBodyInner(
valid_from: factEventTime(f, ctx),
context: ctx.sourceSlug ?? input.pageSlug ?? null,
};
- 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;
- else superseded += 1;
+ await insertDerivedFact(newFact); // DB-only fallback when the fence lane declined the write (write_through opt-out race / localPath echo)
}
continue;
}
@@ -978,5 +991,5 @@ async function runPipelineBodyInner(
if (result.inserted > 0) fencedSlugs.add(slug);
}
- return { inserted, duplicate, superseded, fact_ids, entity_slugs: [...fencedSlugs] };
+ return { inserted, duplicate, superseded, fact_ids, entity_slugs: [...fencedSlugs], write_gate };
}
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index 15562a804c..409bf07ebf 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -58,6 +58,7 @@ 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 { recordFlaggedRow, type GatedRowDecision } from '../write-gate-store.ts';
import type { TaintInput, WriteTrust } from '../trust/tier.ts';
/** Resolved source binding for the entity page. */
@@ -102,6 +103,8 @@ export interface FenceInputFact {
sessionId: string | null;
/** Speaker attribution; written to the fence's attributed_to cell. */
attributedTo?: FactAttribution;
+ /** #5575 B3: the deriver's write-gate decision (an `insert`); a flag records its receipt on the new row. */
+ gate?: GatedRowDecision;
}
export interface FenceWriteResult {
@@ -342,7 +345,7 @@ export async function writeFactsToFence(
}
const { filePath, writeRoot } = resolved;
if (!hasSourceFilesystemLock(writeRoot)) {
- return withSourceFilesystemLock(engine, writeRoot, () => writeFactsToFence(engine, target, facts));
+ return withSourceFilesystemLock(engine, writeRoot, () => writeFactsToFence(engine, target, facts, derivation));
}
const tmpPath = `${filePath}.tmp`;
const durabilityEnabled = isDurabilityHardened(writeRoot);
@@ -561,7 +564,10 @@ export async function writeFactsToFence(
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);
+ for (const [i, id] of (derivation ? inserted.ids : []).entries()) {
+ await recordTaintEdges(tx, { table: 'facts', id, sourceId: target.sourceId }, derivation!.inputs);
+ if (facts[i]?.gate && inserted.ids.length === facts.length) await recordFlaggedRow(tx, facts[i].gate!, { table: 'facts', id, sourceId: target.sourceId });
+ }
return inserted;
}, derivation?.trust);
// v0.46 (#3014) — an unresolvable `superseded by #N` reference (self
diff --git a/src/core/persistence/derived-facts.ts b/src/core/persistence/derived-facts.ts
index 9117ab1611..6fd7b6e5b4 100644
--- a/src/core/persistence/derived-facts.ts
+++ b/src/core/persistence/derived-facts.ts
@@ -5,6 +5,8 @@ import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { withCoordinatedWrite, withWriteTrust } from './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 { maintenanceAttribution, maintenanceTransaction } from './attribution.ts';
import { currentVerifiedLocalWriter } from './identity.ts';
import { managedPersistenceEnabled } from './ownership.ts';
@@ -70,6 +72,37 @@ async function recordInsertedEdges(tx: BrainEngine, sourceId: string, result: un
for (const id of Array.isArray(ids) ? ids : []) await recordTaintEdges(tx, { table: 'facts', id: Number(id), sourceId }, inputs);
}
+/**
+ * #5575 B3: one batch of extracted rows through the write gate at the page's
+ * declared tier (ENG-18): allowed rows are inserted with their input edges
+ * and flag receipts, held rows go to write_gate_holds, rejected rows are
+ * counted and skipped.
+ */
+type FenceRow = NewFact & { row_num: number; source_markdown_slug: string };
+async function insertGatedFacts(tx: BrainEngine, sourceId: string, slug: string, rows: FenceRow[],
+ derivation: Awaited<ReturnType<typeof conversationDerivation>>): Promise<{ inserted: number; ids: number[]; write_gate: GateTally }> {
+ const cfg = await derivedGateConfig(tx);
+ const input = derivedGateInput(derivation.trust);
+ const write_gate = emptyGateTally();
+ const decisions = rows.map(row => decideFactWrite({ fact: row.fact, context: row.context, source: row.source },
+ { sourceId, slug, payload: { ...row, embedding: null }, input, cfg }));
+ for (const decision of decisions) if (decision.action !== 'insert') await applyGateDecision(tx, decision, { table: 'facts', sourceId }, async () => null, write_gate);
+ const allowed = rows.filter((_, i) => decisions[i].action === 'insert');
+ const flags = decisions.filter(decision => decision.action === 'insert');
+ const result = allowed.length ? await tx.insertFacts(allowed, { source_id: sourceId }) : { inserted: 0, ids: [] }; // gbrain-allow-direct-insert: conversation fact rows that passed the write gate
+ for (const [i, id] of result.ids.entries()) {
+ await recordTaintEdges(tx, { table: 'facts', id, sourceId }, derivation.inputs);
+ if (result.ids.length === allowed.length && await recordFlaggedRow(tx, flags[i], { table: 'facts', id, sourceId }) !== null) write_gate.flagged++;
+ }
+ return { inserted: result.inserted, ids: result.ids, write_gate };
+}
+
+/** The conversation fact index's gated batch insert, in writeDerivedFacts' transaction shape. */
+export async function insertDerivedFacts(engine: BrainEngine, sourceId: string, slug: string, rows: FenceRow[]) {
+ const derivation = await conversationDerivation(engine, sourceId, slug);
+ return writeDerivedFacts(engine, sourceId, slug, db => insertGatedFacts(db, sourceId, slug, rows, derivation));
+}
+
/**
* 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
@@ -112,12 +145,8 @@ 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 { 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 };
+ const derivation = await conversationDerivation(tx, sourceId, slug);
+ const { inserted } = rows.length ? await withWriteTrust(tx, derivation.trust, () => insertGatedFacts(tx, sourceId, slug, rows, derivation)) : { inserted: 0 };
return { deleted: Number(deleted?.count ?? 0), inserted };
});
}
diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.ts
index 3320a820b8..a4c934c149 100644
--- a/src/core/persistence/facts-prepare.ts
+++ b/src/core/persistence/facts-prepare.ts
@@ -22,6 +22,8 @@ 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';
+import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally } from '../trust/derived-gate.ts';
+import { decideFactWrite, recordFlaggedRow, type GatedRowDecision } from '../write-gate-store.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] })
@@ -140,8 +142,13 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
const parsed = parseFactsFence(body);
const [maximum] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);
let nextRow = Math.max(maximum?.n ?? 0, ...parsed.facts.map(fact => fact.rowNum)) + 1;
- const entries: Array<{ fact: typeof facts[number]; duplicateId: number | null; rowNum?: number; duplicateOf?: number; supersedes?: FactCandidate }> = [];
+ const entries: Array<{ fact: typeof facts[number]; duplicateId: number | null; rowNum?: number; duplicateOf?: number; supersedes?: FactCandidate; gate?: GatedRowDecision }> = [];
const seen = new Map<string, number[]>();
+ // #5575 B3: a new row passes the write gate at the extraction's declared tier (ENG-18) before it reaches the fence;
+ // held rows are recorded at publication, rejected rows are counted and skipped.
+ const taint = await managedFactsTrust(engine, p);
+ const gateCfg = taint ? await derivedGateConfig(engine) : null;
+ const blocked: GatedRowDecision[] = [];
for (const fact of facts) {
await assertFactNotWithdrawn(engine, row.source_id, fact);
const key = JSON.stringify([fact.fact, fact.visibility, fact.entity_slug]);
@@ -151,6 +158,9 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
const decision = await decideSingleFact(engine, row.source_id, fact, dedupEmbedding(fact), fact.embedding_model, fact.source);
const supersedes = p.supersede === true && decision.status === 'superseded' ? decision.candidate! : undefined;
if (decision.candidate && !supersedes) { entries.push({ fact, duplicateId: decision.candidate.id }); continue; }
+ const gate = taint ? decideFactWrite(fact, { sourceId: row.source_id, slug: row.slug, payload: { ...fact, embedding: null },
+ input: derivedGateInput(taint.trust, row.id), cfg: gateCfg! }) : undefined;
+ if (gate && gate.action !== 'insert') { blocked.push(gate); continue; }
const rowNum = fact.entity_slug !== null && !fallback(fact) ? nextRow++ : undefined;
if (rowNum !== undefined) body = upsertFactRow(body, { rowNum, claim: fact.fact, kind: fact.kind, visibility: fact.visibility,
confidence: fact.confidence ?? 1, notability: fact.notability ?? 'medium', source: fact.source, context: fact.context ?? undefined,
@@ -163,7 +173,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
body = replaceOrInsertFactsFence(body, renderFactsTable(parseFactsFence(body).facts.map(f => f.rowNum === Number(supersedes.row_num)
? { ...f, active: false, supersededBy: rowNum, context: `superseded by #${rowNum}` } : f)));
}
- entries.push({ fact, duplicateId: null, rowNum, supersedes });
+ entries.push({ fact, duplicateId: null, rowNum, supersedes, gate });
}
const canonicalFacts = extractFactsFromFenceText(parseFactsFence(body).facts, row.slug, row.source_id);
for (const entry of entries) {
@@ -175,7 +185,6 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
visibility: 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,
@@ -211,13 +220,16 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
} 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.gate) await recordFlaggedRow(tx, entry.gate, { table: 'facts', id: ids[ids.length - 1], sourceId: row.source_id });
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]]);
superseded++;
}
}
- return { status: 'completed', inserted, duplicate: entries.length - inserted, superseded, fact_ids: ids,
+ const write_gate = emptyGateTally();
+ for (const gate of blocked) await applyGateDecision(tx, gate, { table: 'facts', sourceId: row.source_id }, async () => null, write_gate);
+ return { status: 'completed', inserted, duplicate: entries.length - inserted, superseded, fact_ids: ids, ...(blocked.length ? { write_gate } : {}),
fenced: page !== undefined, kind: p.kind, batch_key: p.batchKey, input_digest: p.inputDigest,
...(page && target?.fixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,
writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {}) };
diff --git a/src/core/trust/derived-gate.ts b/src/core/trust/derived-gate.ts
new file mode 100644
index 0000000000..aaa977c60d
--- /dev/null
+++ b/src/core/trust/derived-gate.ts
@@ -0,0 +1,42 @@
+/**
+ * The row-level write gate for derivers (#5575 B3, ENG-18): the gate input
+ * is exactly the tier the deriver declared (trust/taint.ts). Each writer
+ * calls decideFactWrite / decideTakeWrite / assessTimelineForGate itself
+ * (write-gate-store.ts, write-gate.ts); these helpers read the gate config
+ * once per run and apply one decision inside the writer's transaction.
+ * A deriver never throws for one row: a held row goes to write_gate_holds, a
+ * rejected row is skipped and counted.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { loadImportSanityConfig } from '../import-screen.ts';
+import { DEFAULT_WRITE_GATE_CONFIG, type WriteGateConfig, type WriteGateInput } from '../write-gate.ts';
+import { recordFlaggedRow, recordWriteGateHold, type GatedRowDecision } from '../write-gate-store.ts';
+import type { WriteTrust } from './tier.ts';
+
+/** `write_gate.*` as the import path reads it; unreadable values fall back to the defaults, never `off`. */
+export async function derivedGateConfig(engine: BrainEngine): Promise<WriteGateConfig> {
+ return (await loadImportSanityConfig(engine)).writeGate ?? DEFAULT_WRITE_GATE_CONFIG;
+}
+
+/** The gate input for a declared derivation. */
+export function derivedGateInput(trust: WriteTrust, requestId?: string | null): WriteGateInput {
+ return { tier: trust.tier, origin: trust.origin, requestId: requestId ?? trust.origin?.request_id ?? 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 });
+
+/**
+ * Applies one decision inside the writer's transaction: `insert` runs the
+ * insert and records the flag receipt on the new row; `hold` records the hold
+ * instead of inserting; `reject` writes nothing. Returns the inserted id.
+ */
+export async function applyGateDecision(tx: BrainEngine, decision: GatedRowDecision, target: { table: 'facts' | 'takes'; sourceId: string },
+ insert: () => Promise<number | null>, tally?: GateTally): Promise<number | null> {
+ if (decision.action === 'reject') { if (tally) tally.rejected++; return null; }
+ if (decision.action === 'hold') { await recordWriteGateHold(tx, decision.hold!); if (tally) tally.held++; return null; }
+ const id = await insert();
+ if (id !== null && await recordFlaggedRow(tx, decision, { table: target.table, id, sourceId: target.sourceId }) !== null && tally) tally.flagged++;
+ return id;
+}