Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): patterns partitions external reflections into their own pass and stamps outputs at the pass tier (#5575 L1a-taint, ENG-3, ENG-7)
garrytan2913f498a37f
diff --git a/src/core/cycle/dream-taint.ts b/src/core/cycle/dream-taint.tsindex 628d78e4f7..231a59a3dd 100644--- a/src/core/cycle/dream-taint.ts+++ b/src/core/cycle/dream-taint.ts@@ -9,6 +9,8 @@* sessions: relayed user turns are agent_written); a file under the meeting* transcripts directory is third-party speech, external_untrusted.* - The dream summary page indexes the pages it lists.+ * - Patterns: each pass's outputs take the least trusted reflection submitted+ * in that pass (patterns.ts partitions external reflections into their own pass).*/import { resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';@@ -64,3 +66,10 @@ export async function putDerivedPage(engine: BrainEngine, derivation: Derivationreturn { result: undefined, rows: [{ table: 'pages' as const, id: Number(written.id), sourceId: opts.sourceId }] };});}++/** One patterns pass's derivation: every reflection submitted in its prompt. */+export function patternsDerivation(submitted: Array<{ taint?: TaintInput }>): Derivation & { declaration: DerivationDeclaration } {+ const inputs = submitted.flatMap(r => (r.taint ? [r.taint] : []));+ const trust = derivedWriteTrust({ channel: 'derive:patterns', inputs, lowerTo: inputs.length < submitted.length ? ['unknown'] : [] });+ return { trust, inputs, declaration: declareDerivation(trust, inputs) };+}diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex 94e7d4ae00..245a5ba51c 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -50,6 +50,9 @@ import { resolveCycleDate } from './cycle-date.ts';import { clearPatternsSourceDeaths, patternsBreakerSkip } from './dream-breaker.ts';import { dedupePatternClaimSources, withClaimSources } from './pattern-claim-sources.ts';import { publishOrHold } from '../persistence/accepted-pending.ts';+import { isExternalTier, type DerivationDeclaration } from '../trust/taint.ts';+import { storedTrustTier, type TaintInput } from '../trust/tier.ts';+import { patternsDerivation, type Derivation } from './dream-taint.ts';export interface PatternsPhaseOpts {brainDir: string;@@ -142,11 +145,10 @@ export async function runPhasePatterns(engine: BrainEngine,opts: PatternsPhaseOpts,): Promise<PhaseResult> {- const start = Date.now();- let ownedPrivateQueue: { queue: MinionQueue; name: string } | null = null;+ let config: PatternsConfig, evidenceKey: string, reflections: ReflectionRef[];try {throwIfAborted(opts.signal, '[dream] patterns');- const config = await loadPatternsConfig(engine);+ config = await loadPatternsConfig(engine);if (!config.enabled) {if (!opts.once) {@@ -160,10 +162,31 @@ export async function runPhasePatterns(const [source] = await managedPersistenceEnabled(engine)? await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [opts.sourceId ?? 'default']) : [];- const evidenceKey = source ? `${LAST_EVIDENCE_KEY}.${opts.sourceId ?? 'default'}.${source.incarnation}` : LAST_EVIDENCE_KEY;+ evidenceKey = source ? `${LAST_EVIDENCE_KEY}.${opts.sourceId ?? 'default'}.${source.incarnation}` : LAST_EVIDENCE_KEY;// Gather reflections within lookback window.- const reflections = await gatherReflections(engine, config.lookbackDays, config.sourceSlugPrefix, opts.sourceId ?? 'default');+ reflections = await gatherReflections(engine, config.lookbackDays, config.sourceSlugPrefix, opts.sourceId ?? 'default');+ } catch (e) {+ return failed(makeError('InternalError', 'PATTERNS_PHASE_FAIL',+ e instanceof Error ? (e.message || 'patterns phase threw') : String(e)));+ }+ // #5575 ENG-3: an external_untrusted reflection never shares a prompt with the+ // owner's reflections. External reflections get their own pass (only with+ // enough evidence of their own), and that pass's pattern pages are external.+ const external = reflections.filter(r => isExternalTier(r.taint?.tier ?? 'unknown'));+ const owner = await runPatternsPass(engine, opts, config, reflections.filter(r => !external.includes(r)), evidenceKey);+ if (!external.length) return owner;+ const externalPass = external.length >= config.minEvidence+ ? await runPatternsPass(engine, opts, config, external, `${evidenceKey}.external`) : null;+ return mergeExternalPass(owner, externalPass, external.length);+}++/** One patterns child over one partition of the reflections; `evidenceKey` is that partition's watermark. */+async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, config: PatternsConfig,+ reflections: ReflectionRef[], evidenceKey: string): Promise<PhaseResult> {+ const start = Date.now();+ let ownedPrivateQueue: { queue: MinionQueue; name: string } | null = null;+ try {if (reflections.length < config.minEvidence) {return skipped('insufficient_evidence',@@ -265,6 +288,8 @@ export async function runPhasePatterns(childQueueName, privateQueueOwnerToken, opts.yieldDuringPhase,);const cycleDate = opts.cycleDate ?? await resolveCycleDate(engine);+ // #5575 ENG-3: decided at prompt-build time from exactly the reflections in the prompt.+ const derivation = patternsDerivation(submitted);const data: SubagentHandlerData = {prompt: buildPatternsPrompt(submitted, config.minEvidence, config.sourceSlugPrefix, config.outputSlugPrefix, cycleDate),model: config.model,@@ -373,7 +398,7 @@ export async function runPhasePatterns(const writtenRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId);// #6052: `finalized` leaves out outputs whose managed publication is held (pending or contended); `held` counts them.- const { quoteVerify, finalized, held } = await stampPatternOutputs(engine, maintenance, writtenRefs, submitted, config, cycleSourceId, cycleDate, opts.signal);+ const { quoteVerify, finalized, held } = await stampPatternOutputs(engine, maintenance, writtenRefs, submitted, derivation, config, cycleSourceId, cycleDate, opts.signal);const reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, finalized): await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);const details = { reflections_considered: submitted.length, reflections_selected: selected, plan_basis: plan.basis, patterns_written: finalized.length,@@ -549,6 +574,8 @@ export interface ReflectionRef {updatedAt: Date;/** #4618: the seat the reflection was synthesized from, when stamped. */seat: string | null;+ /** #5575: the reflection page's stored tier; never part of the submission key. */+ taint?: TaintInput;}/** The submission key's reflection identity, unchanged by #4618's seat field@@ -573,9 +600,9 @@ async function gatherReflections(// Reflections live under the configured source slug prefix (bound as a// parameter; see PatternsConfig.sourceSlugPrefix / dream.patterns.source_slug_prefix).const rows = await engine.executeRaw<{- slug: string; title: string | null; compiled_truth: string | null; updated_at: string | Date; seat: string | null;+ id: number | string; slug: string; title: string | null; compiled_truth: string | null; updated_at: string | Date; seat: string | null; trust_tier: string | null;}>(- `SELECT slug, title, compiled_truth, updated_at, frontmatter->>'seat' AS seat+ `SELECT id, slug, title, compiled_truth, updated_at, frontmatter->>'seat' AS seat, trust_tierFROM pagesWHERE slug LIKE $2AND source_id = $3 AND deleted_at IS NULL AND COALESCE(frontmatter->>'visibility','') <> 'private'@@ -596,6 +623,7 @@ async function gatherReflections(// reflection containing emoji cannot abort the entire patterns phase.excerpt: truncateUtf8(r.compiled_truth ?? '', 600),seat: r.seat ?? null,+ taint: { table: 'pages', id: Number(r.id), tier: storedTrustTier(r.trust_tier) },}));}@@ -649,10 +677,11 @@ When done, briefly list the pattern slugs you wrote/updated in your final messag* publications all landed, and the number of pages whose publication is held for a later cycle.*/async function stampPatternOutputs(engine: BrainEngine, maintenance: MaintenanceAuthority | null, written: Array<{ slug: string; source_id: string }>,- reflections: ReflectionRef[], config: { outputSlugPrefix: string; sourceSlugPrefix: string }, sourceId: string, cycleDate: string, signal?: AbortSignal) {+ reflections: ReflectionRef[], derivation: Derivation & { declaration: DerivationDeclaration }, config: { outputSlugPrefix: string; sourceSlugPrefix: string },+ sourceId: string, cycleDate: string, signal?: AbortSignal) {const heldSlugs = new Set<string>();- const quoteVerify = await groundPatternPages(engine, maintenance, written, reflections, config.outputSlugPrefix, sourceId, cycleDate, signal, heldSlugs);- await stampProvenance(engine, maintenance, written.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), signal, heldSlugs);+ const quoteVerify = await groundPatternPages(engine, maintenance, written, reflections, config.outputSlugPrefix, sourceId, cycleDate, signal, heldSlugs, derivation.declaration);+ await stampProvenance(engine, maintenance, written.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), signal, heldSlugs, derivation);// Holds are recorded for this cycle's source only, so a ref in any other source is never excused from verification.const finalized = written.filter(ref => ref.source_id !== sourceId || !heldSlugs.has(ref.slug));return { quoteVerify, finalized, held: heldSlugs.size };@@ -660,15 +689,15 @@ async function stampPatternOutputs(engine: BrainEngine, maintenance: Maintenanceasync function stampProvenance(engine: BrainEngine, maintenance: MaintenanceAuthority | null,refs: Array<{ slug: string; source_id: string }>, cycleDate: string, sourceSlugPrefix: string, seat: string | undefined, signal: AbortSignal | undefined,- heldSlugs: Set<string>): Promise<void> {+ heldSlugs: Set<string>, derivation: Derivation & { declaration: DerivationDeclaration }): Promise<void> {const reason = `derived from reflections under ${sourceSlugPrefix}/; raw traces live on the cited reflection pages`;// A pattern earns a seat only while its reflections share one, so a pattern without one drops a seat an earlier run stamped.- if (!maintenance) return stampDreamProvenance(engine, refs.map(ref => ({ ...ref, raw_trace_exempt_reason: reason, seat: seat ?? null })), cycleDate, signal);+ if (!maintenance) return stampDreamProvenance(engine, refs.map(ref => ({ ...ref, raw_trace_exempt_reason: reason, seat: seat ?? null, derivation })), cycleDate, signal);for (const ref of refs) {throwIfAborted(signal, '[dream] patterns provenance');// A page whose grounding publish is held must not be stamped over the pending revision.if (heldSlugs.has(ref.slug)) continue;- if (await publishOrHold(() => stampMaintenancePage(engine, maintenance, ref.slug, cycleDate, undefined, reason, seat ?? null))) heldSlugs.add(ref.slug);+ if (await publishOrHold(() => stampMaintenancePage(engine, maintenance, ref.slug, cycleDate, undefined, reason, seat ?? null, derivation.declaration))) heldSlugs.add(ref.slug);}}@@ -683,9 +712,11 @@ async function stampProvenance(engine: BrainEngine, maintenance: MaintenanceAuth* dream.quote_verify (default on). Returns null when disabled. With `heldSlugs`* a managed publish that is pending or contended (publicationHold) is recorded* there and the loop moves on; without it every publish error propagates.+ * `derivation` (#5575) is the pass's taint declaration; a managed publish of a page this run wrote carries it.*/export async function groundPatternPages(engine: BrainEngine, maintenance: MaintenanceAuthority | null, refs: Array<{ slug: string; source_id: string }>,- reflections: ReflectionRef[], outputSlugPrefix: string, sourceId: string, cycleDate: string, signal?: AbortSignal, heldSlugs?: Set<string>):+ reflections: ReflectionRef[], outputSlugPrefix: string, sourceId: string, cycleDate: string, signal?: AbortSignal, heldSlugs?: Set<string>,+ derivation?: DerivationDeclaration):Promise<{ pages: number; quarantined: number; repaired: number } | null> {const { dreamQuoteVerifyEnabled, groundSource, verifyBody } = await import('./synthesize-verify.ts');if (!await dreamQuoteVerifyEnabled(engine)) return null;@@ -719,7 +750,8 @@ export async function groundPatternPages(engine: BrainEngine, maintenance: Maintconst content = serializePageToMarkdown(page, snapshot.tags);if (maintenance) {const { publishMaintenancePage } = await import('../persistence/prepared-maintenance.ts');- const publish = () => publishMaintenancePage(engine, maintenance, slug, content, { expectedRevision: snapshot.revision });+ const publish = () => publishMaintenancePage(engine, maintenance, slug, content, { expectedRevision: snapshot.revision,+ ...(derivation && refs.some(r => r.slug === slug) ? { derivation } : {}) });if (!heldSlugs) await publish();else if (await publishOrHold(publish)) heldSlugs.add(slug);} else {@@ -819,6 +851,25 @@ function renderPageToMarkdown(page: Page, tags: string[]): string {// ── Status helpers ───────────────────────────────────────────────────+/**+ * #5575: the owner pass is the phase result; the external pass (null when+ * its reflections were below min_evidence) rides in `details.external_pass`+ * and its pages count toward `patterns_written`. An owner pass skipped for+ * lack of owner evidence takes the external pass's status; a failed or+ * warned external pass turns an ok owner pass into a warning.+ */+function mergeExternalPass(owner: PhaseResult, external: PhaseResult | null, externalReflections: number): PhaseResult {+ const details = { ...owner.details, reflections_external: externalReflections,+ patterns_written: Number(owner.details.patterns_written ?? 0) + Number(external?.details.patterns_written ?? 0),+ ...(external ? { external_pass: { status: external.status, summary: external.summary, details: external.details,+ ...(external.error ? { error: external.error } : {}) } } : {}) };+ if (!external) return { ...owner, details };+ const summary = `${owner.summary}; external reflections pass: ${external.summary}`;+ if (owner.status === 'skipped') return { ...external, summary, details };+ const degraded = owner.status === 'ok' && (external.status === 'fail' || external.status === 'warn');+ return { ...owner, summary, details, ...(degraded ? { status: 'warn' as const } : {}) };+}+function ok(summary: string, details: Record<string, unknown> = {}): PhaseResult {return { phase: 'patterns', status: 'ok', duration_ms: 0, summary, details };}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 8ec1a251f1..2ccd8ec6e5 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -168,8 +168,9 @@ export async function submitDatabaseMaintenanceIntent(engine: BrainEngine, authoreturn submitMaintenance(engine, authority, slug, intent, requestId, false);}+/** `derivation` (#5575 I2): the deriver's taint declaration, stamped onto the output page. */export async function stampMaintenancePage(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,- cycleDate: string, rawSource?: string, rawTraceExemptReason?: string, seat?: string | null): Promise<void> {+ cycleDate: string, rawSource?: string, rawTraceExemptReason?: string, seat?: string | null, derivation?: DerivationDeclaration): Promise<void> {const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId });if (!snapshot) throw opError('page_not_found', 'A maintenance output page disappeared.',`Output page ${slug} in '${authority.writer.sourceId}' no longer exists, so it was not stamped. Confirm with the command in fix, then run maintenance again to regenerate it if it is still wanted.`,@@ -180,7 +181,8 @@ export async function stampMaintenancePage(engine: BrainEngine, authority: Maintdream_cycle_date: firstDate, dream_created_cycle_date: firstDate, ...(rawSource ? { raw_source: rawSource } : {}),...(rawTraceExemptReason ? { raw_trace_exempt: true, raw_trace_exempt_reason: rawTraceExemptReason } : {}),...(seat ? { seat } : {}) } };- await publishMaintenancePage(engine, authority, slug, serializePageToMarkdown(page, snapshot.tags), { expectedRevision: snapshot.revision });+ await publishMaintenancePage(engine, authority, slug, serializePageToMarkdown(page, snapshot.tags), { expectedRevision: snapshot.revision,+ ...(derivation ? { derivation } : {}) });}export async function verifyMaintenanceOutputs(engine: BrainEngine, authority: MaintenanceAuthority,