Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): chronicle, think --save/--take, concepts and atoms stamp their inputs' taint (#5575 L1a-taint, ENG-3, ENG-7)
garrytan51cc10f73528
diff --git a/src/core/chronicle/publish.ts b/src/core/chronicle/publish.tsindex 4b5515bf5d..1e27b9fbe7 100644--- a/src/core/chronicle/publish.ts+++ b/src/core/chronicle/publish.ts@@ -41,6 +41,7 @@ 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';export const CHRONICLE_RETIRED_BY = 'life-chronicle';export const CHRONICLE_EVENT_INTENT = 'managed_maintenance_chronicle_event';@@ -175,6 +176,8 @@ export async function publishChronicleGeneration(engine: BrainEngine, opts: {const broken = await depthPinBroken(engine, sourceId, pin, opts.decisionRequestId);if (broken) return { ...result, superseded: broken };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' });for (const ev of events) {abort();@@ -187,18 +190,19 @@ export async function publishChronicleGeneration(engine: BrainEngine, opts: {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 };+ owned_hashes: [...owned], 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 {- await maintenanceTransaction(engine, async (tx) => {+ await derivedMaintenanceTransaction(engine, derivation, async (tx) => {const reason = await depthPinBroken(tx, sourceId, pin, null);if (reason) throw supersededError(reason);const again = judgeTarget(await tx.readPageSnapshot(ev.slug, { sourceId, includeDeleted: true }), owned);if (!again.write) throw supersededError(again.reason);- await tx.putPage(ev.slug, { type: 'event', title: ev.title, compiled_truth: ev.compiledTruth,+ 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 });+ return { result: undefined, rows: [{ table: 'pages', id: page.id, sourceId }] };});}} catch (error) {diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.tsindex 68e19fdf86..ed694f9299 100644--- a/src/core/cycle/concept-publication.ts+++ b/src/core/cycle/concept-publication.ts@@ -20,6 +20,11 @@ import { existsSync, readFileSync } from 'node:fs';import { acquirePageLock } from '../page-lock.ts';import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';import { writeDerivedPageThrough } from './derived-write-through.ts';+import { declareDerivation, lowerDerivedPage } from '../trust/taint.ts';+import type { TaintInput, WriteTrust } from '../trust/tier.ts';++/** #5575 I2: the member atoms the concept narrative was synthesized from, with their tiers. */+export interface ConceptDerivation { trust: WriteTrust; inputs: readonly TaintInput[] }/** Error code for a concept held because republication could lose canonical material. */export const CONCEPT_PRESERVATION_CODE = 'concept_preservation_hold';@@ -39,7 +44,8 @@ function conceptHoldError(message: string): Error { return Object.assign(new Err* `db_only` storage tier always wins.*/export async function publishManagedConcept(engine: BrainEngine, authority: MaintenanceAuthority,- slug: string, synthesized: Record<string, unknown>, narrative: string, expectedRevision: string | null, brainDir?: string): Promise<string | null> {+ slug: string, synthesized: Record<string, unknown>, narrative: string, expectedRevision: string | null, brainDir?: string,+ derivation?: ConceptDerivation): Promise<string | null> {const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId, includeDeleted: true });// The narrative was synthesized from the revision read before the model call// (or the previous publication's result); an intervening edit wins.@@ -60,7 +66,7 @@ export async function publishManagedConcept(engine: BrainEngine, authority: Main? composeConceptRepublication(snapshot.page, snapshot.tags, synthesized, narrative): serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] });const receipt = await publishMaintenancePage(engine, authority, slug, markdown,- { expectedRevision: snapshot?.revision ?? null, file: !dbOnly });+ { expectedRevision: snapshot?.revision ?? null, file: !dbOnly, ...(derivation ? { derivation: declareDerivation(derivation.trust, derivation.inputs) } : {}) });return typeof receipt.revision === 'string' ? receipt.revision : null;}@@ -184,7 +190,7 @@ async function conceptFile(engine: BrainEngine, slug: string, sourceId: string):*/export async function publishClassicConcept(engine: BrainEngine, slug: string, sourceId: string,synthesized: Record<string, unknown>, narrative: string, baseline: string,- opts: { writeThrough: boolean; importPage: (markdown: string) => Promise<unknown> }): Promise<string> {+ opts: { writeThrough: boolean; importPage: (markdown: string) => Promise<unknown>; derivation?: ConceptDerivation }): Promise<string> {const lock = await acquirePageLock(slug, { timeoutMs: 5_000 });if (!lock) throw Object.assign(new Error('The concept page is locked by another writer.'), { code: 'revision_conflict' });try {@@ -200,6 +206,8 @@ export async function publishClassicConcept(engine: BrainEngine, slug: string, s? composeConceptRepublication({ ...page, ...file }, snapshot!.tags, synthesized, narrative): serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] });await opts.importPage(markdown);+ // The import stamps the page by its own channel; the derivation lowers it to the members' taint and records the edges.+ if (opts.derivation) await lowerDerivedPage(engine, opts.derivation, sourceId, slug);if (file || opts.writeThrough) await writeDerivedPageThrough(engine, slug, sourceId);return narrative;} finally {diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex d63e871ce8..13ff5f0ae1 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -94,6 +94,7 @@ import type { WriteReceipt } from '../persistence/types.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { AtomPageStateError, completeAtomReceipts, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';+import { deriveTrust, lowerDerivedPage } from '../trust/taint.ts';import { ATOM_TYPES, ATOMS_RESPONSE_SCHEMA } from './extract-atoms-schema.ts';import { parseAtomsOutcome } from './extract-atoms-parse.ts';export { parseAtomsOutcome, parseAtomsResponse, type AtomsParseOutcome } from './extract-atoms-parse.ts';@@ -1256,10 +1257,8 @@ export async function runPhaseExtractAtoms({ type: 'atom', title: atom.title, tags: [] },);if (managed) managedAtoms.push({ slug, content: md, links: [] });- else await importFromContent(engine, slug, md, {- sourceId, preserveGateMarkers: true,- noEmbed: !isAvailable('embedding'),- });+ else await importFromContent(engine, slug, md, { sourceId, preserveGateMarkers: true, noEmbed: !isAvailable('embedding') }) // #5575 I2: then the atom takes its origin page's taint+ .then(async () => lowerDerivedPage(engine, await deriveTrust(engine, item.kind === 'page' ? [{ table: 'pages', sourceId, slug: item.slug }] : [], { channel: 'derive:atoms' }), sourceId, slug));importedSlugs.push(slug);if (item.kind === 'page') {provenanceLinks.push({diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex 8f330b2ed1..c5f07db5dd 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -40,6 +40,7 @@ import { pricingSetCommand } from '../budget/no-pricing.ts';import { createHash } from 'node:crypto';import { slugifySegment } from '../sync.ts';import { validatePageSlug } from '../ops/context.ts';+import { deriveTrust } from '../trust/taint.ts';import { privatePagesFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';import { derivedWriteThrough } from './derived-write-through.ts';@@ -492,15 +493,18 @@ export async function runPhaseSynthesizeConcepts(// Unmanaged: the narrative the page held when synthesis started; a// different narrative under the page lock defers the concept (D-N3).let baseline = existing?.compiled_truth ?? '';+ // #5575 I2: the narrative carries the tier of the member atoms in its prompt (capped at agent_written).+ const derivation = await deriveTrust(engine, [...new Set(group.atomSlugs)].map(slug => ({ table: 'pages' as const, sourceId: opts.sourceId ?? 'default', slug })),+ { channel: 'derive:concepts' });const publish = async (pageVisibility: Visibility): Promise<void> => {if (maintenance) {conceptRevision = await publishManagedConcept(engine, maintenance, conceptSlug, synthesized(pageVisibility), narrative,- conceptRevision, opts.brainDir);+ conceptRevision, opts.brainDir, derivation);return;}// #4416: target the cycle's resolved source, not the 'default' literal.baseline = await publishClassicConcept(engine, conceptSlug, opts.sourceId ?? 'default', synthesized(pageVisibility), narrative,- baseline, { writeThrough: conceptFiles !== null, importPage: (markdown) => importFromContent(engine, conceptSlug, markdown, {+ baseline, { writeThrough: conceptFiles !== null, derivation, importPage: (markdown) => importFromContent(engine, conceptSlug, markdown, {noEmbed: !isAvailable('embedding'), sourceId: opts.sourceId, preserveGateMarkers: true,}) });};diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex fb44e00c9f..4581b713ca 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -307,7 +307,7 @@ const think: Operation = {if (remote && (Boolean(p.save) || Boolean(p.take))) ctx.emitNotice?.(thinkNotSavedNotice());const { recordThinkAnswer, feedbackMetaFields } = await import('../feedback/record.ts');const feedbackMeta = feedbackMetaFields(await recordThinkAnswer(ctx, 'think', result));- delete result.feedback_evidence;+ delete result.feedback_evidence; delete result.taint_refs;const { persist: _persist, ...visible } = result;return {...visible,diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.tsindex 1b4d4ad451..8ae66e087e 100644--- a/src/core/persistence/atom-maintenance.ts+++ b/src/core/persistence/atom-maintenance.ts@@ -21,6 +21,7 @@ import type { WriteAuthority, WriteRequest } from './model.ts';import type { WriteReceipt } from './types.ts';import { writeAtomPageState } from '../cycle/extract-atoms-page-state.ts';import { effectiveVisibility } from '../search/private-visibility.ts';+import { deriveTrust, lowerToDerivedTier, recordTaintEdges } from '../trust/taint.ts';export interface AtomOrigin {kind: 'page' | 'transcript';@@ -505,9 +506,17 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write}await authorizeWrite(engine, row.authority, 'put_page', row.slug);const prepared = await preparePageMutation(engine, { ...row, operation: 'put_page' }, config, undefined, undefined, { allowMissingFile: true });- return { ...prepared, additionalPageKeys, validate: async tx => { await validate(tx); await authorizeWrite(tx, row.authority, 'put_page', row.slug); await prepared.validate?.(tx); }, apply: async tx => {+ // #5575 I2: the extractor read only the origin (a page, or a transcript file of the user's own sessions).+ const derivation = await deriveTrust(engine, p.origin.kind === 'page' && p.origin.pageId !== null ? [{ table: 'pages', id: p.origin.pageId }] : [],+ { channel: 'derive:atoms', requestId: row.id });+ return { ...prepared, trust: derivation.trust, additionalPageKeys, validate: async tx => { await validate(tx); await authorizeWrite(tx, row.authority, 'put_page', row.slug); await prepared.validate?.(tx); }, apply: async tx => {const result = await prepared.apply(tx);if (p.links?.length) await tx.addLinksBatch(p.links, { auditSite: 'cycle.extract_atoms.provenance' });+ const [atom] = 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 (atom) {+ await lowerToDerivedTier(tx, 'pages', [Number(atom.id)], derivation.trust);+ await recordTaintEdges(tx, { table: 'pages', id: Number(atom.id), sourceId: row.source_id }, derivation.inputs);+ }return { ...result, atom_run_key: p.runKey, atom_kind: p.kind };} };}diff --git a/src/core/takes-write.ts b/src/core/takes-write.tsindex cc79322bc7..b45c33f934 100644--- a/src/core/takes-write.ts+++ b/src/core/takes-write.ts@@ -59,6 +59,7 @@ import { isWriteTargetContained, msysToNativePath } from './path-confine.ts';import { atomicWriteFileSync } from './atomic-write.ts';import { commitWriteThroughFile, isDurabilityHardened } from './brain-repo-durability.ts';import { maintenanceTransaction } from './persistence/attribution.ts';+import type { WriteTrust } from './trust/tier.ts';export type TakesWriteErrorCode =| 'page_not_found' // slug has no pages row (scoped)@@ -96,6 +97,8 @@ export interface TakesWriteTarget {allowList?: HolderAllowList;/** Lock wait budget. CLI keeps the 30s default; ops pass ~2000. */lockTimeoutMs?: number;+ /** #5575 I2: a deriver's tier for the added row (`think --take`); absent, the row is undeclared. */+ trust?: WriteTrust;}/**@@ -572,7 +575,7 @@ export async function addTakeToPage(holder: input.holder, weight: input.weight ?? 0.5,since_date: input.sinceDate, source: input.source,active: true, superseded_by: null,- }]));+ }]), target.trust);} catch (err) {// P1-4/F4: md is canonical + already written — a failed DB mirror is// healed by the next reconcile, so surface a warning instead of throwingdiff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 8f8508353f..220048ba1c 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -37,7 +37,7 @@ import { resolveExcludePrivatePages } from '../search/private-visibility.ts';import { deliverEvidence, effectivePlan, resolveEvidencePlan, EVIDENCE_BLOCK_CHAR_CAP, THINK_RETURN_UNIT_CONFIG_KEY, type DeliveryMeta } from '../search/evidence-delivery.ts';import { startThinkDecide, thinkAbstainResult, type ThinkAbstention } from './decide.ts';import { classifyIntent } from './intent.ts';-import { maintenanceTransaction } from '../persistence/attribution.ts';+import { deriveTrust, derivedMaintenanceTransaction, type TaintRef } from '../trust/taint.ts';/** Anthropic Messages client interface — same shape used by subagent.ts so test stubs can be shared. */export interface ThinkLLMClient {@@ -219,6 +219,8 @@ export interface ThinkResult {evidence_delivery?: import('../search/evidence-delivery.ts').DeliveryMeta;/** Gathered pages with the revision retrieved, for retrieval-feedback recording; the op layer strips it. */feedback_evidence?: Array<{ source_id: string; slug: string; content_hash: string | null }>;+ /** #5575 I2: every page, take and trajectory fact placed in the synthesis prompt; `persistSynthesis` taints from them. The op layer strips it. */+ taint_refs?: TaintRef[];/** Only set when --save was true and the caller persisted a synthesis page. */savedSlug?: string;/**@@ -673,6 +675,7 @@ export async function runThink(// is the kill switch. `withTrajectory: false` caller opt also bypasses.// `other` intent short-circuits before any SQL fires.let trajectoryBlock = '';+ const trajectoryFactIds: number[] = [];let trajectoryPointsCount = 0;let trajectoryExcludedCount = 0;const trajectoryEnabledConfig = await readThinkTrajectoryEnabled(engine);@@ -729,6 +732,7 @@ export async function runThink(return !outside;}) : points;if (boundedPoints.length === 0) return null;+ trajectoryFactIds.push(...boundedPoints.map(point => point.fact_id));const fmt = formatTrajectoryBlock(boundedPoints, resolved.slug, {intent: trajIntent,});@@ -989,6 +993,8 @@ export async function runThink(synthesisOk: synthesisOk && response.answer.trim().length > 0,synthesis_status: synthesisStatus,feedback_evidence: gather.pages.map(pg => ({ source_id: pg.source_id ?? 'default', slug: pg.slug, content_hash: pg.content_hash ?? null })),+ taint_refs: [...gather.pages.map(pg => ({ table: 'pages' as const, sourceId: pg.source_id ?? 'default', slug: pg.slug })),+ ...gather.takes.map(t => ({ table: 'takes' as const, id: t.take_id })), ...trajectoryFactIds.map(id => ({ table: 'facts' as const, id }))],...(extractive ? { extractive } : {}),usage, ...(evidenceDelivery ? { evidence_delivery: evidenceDelivery } : {}),diagnostics: {@@ -1080,7 +1086,9 @@ export async function persistSynthesis(result.gaps.length > 0 ? '## Gaps\n\n' + result.gaps.map(g => `- ${g}`).join('\n') : '',].filter(Boolean).join('\n');- const page = await maintenanceTransaction(engine, tx => tx.putPage(slug, {+ const derivation = await deriveTrust(engine, result.taint_refs ?? [], { channel: 'derive:think' });+ const page = await derivedMaintenanceTransaction(engine, derivation, async tx => {+ const written = await tx.putPage(slug, {title: result.question.slice(0, 200),type: 'synthesis',compiled_truth: body,@@ -1093,7 +1101,9 @@ export async function persistSynthesis(takes_gathered: result.takesGathered,...(result.persist?.unverified_claims.length ? { unverified_claims: result.persist.unverified_claims.map(c => ({ ...c, sources: ['think evidence'], detected_at: today })) } : {}),},- }, scope.sourceId ? { sourceId: scope.sourceId } : undefined));+ }, scope.sourceId ? { sourceId: scope.sourceId } : undefined);+ return { result: written, rows: [{ table: 'pages' as const, id: written.id, sourceId: scope.sourceId ?? 'default' }] };+ });const persisted = await persistCitations(engine, page.id, result.citations, scope);return { slug, evidenceInserted: persisted.inserted, warnings: persisted.warnings };diff --git a/src/core/think/persist-take.ts b/src/core/think/persist-take.tsindex 5ad8d1e19b..ade62fccc7 100644--- a/src/core/think/persist-take.ts+++ b/src/core/think/persist-take.ts@@ -30,6 +30,7 @@ import type { BrainEngine } from '../engine.ts';import { stripGapsSection, type ThinkResult } from './index.ts';import { resolveOwnerHolder } from '../owner-holder.ts';import { resolveTakesRepoDir, addTakeToPage, TakesWriteError } from '../takes-write.ts';+import { deriveTrust, derivedMaintenanceTransaction } from '../trust/taint.ts';/** Max claim length for a fence cell — one readable line, not an essay. */export const TAKE_CLAIM_MAX_CHARS = 300;@@ -85,7 +86,7 @@ export function claimFromAnswer(answer: string): string | null {*/export async function persistTakeFromSynthesis(engine: BrainEngine,- result: Pick<ThinkResult, 'answer' | 'synthesisOk'>,+ result: Pick<ThinkResult, 'answer' | 'synthesisOk' | 'taint_refs'>,opts: { anchor: string; sourceId?: string; lockTimeoutMs?: number },): Promise<PersistTakeResult> {const warnings: string[] = [];@@ -115,6 +116,8 @@ export async function persistTakeFromSynthesis(configValue: await engine.getConfig('emotional_weight.user_holder'),});+ // #5575 I2: the take restates the synthesis, so it carries the tier of everything in the synthesis prompt.+ const derivation = await deriveTrust(engine, result.taint_refs ?? [], { channel: 'derive:think' });try {const { rowNum, mirror } = await addTakeToPage({@@ -122,12 +125,17 @@ export async function persistTakeFromSynthesis(slug: opts.anchor,brainDir,sourceId: opts.sourceId,+ trust: derivation.trust,...(opts.lockTimeoutMs !== undefined ? { lockTimeoutMs: opts.lockTimeoutMs } : {}),},{ claim, kind: 'take', holder, source: 'think' },);if (mirror.mirror_warning) {warnings.push(`TAKE_DB_MIRROR_WARNING: ${mirror.mirror_warning}`);+ } else {+ await derivedMaintenanceTransaction(engine, derivation, async tx => ({ result: undefined, rows: (await tx.executeRaw<{ id: number }>(+ 'SELECT k.id FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND p.slug=$2 AND k.row_num=$3',+ [opts.sourceId ?? 'default', opts.anchor, rowNum])).map(take => ({ table: 'takes' as const, id: Number(take.id), sourceId: opts.sourceId ?? 'default' })) }));}return { take_row: rowNum, path: mirror.path, warnings };} catch (e) {diff --git a/src/core/trust/taint.ts b/src/core/trust/taint.tsindex d2032ab4f3..3deaba7b0f 100644--- a/src/core/trust/taint.ts+++ b/src/core/trust/taint.ts@@ -149,6 +149,18 @@ export async function derivedMaintenanceTransaction<T>(engine: BrainEngine, deri}, derivation.trust);}+/**+ * A derived page written through a path that stamps by its own channel (an+ * unmanaged importFromContent): lowers the live page to the derivation's+ * taint and records its edges, in one attributed transaction.+ */+export async function lowerDerivedPage(engine: BrainEngine, derivation: { trust: WriteTrust; inputs: readonly TaintInput[] },+ sourceId: string, slug: string): Promise<void> {+ await derivedMaintenanceTransaction(engine, derivation, async tx => ({ result: undefined,+ rows: (await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]))+ .map(row => ({ table: 'pages' as const, id: Number(row.id), sourceId })) }));+}+// ---------------------------------------------------------------------------// Declarations carried in a journaled maintenance intent// ---------------------------------------------------------------------------