Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): derived timeline rows (gbrain extract, meetings, enrichment, chronicle projection) pass the write gate (#5575 L1a-taint, B3)
garrytand50c5eada1ce
diff --git a/src/core/chronicle/publish.ts b/src/core/chronicle/publish.tsindex 1e27b9fbe7..7976e6d25d 100644--- a/src/core/chronicle/publish.ts+++ b/src/core/chronicle/publish.ts@@ -41,7 +41,10 @@ import { preparePageMutation } from '../persistence/page-prepare.ts';import { effectiveVisibility, type Visibility } from '../search/private-visibility.ts';import type { ChronicleEventProposal } from './extract-events.ts';import { resolveChronicleEventSlugs } from './event-identity.ts';-import { declareDerivation, deriveTrust, derivedMaintenanceTransaction } from '../trust/taint.ts';+import { declareDerivation, declaredWriteTrust, deriveTrust, derivedMaintenanceTransaction, readDerivationDeclaration } from '../trust/taint.ts';+import { derivedGateConfig, derivedGateInput, timelineRowAllowed } from '../trust/derived-gate.ts';+import { assessTimelineForGate, type WriteGateAssessment } from '../write-gate.ts';+import { recordWriteGateReceipt } from '../write-gate-store.ts';export const CHRONICLE_RETIRED_BY = 'life-chronicle';export const CHRONICLE_EVENT_INTENT = 'managed_maintenance_chronicle_event';@@ -178,6 +181,7 @@ export async function publishChronicleGeneration(engine: BrainEngine, opts: {const events = await resolveChronicleEventSlugs(engine, sourceId, opts.events);// #5575 I2: the judge read only the depth page, so its events carry that page's tier (capped at agent_written).const derivation = await deriveTrust(engine, [{ table: 'pages', id: pin.pageId }], { channel: 'derive:chronicle' });+ const gateCfg = await derivedGateConfig(engine);for (const ev of events) {abort();@@ -185,12 +189,14 @@ export async function publishChronicleGeneration(engine: BrainEngine, opts: {const verdict = judgeTarget(existing, owned);if (!verdict.write) { result.protected.push({ slug: ev.slug, reason: verdict.reason }); continue; }const content = serializeMarkdown(ev.frontmatter, ev.compiledTruth, '', { type: 'event', title: ev.title, tags: [] });- const projection = { depth_slug: pin.slug, date: ev.day, summary: ev.summary };+ // #5575 B3: the event's summary lands on the depth page's timeline; a quarantined or rejected one projects nothing.+ const projectionGate = assessTimelineForGate({ summary: ev.summary, source: `life-chronicle:event:${ev.slug}` }, derivedGateInput(derivation.trust), gateCfg);+ const projection = timelineRowAllowed(projectionGate) ? { depth_slug: pin.slug, date: ev.day, summary: ev.summary } : undefined;try {if (maintenance) {const intent = { kind: CHRONICLE_EVENT_INTENT, content, expected_revision: verdict.expectedRevision,restore_retired: verdict.restore, depth: pin, decision_request_id: opts.decisionRequestId,- owned_hashes: [...owned], event_projection: projection, derivation: declareDerivation(derivation.trust, derivation.inputs) };+ owned_hashes: [...owned], ...(projection ? { event_projection: projection } : {}), derivation: declareDerivation(derivation.trust, derivation.inputs) };await submitDatabaseMaintenanceIntent(engine, maintenance, ev.slug, intent,requestIdFor({ writer: maintenance.writer.principal, slug: ev.slug, intent }));} else {@@ -201,7 +207,10 @@ export async function publishChronicleGeneration(engine: BrainEngine, opts: {if (!again.write) throw supersededError(again.reason);const page = await tx.putPage(ev.slug, { type: 'event', title: ev.title, compiled_truth: ev.compiledTruth,frontmatter: { type: 'event', ...ev.frontmatter }, effective_date: safeDate(ev.when) }, { sourceId });- await tx.upsertEventProjection({ depthSlug: pin.slug, eventSlug: ev.slug, date: ev.day, summary: ev.summary, sourceId });+ if (projection) {+ await tx.upsertEventProjection({ depthSlug: pin.slug, eventSlug: ev.slug, date: ev.day, summary: ev.summary, sourceId });+ await recordProjectionFlag(tx, projectionGate, page.id, ev.day, sourceId);+ }return { result: undefined, rows: [{ table: 'pages', id: page.id, sourceId }] };});}@@ -306,6 +315,20 @@ export async function prepareChronicleMutation(engine: BrainEngine, row: WriteReif (!projection) return outcome;const { projected } = await tx.upsertEventProjection({ depthSlug: projection.depth_slug, eventSlug: row.slug,date: projection.date, summary: projection.summary, sourceId: row.source_id });+ const declaration = readDerivationDeclaration(p.derivation);+ if (projected && declaration) {+ const assessment = assessTimelineForGate({ summary: projection.summary, source: `life-chronicle:event:${row.slug}` },+ derivedGateInput(declaredWriteTrust(declaration), row.id), await derivedGateConfig(tx));+ const [event] = 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]);+ if (event) await recordProjectionFlag(tx, assessment, Number(event.id), projection.date, row.source_id, row.id);+ }return { ...outcome, event_projected: projected };} };}++/** A flagged event projection's receipt on its timeline row (found by its event page and date). */+async function recordProjectionFlag(tx: BrainEngine, assessment: WriteGateAssessment, eventPageId: number, date: string, sourceId: string, requestId?: string): Promise<void> {+ if (assessment.verdict !== 'flag') return;+ const [entry] = await tx.executeRaw<{ id: number }>('SELECT id FROM timeline_entries WHERE event_page_id=$1 AND date=$2::date', [eventPageId, date]);+ if (entry) await recordWriteGateReceipt(tx, { targetTable: 'timeline_entries', targetId: Number(entry.id), sourceId, assessment, requestId });+}diff --git a/src/core/enrichment-service.ts b/src/core/enrichment-service.tsindex 4692fa7186..8467858489 100644--- a/src/core/enrichment-service.ts+++ b/src/core/enrichment-service.ts@@ -29,6 +29,8 @@ import { isAvailable } from './ai/gateway.ts';import { isJunkEntityName } from './entity-name-quality.ts';import { maintenanceTransaction } from './persistence/attribution.ts';import { deriveTrust, derivedMaintenanceTransaction, lowerDerivedPage } from './trust/taint.ts';+import { derivedGateConfig, derivedGateInput, recordTimelineFlag, timelineRowAllowed } from './trust/derived-gate.ts';+import { assessTimelineForGate } from './write-gate.ts';// ---------------------------------------------------------------------------// Types@@ -243,12 +245,14 @@ export async function enrichEntity(// 4. Add timeline entrylet timelineAdded = false;try {- await maintenanceTransaction(engine, tx => tx.addTimelineEntry(slug, { // gbrain-allow-direct-insert: auto-timeline reconciliation triggered by entity reference in source markdown- date: new Date().toISOString().split('T')[0] ?? '',- summary: `Referenced in [${request.sourceSlug}](${request.sourceSlug}) — ${request.context}`,- source: request.sourceSlug,- }, scope), derivation.trust);- timelineAdded = true;+ const entry = { date: new Date().toISOString().split('T')[0] ?? '', summary: `Referenced in [${request.sourceSlug}](${request.sourceSlug}) — ${request.context}`, source: request.sourceSlug };+ // #5575 B3: the caller's context lands on the entity page, so it passes the write gate at the derived tier.+ const assessment = assessTimelineForGate(entry, derivedGateInput(derivation.trust), await derivedGateConfig(engine));+ timelineAdded = timelineRowAllowed(assessment) && await maintenanceTransaction(engine, async tx => {+ const added = await tx.addTimelineEntry(slug, entry, scope); // gbrain-allow-direct-insert: auto-timeline reconciliation triggered by entity reference in source markdown+ if (added) await recordTimelineFlag(tx, assessment, { slug, source_id: sourceId, ...entry });+ return true;+ }, derivation.trust);} catch {// Timeline add failed (page might not support it)}diff --git a/src/core/extract-timeline-from-meetings.ts b/src/core/extract-timeline-from-meetings.tsindex 97d7d25508..6579095652 100644--- a/src/core/extract-timeline-from-meetings.ts+++ b/src/core/extract-timeline-from-meetings.ts@@ -19,6 +19,8 @@ import { isPrivatePage } from './search/private-visibility.ts';import { quarantineFilterFragment } from './quarantine.ts';import { maintenanceTransaction } from './persistence/attribution.ts';import { derivedWriteTrust } from './trust/taint.ts';+import { derivedGateConfig, derivedGateInput, recordTimelineFlag, timelineRowAllowed } from './trust/derived-gate.ts';+import { assessTimelineForGate } from './write-gate.ts';import { storedTrustTier, type TaintInput } from './trust/tier.ts';export interface ExtractTimelineFromMeetingsOpts {@@ -45,6 +47,8 @@ export interface ExtractTimelineFromMeetingsResult {batch_errors: number;/** First batch-insert error message, when batch_errors > 0. */first_batch_error?: string;+ /** #5575 B3: rows the write gate quarantined or rejected (timeline rows are skipped, not held). */+ write_gate_skipped?: number;}interface MeetingRow {@@ -137,6 +141,8 @@ export async function extractTimelineFromMeetings(const batch: TimelineBatchInput[] = [];// #5575 I2: the rows restate their meeting (no model), so a batch holds one meeting tier and is stamped with it.const batchInputs: TaintInput[] = [];+ const gateCfg = await derivedGateConfig(engine);+ let gateSkipped = 0;let entriesCreated = 0;const entitiesTouched = new Set<string>();let meetingsScanned = 0;@@ -151,7 +157,14 @@ export async function extractTimelineFromMeetings(if (!dryRun) {try {const trust = derivedWriteTrust({ channel: 'derive:meeting_timeline', inputs: batchInputs, projection: true });- entriesCreated += await maintenanceTransaction(engine, tx => tx.addTimelineEntriesBatch(batch), trust);+ // #5575 B3: the meeting title lands on other pages, so each row passes the write gate at the meeting's tier.+ const kept = batch.map(row => ({ row, assessment: assessTimelineForGate(row, derivedGateInput(trust), gateCfg) })).filter(r => timelineRowAllowed(r.assessment));+ gateSkipped += batch.length - kept.length;+ entriesCreated += kept.length === 0 ? 0 : await maintenanceTransaction(engine, async tx => {+ const count = await tx.addTimelineEntriesBatch(kept.map(r => r.row));+ for (const r of kept) await recordTimelineFlag(tx, r.assessment, r.row);+ return count;+ }, trust);} catch (e) {// #2057: do NOT swallow. A bare `catch {}` here hid a brain-wide// timeline-write failure (the run reported 0 entries with no error).@@ -281,5 +294,6 @@ export async function extractTimelineFromMeetings(entities_touched: entitiesTouched.size,batch_errors: batchErrors,first_batch_error: firstBatchError,+ ...(gateSkipped ? { write_gate_skipped: gateSkipped } : {}),};}diff --git a/src/core/trust/derived-gate.ts b/src/core/trust/derived-gate.tsindex aaa977c60d..91405cdf3f 100644--- a/src/core/trust/derived-gate.ts+++ b/src/core/trust/derived-gate.ts@@ -10,7 +10,8 @@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 { recordFlaggedRow, recordWriteGateHold, recordWriteGateReceipt, type GatedRowDecision } from '../write-gate-store.ts';+import type { WriteGateAssessment } from '../write-gate.ts';import type { WriteTrust } from './tier.ts';/** `write_gate.*` as the import path reads it; unreadable values fall back to the defaults, never `off`. */@@ -40,3 +41,23 @@ export async function applyGateDecision(tx: BrainEngine, decision: GatedRowDecisif (id !== null && await recordFlaggedRow(tx, decision, { table: target.table, id, sourceId: target.sourceId }) !== null && tally) tally.flagged++;return id;}++/** Whether a timeline row's assessment lets it be written: timeline rows have no hold store, so quarantine and reject skip the row. */+export function timelineRowAllowed(assessment: WriteGateAssessment): boolean {+ return assessment.verdict === 'allow' || assessment.verdict === 'flag';+}++/**+ * Records a flagged timeline row's receipt after its insert, in the same+ * transaction. Batch inserts return no ids, so the row is found by its+ * natural key (page, date, summary, source).+ */+export async function recordTimelineFlag(tx: BrainEngine, assessment: WriteGateAssessment,+ row: { slug: string; source_id?: string; date: string; summary: string; source?: string | null }, requestId?: string | null): Promise<void> {+ if (assessment.verdict !== 'flag') return;+ const sourceId = row.source_id ?? 'default';+ const [entry] = await tx.executeRaw<{ id: number }>(`SELECT te.id FROM timeline_entries te JOIN pages p ON p.id=te.page_id+ WHERE p.source_id=$1 AND p.slug=$2 AND te.date=$3::date AND te.summary=$4 AND COALESCE(te.source,'')=COALESCE($5,'') ORDER BY te.id DESC LIMIT 1`,+ [sourceId, row.slug, row.date, row.summary, row.source ?? null]);+ if (entry) await recordWriteGateReceipt(tx, { targetTable: 'timeline_entries', targetId: Number(entry.id), sourceId, assessment, requestId });+}diff --git a/src/core/trust/timeline-projection.ts b/src/core/trust/timeline-projection.tsindex 66f95d190f..304de3679b 100644--- a/src/core/trust/timeline-projection.ts+++ b/src/core/trust/timeline-projection.ts@@ -3,13 +3,17 @@* timeline walks) are a deterministic projection of that page: each row takes* its page's stored tier, capped at operator_curated. Rows of pages with* different tiers commit in separate attributed maintenance transactions, so- * a batch never mixes tiers.+ * a batch never mixes tiers. Each row passes the write gate at its tier (an+ * owner page never runs it): a quarantined or rejected row is skipped (timeline+ * rows have no hold store), a flagged row gets its receipt.*/import type { BatchOpts, BrainEngine, TimelineBatchInput } from '../engine.ts';import type { TimelineInput } from '../types.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { derivedWriteTrust } from './taint.ts';import { storedTrustTier, type TaintInput, type TrustTier } from './tier.ts';+import { derivedGateConfig, derivedGateInput, recordTimelineFlag, timelineRowAllowed } from './derived-gate.ts';+import { assessTimelineForGate } from '../write-gate.ts';const CHANNEL = 'derive:timeline';@@ -36,10 +40,17 @@ export async function addProjectedTimelineBatch(engine: BrainEngine, rows: Timelgroup.rows.push(row);if (input) group.inputs.set(key(row), input);}+ const cfg = await derivedGateConfig(engine);let inserted = 0;for (const group of groups.values()) {const trust = derivedWriteTrust({ channel: CHANNEL, inputs: [...group.inputs.values()], projection: true });- inserted += await maintenanceTransaction(engine, tx => tx.addTimelineEntriesBatch(group.rows, opts), trust);+ const kept = group.rows.map(row => ({ row, assessment: assessTimelineForGate(row, derivedGateInput(trust), cfg) })).filter(r => timelineRowAllowed(r.assessment));+ if (!kept.length) continue;+ inserted += await maintenanceTransaction(engine, async tx => {+ const count = await tx.addTimelineEntriesBatch(kept.map(r => r.row), opts);+ for (const r of kept) await recordTimelineFlag(tx, r.assessment, r.row);+ return count;+ }, trust);}return inserted;}@@ -49,5 +60,11 @@ export async function addProjectedTimelineEntry(engine: BrainEngine, slug: strinentry: TimelineInput, opts?: { sourceId?: string }): Promise<boolean> {const input = (await pageInputs(engine, [{ source_id: opts?.sourceId ?? 'default', slug }])).get(`${opts?.sourceId ?? 'default'}:${slug}`);const trust = derivedWriteTrust({ channel: CHANNEL, inputs: input ? [input] : [], projection: true });- return maintenanceTransaction(engine, tx => tx.addTimelineEntry(slug, entry, opts), trust); // gbrain-allow-direct-insert: gbrain extract single-row fallback for timeline entries, stamped with the page tier+ const assessment = assessTimelineForGate(entry, derivedGateInput(trust), await derivedGateConfig(engine));+ if (!timelineRowAllowed(assessment)) return false;+ return maintenanceTransaction(engine, async tx => {+ const added = await tx.addTimelineEntry(slug, entry, opts); // gbrain-allow-direct-insert: gbrain extract single-row fallback for timeline entries, stamped with the page tier+ if (added) await recordTimelineFlag(tx, assessment, { slug, source_id: opts?.sourceId, date: entry.date, summary: entry.summary, source: entry.source });+ return added;+ }, trust);}