Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): pattern pages carry a raw-trace exemption (#5884)
garrytanb2e9751d2241
diff --git a/src/core/cycle/dream-provenance.ts b/src/core/cycle/dream-provenance.tsindex d33278b798..4c08926254 100644--- a/src/core/cycle/dream-provenance.ts+++ b/src/core/cycle/dream-provenance.ts@@ -9,13 +9,13 @@ import { throwIfAborted } from '../abort-check.ts';*/export async function stampDreamProvenance(engine: BrainEngine,- refs: Array<{ slug: string; source_id: string; raw_source?: string; first_write_at?: Date }>,+ refs: Array<{ slug: string; source_id: string; raw_source?: string; raw_trace_exempt_reason?: string; first_write_at?: Date }>,cycleDate: string,signal?: AbortSignal,): Promise<void> {if (refs.length === 0) return;const { executeRawJsonb } = await import('../sql-query.ts');- for (const { slug, source_id, raw_source, first_write_at } of refs) {+ for (const { slug, source_id, raw_source, raw_trace_exempt_reason, first_write_at } of refs) {// #4077: per-row abort check — the per-row try below is only for stamp// failures and must not swallow the cancellation unwind.throwIfAborted(signal, '[dream] synthesize provenance');@@ -45,6 +45,7 @@ export async function stampDreamProvenance([{dream_generated: true,...(raw_source ? { raw_source } : {}),+ ...(raw_trace_exempt_reason ? { raw_trace_exempt: true, raw_trace_exempt_reason } : {}),}],);} catch (e) {diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex 74875d4b35..eb524f7edb 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -361,7 +361,7 @@ export async function runPhasePatterns(throwIfAborted(opts.signal, '[dream] patterns output');const writtenRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId);- await stampPatternOutputs(engine, maintenance, writtenRefs.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, opts.signal);+ await stampPatternOutputs(engine, maintenance, writtenRefs.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, opts.signal);const reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, writtenRefs): await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);@@ -615,13 +615,16 @@ When done, briefly list the pattern slugs you wrote/updated in your final messag* #5733: pages under the patterns output prefix are dream output and carry the* dream_generated identity stamp every dream_generated consumer reads, through* the managed maintenance write on a managed brain, before the reverse-write.+ * #5884: a pattern is derived from reflection pages, not raw material, so it is+ * stamped raw-trace exempt (doctor raw_provenance) on every run that writes it.*/async function stampPatternOutputs(engine: BrainEngine, maintenance: MaintenanceAuthority | null,- refs: Array<{ slug: string; source_id: string }>, cycleDate: string, signal?: AbortSignal): Promise<void> {- if (!maintenance) return stampDreamProvenance(engine, refs, cycleDate, signal);+ refs: Array<{ slug: string; source_id: string }>, cycleDate: string, sourceSlugPrefix: string, signal?: AbortSignal): Promise<void> {+ const reason = `derived from reflections under ${sourceSlugPrefix}/; raw traces live on the cited reflection pages`;+ if (!maintenance) return stampDreamProvenance(engine, refs.map(ref => ({ ...ref, raw_trace_exempt_reason: reason })), cycleDate, signal);for (const ref of refs) {throwIfAborted(signal, '[dream] patterns provenance');- await stampMaintenancePage(engine, maintenance, ref.slug, cycleDate);+ await stampMaintenancePage(engine, maintenance, ref.slug, cycleDate, undefined, reason);}}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 2947d62d08..71f0f0765b 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -133,12 +133,13 @@ export async function submitDatabaseMaintenanceIntent(engine: BrainEngine, autho}export async function stampMaintenancePage(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,- cycleDate: string, rawSource?: string): Promise<void> {+ cycleDate: string, rawSource?: string, rawTraceExemptReason?: string): Promise<void> {const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId });if (!snapshot) throw new OperationError('page_not_found', 'A maintenance output page disappeared.');const firstDate = snapshot.page.frontmatter.dream_created_cycle_date || snapshot.page.frontmatter.dream_cycle_date || cycleDate;const page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,- dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, ...(rawSource ? { raw_source: rawSource } : {}) } };+ dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, ...(rawSource ? { raw_source: rawSource } : {}),+ ...(rawTraceExemptReason ? { raw_trace_exempt: true, raw_trace_exempt_reason: rawTraceExemptReason } : {}) } };await publishMaintenancePage(engine, authority, slug, serializePageToMarkdown(page, snapshot.tags), { expectedRevision: snapshot.revision });}diff --git a/test/managed-maintenance.test.ts b/test/managed-maintenance.test.tsindex c6870e92a6..bbb1850ddb 100644--- a/test/managed-maintenance.test.ts+++ b/test/managed-maintenance.test.ts@@ -26,6 +26,7 @@ import { withEnv } from './helpers/with-env.ts';import { withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';import type { WriteRequest } from '../src/core/persistence/model.ts';import { testBackends } from './helpers/test-backends.ts';+import { rawProvenanceCheck } from '../src/commands/doctor/checks/core-health.ts';const backends = testBackends();const engines: BrainEngine[] = [];@@ -519,6 +520,41 @@ for (const managed of [true, false]) test(`#5733: ${managed ? 'managed' : 'unman});}, 90_000);+for (const managed of [true, false]) test(`#5884: ${managed ? 'managed' : 'unmanaged'} patterns output passes raw_provenance${managed ? ' on every run that rewrites it' : ''}`, async () => {+ await fixture(async (engine, sourceId, root) => {+ for (let i = 0; i < 3; i++) await seed(engine, sourceId, `wiki/personal/reflections/example-${i}`);+ await engine.setConfig('dream.patterns.enabled', 'true');+ await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');+ await engine.setConfig('agent.use_gateway_loop', 'true');+ if (managed) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ let calls = 0;+ __setChatTransportForTests(async opts => {+ calls++;+ const write = calls % 2 === 1;+ return { text: write ? '' : 'Saved the pattern.', blocks: write ? [{ type: 'tool-call', toolCallId: `pattern-write-${calls}`, toolName: 'brain_put_page', input: {+ slug: 'wiki/personal/patterns/traced', content: `---\ntitle: Traced pattern\ntype: note\n---\nA recurring theme, run ${calls}, in [[wiki/personal/reflections/example-0]].`,+ } }] : [{ type: 'text', text: 'Saved the pattern.' }], stopReason: write ? 'tool_calls' : 'end',+ usage: { input_tokens: 100, output_tokens: 100, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: opts.model!, providerId: 'anthropic' };+ });+ try {+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-maintenance' }, async () => {+ for (const cycleDate of managed ? ['2026-02-03', '2026-02-04'] : ['2026-02-03']) {+ const result = await runPhasePatterns(engine, { brainDir: root, sourceId, dryRun: false, once: true, cycleDate });+ expect(result.details.patterns_written).toBe(1);+ const page = (await engine.readPageSnapshot('wiki/personal/patterns/traced', { sourceId }))!;+ expect(page.page.compiled_truth).toContain(`run ${calls - 1}`);+ expect(page.page.frontmatter).toMatchObject({ dream_generated: true, raw_trace_exempt: true,+ raw_trace_exempt_reason: 'derived from reflections under wiki/personal/reflections/; raw traces live on the cited reflection pages' });+ expect(await rawProvenanceCheck(engine)).toMatchObject({ name: 'raw_provenance', status: 'ok' });+ }+ expect(parseMarkdown(readFileSync(join(root, 'wiki/personal/patterns/traced.md'), 'utf8')).frontmatter)+ .toMatchObject({ raw_trace_exempt: true });+ });+ } finally { __setChatTransportForTests(null); }+ });+}, 90_000);+test('managed patterns scopes evidence and publishes through the real admitted subagent operation', async () => {await fixture(async (engine, sourceId, root) => {for (let i = 0; i < 3; i++) await seed(engine, sourceId, `wiki/personal/reflections/example-${i}`);