Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(trust): synthesis outputs and the dream summary publish at their transcript's derived tier (#5575 L1a-taint, ENG-3, ENG-7)

garrytan8854c2d6a5dd
diff --git a/src/core/cycle/dream-provenance.ts b/src/core/cycle/dream-provenance.ts
index 7b2601bded..5e15c6955c 100644
--- a/src/core/cycle/dream-provenance.ts
+++ b/src/core/cycle/dream-provenance.ts
@@ -1,6 +1,8 @@
import type { BrainEngine } from '../engine.ts';
import { throwIfAborted } from '../abort-check.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { derivedMaintenanceTransaction } from '../trust/taint.ts';
+import type { TaintInput, WriteTrust } from '../trust/tier.ts';
/**
* Dream-provenance DB stamp (#2569): marks pages a dream child wrote with
@@ -9,21 +11,27 @@ import { maintenanceTransaction } from '../persistence/attribution.ts';
* is not stamped. `seat` (#4618) credits the capturing agent seat; `seat: null`
* removes a seat the page no longer earns (a pattern whose reflections no
* longer share one).
+ *
+ * #5575 I2: a ref carrying `derivation` (the tier of everything in the
+ * child's prompt) is stamped at that tier, and the page the child wrote is
+ * lowered to it and gets its input edges even when it is not dream-owned:
+ * the child wrote it from that prompt either way.
*/
export async function stampDreamProvenance(
engine: BrainEngine,
- refs: Array<{ slug: string; source_id: string; raw_source?: string; seat?: string | null; raw_trace_exempt_reason?: string; first_write_at?: Date }>,
+ refs: Array<{ slug: string; source_id: string; raw_source?: string; seat?: string | null; raw_trace_exempt_reason?: string; first_write_at?: Date;
+ derivation?: { trust: WriteTrust; inputs: readonly TaintInput[] } }>,
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, seat, raw_trace_exempt_reason, first_write_at } of refs) {
+ for (const { slug, source_id, raw_source, seat, raw_trace_exempt_reason, first_write_at, derivation } 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');
try {
- await maintenanceTransaction(engine, tx => executeRawJsonb(
+ const stamp = (tx: BrainEngine) => executeRawJsonb(
tx,
`UPDATE pages
SET frontmatter = (COALESCE(frontmatter, '{}'::jsonb) - CASE WHEN $5::boolean THEN 'seat' ELSE '' END)
@@ -51,7 +59,13 @@ export async function stampDreamProvenance(
...(seat ? { seat } : {}),
...(raw_trace_exempt_reason ? { raw_trace_exempt: true, raw_trace_exempt_reason } : {}),
}],
- ));
+ );
+ if (!derivation) await maintenanceTransaction(engine, stamp);
+ else await derivedMaintenanceTransaction(engine, derivation, async tx => {
+ await stamp(tx);
+ const pages = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL', [slug, source_id]);
+ return { result: undefined, rows: pages.map(p => ({ table: 'pages' as const, id: Number(p.id), sourceId: source_id })) };
+ });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
process.stderr.write(`[dream] provenance stamp ${slug}@${source_id} failed: ${msg}\n`);
diff --git a/src/core/cycle/dream-taint.ts b/src/core/cycle/dream-taint.ts
new file mode 100644
index 0000000000..628d78e4f7
--- /dev/null
+++ b/src/core/cycle/dream-taint.ts
@@ -0,0 +1,66 @@
+/**
+ * #5575 I2 taint for the dream derivers (ENG-3): the tier of a synthesis or
+ * patterns output is the least trusted input placed in the child's prompt,
+ * capped at agent_written.
+ *
+ * - Synthesis: each child reads one transcript. A conversation page
+ * (`gbrain-page://<source>/<slug>`) is that page's stored tier; a corpus
+ * file is the cap its frontmatter names, else agent_written (the user's own
+ * 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.
+ */
+import { resolve, sep } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { parseMarkdown } from '../markdown.ts';
+import { declareDerivation, deriveTrust, derivedMaintenanceTransaction, derivedWriteTrust, frontmatterTaint, type DerivationDeclaration } from '../trust/taint.ts';
+import type { TaintInput, TrustTier, WriteTrust } from '../trust/tier.ts';
+import { CONVERSATION_PAGE_URI_PREFIX } from './transcript-discovery.ts';
+
+export interface Derivation { trust: WriteTrust; inputs: TaintInput[] }
+
+/** The derivation of every page a synthesis child wrote from one transcript. */
+export async function transcriptDerivation(engine: Pick<BrainEngine, 'executeRaw'>, transcript: { filePath: string; content?: string } | undefined,
+ meetingTranscriptsDir?: string | null): Promise<Derivation> {
+ const channel = 'derive:synthesize';
+ if (!transcript) return { trust: derivedWriteTrust({ channel, inputs: [], lowerTo: ['unknown'] }), inputs: [] };
+ const sourceUri = transcript.filePath;
+ if (sourceUri.startsWith(CONVERSATION_PAGE_URI_PREFIX)) {
+ const rest = sourceUri.slice(CONVERSATION_PAGE_URI_PREFIX.length);
+ const cut = rest.indexOf('/');
+ return deriveTrust(engine, [{ table: 'pages', sourceId: rest.slice(0, cut), slug: rest.slice(cut + 1) }], { channel, sourceUri });
+ }
+ const meeting = !!meetingTranscriptsDir && resolve(sourceUri).startsWith(resolve(meetingTranscriptsDir) + sep);
+ let cap: TrustTier = meeting ? 'external_untrusted' : 'agent_written';
+ if (!meeting && transcript.content) {
+ try { cap = frontmatterTaint(parseMarkdown(transcript.content).frontmatter) ?? cap; } catch { cap = 'unknown'; }
+ }
+ return { trust: derivedWriteTrust({ channel, inputs: [], lowerTo: [cap], sourceUri }), inputs: [] };
+}
+
+/** Synthesis output refs with the derivation of the transcript each was written from (the unmanaged provenance stamp). */
+export async function withTranscriptTaint<R extends { raw_source?: string }>(engine: BrainEngine, refs: R[],
+ transcripts: Array<{ filePath: string; content: string }>, meetingTranscriptsDir?: string | null): Promise<Array<R & { derivation: Derivation }>> {
+ const byPath = new Map(transcripts.map(t => [t.filePath, t]));
+ const out: Array<R & { derivation: Derivation }> = [];
+ for (const ref of refs) {
+ const transcript = ref.raw_source ? byPath.get(ref.raw_source) ?? { filePath: ref.raw_source } : undefined;
+ out.push({ ...ref, derivation: await transcriptDerivation(engine, transcript, meetingTranscriptsDir) });
+ }
+ return out;
+}
+
+/** The dream summary page's derivation: the output pages it indexes. */
+export async function summaryDerivation(engine: BrainEngine, sourceId: string, slugs: string[]): Promise<Derivation & { declaration: DerivationDeclaration }> {
+ const { trust, inputs } = await deriveTrust(engine, slugs.map(slug => ({ table: 'pages' as const, sourceId, slug })), { channel: 'derive:synthesize' });
+ return { trust, inputs, declaration: declareDerivation(trust, inputs) };
+}
+
+/** An unmanaged derived page write (the dream summary): putPage at the derivation's tier, lowered, with its input edges. */
+export async function putDerivedPage(engine: BrainEngine, derivation: Derivation, slug: string,
+ page: Parameters<BrainEngine['putPage']>[1], opts: { sourceId: string }): Promise<void> {
+ await derivedMaintenanceTransaction(engine, derivation, async tx => {
+ const written = await tx.putPage(slug, page, opts);
+ return { result: undefined, rows: [{ table: 'pages' as const, id: Number(written.id), sourceId: opts.sourceId }] };
+ });
+}
diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.ts
index 1dc3153719..925835c599 100644
--- a/src/core/cycle/synthesize-postprocess.ts
+++ b/src/core/cycle/synthesize-postprocess.ts
@@ -13,6 +13,8 @@ import { publishMaintenancePage, type MaintenanceAuthority } from '../persistenc
import { writeResponse } from '../persistence/service.ts';
import type { PhaseResult } from '../cycle.ts';
import type { DiscoveredTranscript } from './transcript-discovery.ts';
+import { transcriptDerivation } from './dream-taint.ts';
+import { declareDerivation, readDerivationDeclaration } from '../trust/taint.ts';
import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPrior, verifyDreamPage, type GroundedSource, type GroundingPass } from './synthesize-verify.ts';
interface OutputRef { slug: string; source_id: string; raw_source?: string; seat?: string; first_write_at?: Date; }
@@ -27,7 +29,9 @@ export async function postprocessManagedSynthesis(
childIds: number[],
jobRawSource: Map<number, string>,
transcripts: DiscoveredTranscript[],
- opts: { cycleDate: string; quoteVerify: boolean; sinceByTranscript: Map<string, Date>; signal?: AbortSignal; grounding?: GroundingPass },
+ opts: { cycleDate: string; quoteVerify: boolean; sinceByTranscript: Map<string, Date>; signal?: AbortSignal; grounding?: GroundingPass;
+ /** #5575 I2: files under it are third-party speech; their outputs publish external_untrusted. */
+ meetingTranscriptsDir?: string | null },
) {
const stats = emptyQuoteVerifyStats();
const writtenRefs: OutputRef[] = [];
@@ -106,8 +110,12 @@ export async function postprocessManagedSynthesis(
content = serializePageToMarkdown(page, snapshot.tags);
}
throwIfAborted(opts.signal, '[dream] synthesis postprocessing');
+ // #5575 I2: the page publishes at its transcript's tier (lowered even when the content is unchanged), with its input edges.
+ // A retained request replays the declaration it was admitted with (none for one admitted before tiers).
+ const derivation = prior ? readDerivationDeclaration(prior.intent?.derivation) ?? undefined
+ : await transcriptDerivation(engine, transcript, opts.meetingTranscriptsDir).then(d => declareDerivation(d.trust, d.inputs));
try {
- await publishMaintenancePage(engine, authority, ref.slug, content, { requestId, expectedRevision: revision });
+ await publishMaintenancePage(engine, authority, ref.slug, content, { requestId, expectedRevision: revision, derivation });
} catch (error) {
deferPublishOrThrow(error, `${ref.slug} (request ${requestId})`);
pending++;
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index a2299743d2..015e96b61e 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -76,7 +76,7 @@ import { buildManifestContext, buildLinkManifest, type ManifestContext } from '.
import { resolveCycleDate, utcDate } from './cycle-date.ts';
import { throwIfAborted } from '../abort-check.ts';
import { stampDreamProvenance } from './dream-provenance.ts';
-import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { putDerivedPage, summaryDerivation, withTranscriptTaint } from './dream-taint.ts';
import { findLegacyCompletion, findSynthV2Completion, partitionCompletedSynthesis } from './synthesize-completion.ts';
// Re-exports: the drain was peeled to inline-drain.ts (dream-wave C7), the
@@ -1153,7 +1153,7 @@ async function runPhaseSynthesizeInner(
const grounding = config.quoteVerify ? await resolveGroundingDecide(engine) : undefined;
if (maintenance) {
const processed = await postprocessManagedSynthesis(engine, maintenance, writtenRefs, childIds, jobRawSource,
- worthProcessing, { cycleDate: summaryDate, quoteVerify: config.quoteVerify, sinceByTranscript, signal: opts.signal, grounding });
+ worthProcessing, { cycleDate: summaryDate, quoteVerify: config.quoteVerify, sinceByTranscript, signal: opts.signal, grounding, meetingTranscriptsDir: config.meetingTranscriptsDir });
writtenRefs = processed.writtenRefs;
finalizedRefs = processed.finalizedRefs;
publishPending = processed.pending;
@@ -1169,7 +1169,7 @@ async function runPhaseSynthesizeInner(
}
}
- if (!maintenance) await stampDreamProvenance(engine, writtenRefs, summaryDate, opts.signal);
+ if (!maintenance) await stampDreamProvenance(engine, await withTranscriptTaint(engine, writtenRefs, worthProcessing, config.meetingTranscriptsDir), summaryDate, opts.signal);
// Dual-write: reverse-render each DB row → markdown file.
const reverseWriteCount = maintenance ? (maintenance.binding ? writtenRefs.length : 0)
@@ -3121,15 +3121,15 @@ async function writeSummaryPage(
{ type: 'note' as string, title: `Dream cycle ${summaryDate}`, tags: ['dream-cycle'] },
);
- const { parseMarkdown } = await import('../markdown.ts');
+ const [{ parseMarkdown }, derivation] = await Promise.all([import('../markdown.ts'), summaryDerivation(engine, sourceId, writtenSlugs)]);
const parsed = parseMarkdown(fullMarkdown);
- if (!maintenance) await maintenanceTransaction(engine, tx => tx.putPage(summarySlug, {
+ if (!maintenance) await putDerivedPage(engine, derivation, summarySlug, {
type: parsed.type,
title: parsed.title,
compiled_truth: parsed.compiled_truth,
timeline: parsed.timeline,
frontmatter: parsed.frontmatter,
- }, { sourceId }));
+ }, { sourceId });
const fileWriteRaw = (await engine.getConfig('dream.synthesize.summary_file_write'))?.trim().toLowerCase();
const fileWriteEnabled = !(fileWriteRaw === 'false' || fileWriteRaw === '0' || fileWriteRaw === 'off');
@@ -3146,7 +3146,7 @@ async function writeSummaryPage(
if (!fileWriteEnabled || dbOnlyTier) {
if (maintenance) {
const snapshot = await engine.readPageSnapshot(summarySlug, { sourceId, includeDeleted: true });
- await publishMaintenancePage(engine, maintenance, summarySlug, fullMarkdown, { expectedRevision: snapshot?.revision ?? null, file: false });
+ await publishMaintenancePage(engine, maintenance, summarySlug, fullMarkdown, { expectedRevision: snapshot?.revision ?? null, file: false, derivation: derivation.declaration });
}
const why = !fileWriteEnabled ? 'dream.synthesize.summary_file_write=off' : 'db_only storage tier';
process.stderr.write(`[dream] summary file-write skipped (${why}): ${summarySlug} lives in the DB only\n`);
@@ -3155,7 +3155,7 @@ async function writeSummaryPage(
if (maintenance) {
const snapshot = await engine.readPageSnapshot(summarySlug, { sourceId, includeDeleted: true });
- await publishMaintenancePage(engine, maintenance, summarySlug, fullMarkdown, { expectedRevision: snapshot?.revision ?? null });
+ await publishMaintenancePage(engine, maintenance, summarySlug, fullMarkdown, { expectedRevision: snapshot?.revision ?? null, derivation: derivation.declaration });
return;
}
try {