Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): attribute and tier gbrain extract timeline walks, enrichment and meeting timeline extraction as derivers (#5575 L1a-taint)
garrytan8435e09a5edc
diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex b9152c786d..4bd2b15767 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -68,6 +68,7 @@ import { PageRegexBudget } from '../core/schema-pack/redos-guard.ts';export { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';import { extractTimelineFromContent, pruneTimelineOrphans, retractRemovedTimelineEntries, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';+import { addProjectedTimelineBatch, addProjectedTimelineEntry } from '../core/trust/timeline-projection.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { pathToSlug, slugifyPath, slugifySegment, pruneDir, isSyncable } from '../core/sync.ts';@@ -244,7 +245,6 @@ export interface ExtractedLink {origin_field?: string;}-interface ExtractResult {links_created: number;timeline_entries_created: number;@@ -1375,7 +1375,7 @@ async function extractForSlugs(const snapshot = timelineBatch.slice();timelineBatch.length = 0;try {- timelineCreated += await engine.addTimelineEntriesBatch(snapshot, { auditSite: 'extract.timeline_inc' });+ timelineCreated += await addProjectedTimelineBatch(engine, snapshot, { auditSite: 'extract.timeline_inc' });} catch (e) {const msg = e instanceof Error ? e.message : String(e);if (jsonMode) {@@ -1581,7 +1581,7 @@ async function extractTimelineFromDir(const snapshot = batch.slice();batch.length = 0;try {- created += await engine.addTimelineEntriesBatch(snapshot, { auditSite: 'extract.timeline_fs' });+ created += await addProjectedTimelineBatch(engine, snapshot, { auditSite: 'extract.timeline_fs' });} catch (e) {const msg = e instanceof Error ? e.message : String(e);if (jsonMode) {@@ -1761,7 +1761,7 @@ export async function extractTimelineForSlugs(await retractRemovedTimelineEntries(engine, slug, opts?.sourceId ?? 'default', content);processed.push(slug);for (const entry of entries) {- try { await engine.addTimelineEntry(entry.slug, { date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail }, entryOpts); created++; } catch { /* skip */ } // gbrain-allow-direct-insert: gbrain extract single-row fallback for timeline entries+ try { await addProjectedTimelineEntry(engine, entry.slug, { date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail }, entryOpts); created++; } catch { /* skip */ }}} catch (e) { errors.push({ slug, error: e instanceof Error ? e.message : String(e) }); }}@@ -2155,7 +2155,7 @@ export async function extractStaleFromDB(const attendanceBlocked: Array<{ slug: string; source_id: string; revision: string }> = [];const flushBatch = async () => {for (let i = 0; i < timelineRows.length; i += BATCH_SIZE) {- timelineCreated += await engine.addTimelineEntriesBatch(timelineRows.slice(i, i + BATCH_SIZE), { auditSite: 'extract.stale' });+ timelineCreated += await addProjectedTimelineBatch(engine, timelineRows.slice(i, i + BATCH_SIZE), { auditSite: 'extract.stale' });}// Stamp LAST, directly (not the swallowing stampExtracted) so a stamp// failure surfaces instead of looping forever.diff --git a/src/core/enrichment-service.ts b/src/core/enrichment-service.tsindex 13c35ec9e0..4692fa7186 100644--- a/src/core/enrichment-service.ts+++ b/src/core/enrichment-service.ts@@ -27,6 +27,8 @@ import { isAvailable } from './ai/gateway.ts';// #4222: shared generic-token reject list — same list gates the by-mention// gazetteer and drives the junk_entity_hubs doctor check.import { isJunkEntityName } from './entity-name-quality.ts';+import { maintenanceTransaction } from './persistence/attribution.ts';+import { deriveTrust, derivedMaintenanceTransaction, lowerDerivedPage } from './trust/taint.ts';// ---------------------------------------------------------------------------// Types@@ -150,6 +152,8 @@ export async function enrichEntity(// Fail-closed: only an explicit `trusted: true` writes authoritative pages.const trusted = opts?.trusted === true;const scope = opts?.sourceId ? { sourceId: opts.sourceId } : undefined;+ // #5575 I2: a stub and its timeline row restate the source page's mention, so they carry its taint (capped at agent_written).+ const derivation = await deriveTrust(engine, [{ table: 'pages', sourceId, slug: request.sourceSlug }], { channel: 'derive:enrichment' });// 1. Count existing mentions for tier auto-escalationconst { mentionCount, mentionSources } = await countMentions(engine, request.entityName, opts?.sourceId);@@ -217,6 +221,7 @@ export async function enrichEntity(noEmbed: !isAvailable('embedding'),...(opts?.sourceId ? { sourceId: opts.sourceId } : {}),});+ await lowerDerivedPage(engine, derivation, sourceId, slug);} catch (e) {// Fail-open fallback: a pipeline error (parse edge case, size guard)// must never regress the batch — the pre-#3994 direct write still@@ -227,13 +232,10 @@ export async function enrichEntity(`[enrich] import pipeline failed for stub ${slug} (${e instanceof Error ? e.message : String(e)}); ` +'falling back to a direct unchunked write — the page exists but is not chunked/embedded until re-imported.\n',);- await engine.putPage(slug, {- title,- type,- compiled_truth: content,- timeline: '',- frontmatter,- }, scope);+ await derivedMaintenanceTransaction(engine, derivation, async tx => {+ const page = await tx.putPage(slug, { title, type, compiled_truth: content, timeline: '', frontmatter }, scope);+ return { result: page, rows: [{ table: 'pages', id: page.id, sourceId }] };+ });}action = 'created';}@@ -241,11 +243,11 @@ export async function enrichEntity(// 4. Add timeline entrylet timelineAdded = false;try {- await engine.addTimelineEntry(slug, { // gbrain-allow-direct-insert: auto-timeline reconciliation triggered by entity reference in source markdown+ await maintenanceTransaction(engine, tx => tx.addTimelineEntry(slug, { // gbrain-allow-direct-insert: auto-timeline reconciliation triggered by entity reference in source markdowndate: new Date().toISOString().split('T')[0] ?? '',summary: `Referenced in [${request.sourceSlug}](${request.sourceSlug}) — ${request.context}`,source: request.sourceSlug,- }, scope);+ }, scope), derivation.trust);timelineAdded = true;} 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 db6b460926..97d7d25508 100644--- a/src/core/extract-timeline-from-meetings.ts+++ b/src/core/extract-timeline-from-meetings.ts@@ -17,6 +17,9 @@ import { computeEffectiveDate } from './effective-date.ts';import { parseFrontmatter } from './backfill-effective-date.ts';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 { storedTrustTier, type TaintInput } from './trust/tier.ts';export interface ExtractTimelineFromMeetingsOpts {dryRun?: boolean;@@ -45,6 +48,8 @@ export interface ExtractTimelineFromMeetingsResult {}interface MeetingRow {+ id: number;+ trust_tier: string | null;slug: string;source_id: string;title: string;@@ -83,7 +88,7 @@ export async function extractTimelineFromMeetings(const sourceFilter = opts.sourceIdFilter ? `AND source_id = $1` : '';const meetingParams = opts.sourceIdFilter ? [opts.sourceIdFilter] : [];const meetings = await engine.executeRaw<MeetingRow>(- `SELECT slug, source_id, title, effective_date, frontmatter, import_filename,+ `SELECT id, trust_tier, slug, source_id, title, effective_date, frontmatter, import_filename,created_at, updated_at, compiled_truth, COALESCE(timeline, '') AS timelineFROM pagesWHERE ${MEETING_PAGE_PREDICATE}@@ -130,6 +135,8 @@ export async function extractTimelineFromMeetings(const allowCrossSource = await isCrossSourceLinksEnabled(engine);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[] = [];let entriesCreated = 0;const entitiesTouched = new Set<string>();let meetingsScanned = 0;@@ -140,10 +147,11 @@ export async function extractTimelineFromMeetings(let firstBatchError: string | undefined;async function flush() {- if (batch.length === 0) return;+ if (batch.length === 0) { batchInputs.length = 0; return; }if (!dryRun) {try {- entriesCreated += await engine.addTimelineEntriesBatch(batch);+ const trust = derivedWriteTrust({ channel: 'derive:meeting_timeline', inputs: batchInputs, projection: true });+ entriesCreated += await maintenanceTransaction(engine, tx => tx.addTimelineEntriesBatch(batch), 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).@@ -158,6 +166,7 @@ export async function extractTimelineFromMeetings(entriesCreated += batch.length;}batch.length = 0;+ batchInputs.length = 0;}for (const meeting of meetings) {@@ -232,6 +241,9 @@ export async function extractTimelineFromMeetings(}// Emit one timeline row per (entity, this meeting).+ const input: TaintInput = { table: 'pages', id: Number(meeting.id), tier: storedTrustTier(meeting.trust_tier) };+ if (targets.size && batchInputs.length && batchInputs[0].tier !== input.tier) await flush();+ if (targets.size) batchInputs.push(input);for (const t of targets.values()) {batch.push({slug: t.slug,@@ -241,7 +253,7 @@ export async function extractTimelineFromMeetings(summary,});entitiesTouched.add(`${t.source_id}::${t.slug}`);- if (batch.length >= BATCH_SIZE) await flush();+ if (batch.length >= BATCH_SIZE) { await flush(); batchInputs.push(input); }}}diff --git a/src/core/trust/timeline-projection.ts b/src/core/trust/timeline-projection.tsnew file mode 100644index 0000000000..66f95d190f--- /dev/null+++ b/src/core/trust/timeline-projection.ts@@ -0,0 +1,53 @@+/**+ * #5575 I2: timeline rows parsed from a page's own timeline (`gbrain extract`+ * 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.+ */+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';++const CHANNEL = 'derive:timeline';++async function pageInputs(engine: BrainEngine, refs: Array<{ source_id: string; slug: string }>): Promise<Map<string, TaintInput>> {+ const rows = await engine.executeRaw<{ id: number | string; source_id: string; slug: string; trust_tier: string | null }>(+ `SELECT p.id,p.source_id,p.slug,p.trust_tier FROM pages p+ JOIN jsonb_to_recordset($1::text::jsonb) AS r(source_id text,slug text) ON p.source_id=r.source_id AND p.slug=r.slug`,+ [JSON.stringify(refs)]);+ return new Map(rows.map(row => [`${row.source_id}:${row.slug}`, { table: 'pages', id: Number(row.id), tier: storedTrustTier(row.trust_tier) }]));+}++/** addTimelineEntriesBatch, stamped per page tier. Returns the rows inserted. */+export async function addProjectedTimelineBatch(engine: BrainEngine, rows: TimelineBatchInput[], opts?: BatchOpts): Promise<number> {+ if (!rows.length) return 0;+ const key = (row: TimelineBatchInput) => `${row.source_id ?? 'default'}:${row.slug}`;+ const refs = [...new Map(rows.map(row => [key(row), { source_id: row.source_id ?? 'default', slug: row.slug }])).values()];+ const inputs = await pageInputs(engine, refs);+ const groups = new Map<TrustTier, { rows: TimelineBatchInput[]; inputs: Map<string, TaintInput> }>();+ for (const row of rows) {+ const input = inputs.get(key(row));+ const tier = input?.tier ?? 'unknown';+ let group = groups.get(tier);+ if (!group) groups.set(tier, group = { rows: [], inputs: new Map() });+ group.rows.push(row);+ if (input) group.inputs.set(key(row), input);+ }+ 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);+ }+ return inserted;+}++/** addTimelineEntry for one row of `slug`'s own timeline, stamped with the page's tier. */+export async function addProjectedTimelineEntry(engine: BrainEngine, slug: string,+ entry: 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+}