Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(trust): keep deriver functions under their size baselines (gated writer helpers)
garrytane8d45e9b8a05
diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.tsindex ed694f9299..35340377aa 100644--- a/src/core/cycle/concept-publication.ts+++ b/src/core/cycle/concept-publication.ts@@ -20,11 +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';+import { declareDerivation, deriveTrust, lowerDerivedPage } from '../trust/taint.ts';-/** #5575 I2: the member atoms the concept narrative was synthesized from, with their tiers. */-export interface ConceptDerivation { trust: WriteTrust; inputs: readonly TaintInput[] }+/** #5575 I2: the narrative carries the tier of the member atoms its prompt was built from (capped at agent_written). */+const conceptDerivation = (engine: BrainEngine, sourceId: string, members: readonly string[]) =>+ deriveTrust(engine, [...new Set(members)].map(slug => ({ table: 'pages' as const, sourceId, slug })), { channel: 'derive:concepts' });/** Error code for a concept held because republication could lose canonical material. */export const CONCEPT_PRESERVATION_CODE = 'concept_preservation_hold';@@ -45,7 +45,8 @@ function conceptHoldError(message: string): Error { return Object.assign(new Err*/export async function publishManagedConcept(engine: BrainEngine, authority: MaintenanceAuthority,slug: string, synthesized: Record<string, unknown>, narrative: string, expectedRevision: string | null, brainDir?: string,- derivation?: ConceptDerivation): Promise<string | null> {+ members?: readonly string[]): Promise<string | null> {+ const derivation = members ? await conceptDerivation(engine, authority.writer.sourceId, members) : 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.@@ -190,7 +191,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>; derivation?: ConceptDerivation }): Promise<string> {+ opts: { writeThrough: boolean; importPage: (markdown: string) => Promise<unknown>; members?: readonly string[] }): 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 {@@ -207,7 +208,7 @@ export async function publishClassicConcept(engine: BrainEngine, slug: string, s: 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 (opts.members) await lowerDerivedPage(engine, await conceptDerivation(engine, sourceId, opts.members), sourceId, slug);if (file || opts.writeThrough) await writeDerivedPageThrough(engine, slug, sourceId);return narrative;} finally {diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 42bd290f75..837616b14d 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -50,6 +50,7 @@ import { managedDerivedFactsPreflight, withDerivedFactsWrite } from '../persisteimport { withWriteTrust } from '../persistence/context.ts';import { deriveTrust, recordTaintEdges } from '../trust/taint.ts';import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';+import type { WriteGateConfig } from '../write-gate.ts';import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';import type { WriteTrust } from '../trust/tier.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';@@ -251,6 +252,30 @@ async function refuseDestructiveReconcileOnStaleCache(return true;}+/**+ * #5575 I2/B3: new fence rows restate the page (no model), so they take its+ * tier capped at operator_curated (the caller's write scope) and pass the+ * write gate at it (an owner page never runs it). Held rows go to+ * write_gate_holds, rejected rows are skipped; inserted rows get input edges+ * and flag receipts.+ */+type ReconcileRow = Parameters<BrainEngine['insertFacts']>[0][number];+async function insertReconciledFacts<F extends ReconcileRow>(+ tx: BrainEngine, sourceId: string, slug: string, inserts: F[], derivation: Awaited<ReturnType<typeof deriveTrust>>, cfg: WriteGateConfig, tally: GateTally,+): Promise<{ inserted: { inserted: number; ids: number[] }; allowed: F[] }> {+ const decisions = inserts.map(f => decideFactWrite(f, { sourceId, slug, payload: { ...(f as ReconcileRow), embedding: null }, input: derivedGateInput(derivation.trust), cfg }));+ for (const d of decisions) if (d.action !== 'insert') await applyGateDecision(tx, d, { table: 'facts', sourceId }, async () => null, tally);+ const allowed = inserts.filter((_, i) => decisions[i].action === 'insert');+ const flags = decisions.filter(d => d.action === 'insert');+ const inserted = allowed.length === 0 ? { inserted: 0, ids: [] as number[] }+ : await tx.insertFacts(allowed.map(f => ({ ...f, superseded_by_row: undefined })), { source_id: sourceId }); // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB+ for (const [i, id] of inserted.ids.entries()) {+ await recordTaintEdges(tx, { table: 'facts', id, sourceId }, derivation.inputs);+ if (inserted.ids.length === allowed.length && await recordFlaggedRow(tx, flags[i], { table: 'facts', id, sourceId }) !== null) tally.flagged++;+ }+ return { inserted, allowed };+}+/*** Run one page's destructive reconcile under its page lock (5s, matching the* fence writers in fence-write.ts / forget.ts). A lock still held past the@@ -822,7 +847,6 @@ export async function runExtractFacts(result.warnings.push(`${slug}: destructive fact reconciliation deferred; existing vectors preserved until embedding succeeds`);}- // #5575 I2: the fence rows restate the page (no model): they take its tier, capped at operator_curated.const derivation = await deriveTrust(engine, [{ table: 'pages', id: page.id }], { channel: 'derive:facts_fence', projection: true });const apply = async () => {try {@@ -856,21 +880,7 @@ export async function runExtractFacts(f.claim_metric ?? null, f.claim_value ?? null, f.claim_unit ?? null, f.claim_period ?? null],);}- // #5575 B3: each new fence row passes the write gate at the page's tier (an owner page never runs it).- const decisions = inserts.map(f => decideFactWrite(f, { sourceId, slug, payload: { ...f, embedding: null }, input: derivedGateInput(derivation.trust), cfg: gateCfg }));- for (const d of decisions) if (d.action !== 'insert') await applyGateDecision(tx, d, { table: 'facts', sourceId }, async () => null, gateTally);- const allowed = inserts.filter((_, i) => decisions[i].action === 'insert');- const flags = decisions.filter(d => d.action === 'insert');- const inserted = allowed.length === 0- ? { inserted: 0, ids: [] as number[] }- : await tx.insertFacts( // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB- allowed.map(f => ({ ...f, superseded_by_row: undefined })),- { source_id: sourceId },- );- for (const [i, id] of inserted.ids.entries()) {- await recordTaintEdges(tx, { table: 'facts', id, sourceId }, derivation.inputs);- if (inserted.ids.length === allowed.length && await recordFlaggedRow(tx, flags[i], { table: 'facts', id, sourceId }) !== null) gateTally.flagged++;- }+ const { inserted, allowed } = await insertReconciledFacts(tx, sourceId, slug, inserts, derivation, gateCfg, gateTally);const insertedRows = new Set(allowed.map(f => f.row_num));const linked = await syncSupersession(tx, sourceId, slug, extracted, chain, insertedRows);opts.signal?.throwIfAborted();diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex c5f07db5dd..bd6caa15bf 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -40,7 +40,6 @@ 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';@@ -493,18 +492,15 @@ 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, derivation);+ conceptRevision, opts.brainDir, group.atomSlugs);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, derivation, importPage: (markdown) => importFromContent(engine, conceptSlug, markdown, {+ baseline, { writeThrough: conceptFiles !== null, members: group.atomSlugs, importPage: (markdown) => importFromContent(engine, conceptSlug, markdown, {noEmbed: !isAvailable('embedding'), sourceId: opts.sourceId, preserveGateMarkers: true,}) });};diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex aad015e349..37f05b9b75 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -166,6 +166,8 @@ export type FactsBackstopResult =skipped?: 'extraction_disabled' | 'extraction_unavailable' | `eligibility_failed:${string}`;/** Set when the LLM extraction step failed non-transport-fatally (see runPipelineWithBody). */skipped_reason?: import('./extract.ts').ExtractFailureReason;+ /** #5575 B3: rows the write gate flagged, held or rejected (unmanaged path). */+ write_gate?: GateTally;};/** One pipeline run's input: the turn text plus its page provenance and observation date. */@@ -617,6 +619,42 @@ async function runPipelineWithBody(return runPipelineBodyInner(input, ctx, abortSignal);}+/**+ * #5575 B3: the unmanaged pipeline's gated writers. Every row passes the write+ * gate at the extraction's declared tier (ENG-18); the extractor rewrites+ * strict injection hits to [redacted], so such a row is also gated on the+ * source text. `counts` accumulates the run's insert counters.+ */+async function derivedFactWriter(ctx: FactsBackstopCtx, input: PipelineInput, derivation: Awaited<ReturnType<typeof factsDerivation>>,+ counts: { inserted: number; duplicate: number; superseded: number; fact_ids: number[] }) {+ const gateCfg = await derivedGateConfig(ctx.engine);+ const gateInput = derivedGateInput(derivation.trust, ctx.persistenceRequestId);+ const write_gate = emptyGateTally();+ const decideFact = (row: { fact: string; context?: string | null; source?: string | null }, slug: string | null, payload: Record<string, unknown>) =>+ decideFactWrite({ ...row, source_text: row.fact.includes('[redacted]') ? input.turnText : null },+ { sourceId: ctx.sourceId, slug, payload: { ...payload, embedding: null }, input: gateInput, cfg: gateCfg });+ /** A DB-only insert: one attributed transaction at the derived tier, gated, with input edges for a new row. */+ const insertDerivedFact = (newFact: NewFact) => maintenanceTransaction(ctx.engine, tx =>+ applyGateDecision(tx, decideFact(newFact, newFact.entity_slug ?? null, { ...newFact }), { table: 'facts', sourceId: ctx.sourceId }, async () => {+ const result = await tx.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: the facts backstop's DB-only fallbacks (unparented / thin-client facts, stub-guard or unresolvable targets, a declined fence lane)+ counts.fact_ids.push(result.id);+ if (result.status === 'inserted') counts.inserted += 1;+ else if ((result.status as FactInsertStatus) === 'duplicate') { counts.duplicate += 1; return null; }+ else counts.superseded += 1;+ await recordTaintEdges(tx, { table: 'facts', id: result.id, sourceId: ctx.sourceId }, derivation.inputs);+ return result.id;+ }, write_gate), derivation.trust);+ /** Gates one entity group before its fence write: held and rejected rows are recorded; the rest carry their decision. */+ const gateGroup = async <F extends { fact: string; context?: string | null; source?: string | null }>(facts: F[], slug: string) => {+ const decisions = facts.map(fact => decideFact(fact, slug, { ...fact }));+ if (decisions.some(d => d.action !== 'insert')) await maintenanceTransaction(ctx.engine, async tx => {+ for (const d of decisions) if (d.action !== 'insert') await applyGateDecision(tx, d, { table: 'facts', sourceId: ctx.sourceId }, async () => null, write_gate);+ });+ return { keep: decisions.map(d => d.action === 'insert'), keptFacts: facts.flatMap((fact, i) => decisions[i].action === 'insert' ? [{ ...fact, gate: decisions[i] }] : []) };+ };+ return { insertDerivedFact, gateGroup, write_gate };+}+/** The actual pipeline body — always runs inside a BudgetTracker scope (#4210). */async function runPipelineBodyInner(input: PipelineInput,@@ -706,29 +744,9 @@ async function runPipelineBodyInner(if (!managed) await assertAmbientCaptureAdmissible(ctx.engine, ctx.source);if (managed) return withCaptureDrops(dropped, facts.length || !dropped.length ? await publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug) : null);- let inserted = 0;- let duplicate = dropped.length;- let superseded = 0;- const fact_ids: number[] = [...dropped];- // #5575 B3: every row passes the write gate at the extraction's declared tier (ENG-18). The extractor- // rewrites strict injection hits to [redacted], so such a row is also gated on the source text.- const gateCfg = await derivedGateConfig(ctx.engine);- const gateInput = derivedGateInput(derivation.trust, ctx.persistenceRequestId);- const write_gate = emptyGateTally();- const decideFact = (row: { fact: string; context?: string | null; source?: string | null }, slug: string | null, payload: Record<string, unknown>) =>- decideFactWrite({ ...row, source_text: row.fact.includes('[redacted]') ? input.turnText : null },- { sourceId: ctx.sourceId, slug, payload: { ...payload, embedding: null }, input: gateInput, cfg: gateCfg });- // Every DB-only insert: one attributed transaction at the derived tier, gated, with input edges for a new row.- const insertDerivedFact = (newFact: NewFact) => maintenanceTransaction(ctx.engine, tx =>- applyGateDecision(tx, decideFact(newFact, newFact.entity_slug ?? null, { ...newFact }), { table: 'facts', sourceId: ctx.sourceId }, async () => {- const result = await tx.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: the facts backstop's DB-only fallbacks (unparented / thin-client facts, stub-guard or unresolvable targets, a declined fence lane)- fact_ids.push(result.id);- if (result.status === 'inserted') inserted += 1;- else if ((result.status as FactInsertStatus) === 'duplicate') { duplicate += 1; return null; }- else superseded += 1;- await recordTaintEdges(tx, { table: 'facts', id: result.id, sourceId: ctx.sourceId }, derivation.inputs);- return result.id;- }, write_gate), derivation.trust);+ const counts = { inserted: 0, duplicate: dropped.length, superseded: 0, fact_ids: [...dropped] };+ const writer = await derivedFactWriter(ctx, input, derivation, counts);+ const { insertDerivedFact, write_gate } = writer;// Cathedral 5: slugs whose fence-write actually inserted a fact this run.const fencedSlugs = new Set<string>();@@ -782,8 +800,8 @@ async function runPipelineBodyInner(}if (matchedExistingId !== null) {- duplicate += 1;- fact_ids.push(matchedExistingId);+ counts.duplicate += 1;+ counts.fact_ids.push(matchedExistingId);continue;}@@ -791,7 +809,7 @@ async function runPipelineBodyInner(}if (survived.length === 0) {- return { inserted, duplicate, superseded, fact_ids, entity_slugs: [], write_gate };+ return { ...counts, entity_slugs: [], write_gate };}// Phase 2: group survived facts by resolved entity_slug. Facts with@@ -866,7 +884,7 @@ async function runPipelineBodyInner(if (localPath === null) {// All went through legacy bucket; nothing left to fence — DB-only// inserts have no fence-written page, so entity_slugs stays empty.- return { inserted, duplicate, superseded, fact_ids, entity_slugs: [], write_gate };+ return { ...counts, entity_slugs: [], write_gate };}// Phase 5: fence-write per entity. writeFactsToFence handles the@@ -893,12 +911,8 @@ async function runPipelineBodyInner(sessionId: f.source_session ?? null,}));// #5575 B3: gate before the fence write; a held or rejected row reaches neither the fence nor a fallback below.- const decisions = inputFacts.map(fact => decideFact(fact, slug, { ...fact }));- if (decisions.some(d => d.action !== 'insert')) await maintenanceTransaction(ctx.engine, async tx => {- for (const d of decisions) if (d.action !== 'insert') await applyGateDecision(tx, d, { table: 'facts', sourceId: ctx.sourceId }, async () => null, write_gate);- });- const kept = group.filter((_, i) => decisions[i].action === 'insert');- const keptFacts = inputFacts.flatMap((fact, i) => decisions[i].action === 'insert' ? [{ ...fact, gate: decisions[i] }] : []);+ const { keptFacts, keep } = await writer.gateGroup(inputFacts, slug);+ const kept = group.filter((_, i) => keep[i]);if (!keptFacts.length) continue;// #4108 fail-closed on mixed provenance: one fallback-minted ref in the@@ -986,10 +1000,10 @@ async function runPipelineBodyInner(continue;}- inserted += result.inserted;- fact_ids.push(...result.ids);+ counts.inserted += result.inserted;+ counts.fact_ids.push(...result.ids);if (result.inserted > 0) fencedSlugs.add(slug);}- return { inserted, duplicate, superseded, fact_ids, entity_slugs: [...fencedSlugs], write_gate };+ return { ...counts, entity_slugs: [...fencedSlugs], write_gate };}diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex 409bf07ebf..f9f14b38a8 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -562,14 +562,7 @@ export async function writeFactsToFence(source_session: facts[i].sessionId,}));- const result = await maintenanceTransaction(engine, async tx => {- const inserted = await tx.insertFacts(enriched, { source_id: target.sourceId }); // gbrain-allow-direct-insert: writeFactsToFence is the markdown-first reconcile path; runs only after the atomic fence write commits- for (const [i, id] of (derivation ? inserted.ids : []).entries()) {- await recordTaintEdges(tx, { table: 'facts', id, sourceId: target.sourceId }, derivation!.inputs);- if (facts[i]?.gate && inserted.ids.length === facts.length) await recordFlaggedRow(tx, facts[i].gate!, { table: 'facts', id, sourceId: target.sourceId });- }- return inserted;- }, derivation?.trust);+ const result = await insertFenceRows(engine, target.sourceId, enriched, facts, derivation);// v0.46 (#3014) — an unresolvable `superseded by #N` reference (self// / dangling / struck target) leaves superseded_by NULL; log it rather// than swallow it. The row still lands (expired_at set for struck@@ -593,6 +586,23 @@ export async function writeFactsToFence();}+/**+ * The DB stamp of new fence rows in one attributed transaction: at the+ * deriver's tier when it declared one, with input edges, and the flag receipt+ * of a row whose gate decision flagged it (`facts[i]` is the input of row i).+ */+async function insertFenceRows(engine: BrainEngine, sourceId: string, rows: Parameters<BrainEngine['insertFacts']>[0], facts: FenceInputFact[],+ derivation?: { trust: WriteTrust; inputs: readonly TaintInput[] }) {+ return maintenanceTransaction(engine, async tx => {+ const inserted = await tx.insertFacts(rows, { source_id: sourceId }); // gbrain-allow-direct-insert: writeFactsToFence is the markdown-first reconcile path; runs only after the atomic fence write commits+ for (const [i, id] of inserted.ids.entries()) {+ if (derivation) await recordTaintEdges(tx, { table: 'facts', id, sourceId }, derivation.inputs);+ if (facts[i]?.gate && inserted.ids.length === facts.length) await recordFlaggedRow(tx, facts[i].gate!, { table: 'facts', id, sourceId });+ }+ return inserted;+ }, derivation?.trust);+}+/*** Look up `sources.local_path` for a given source_id. Returns null* when the source has no local_path configured (thin-client / remote-