Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): guarded fence re-projection (higher-tier rows never expired by a lower writer: contested, forget proposal or moved) and the row gate on new fence rows; unmanaged owner imports declare trust (#5575 A5, ENG-1)
garrytan12009399b429
diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex ce6321f5a1..374b7593ef 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -1,6 +1,6 @@import { assertUnmanagedCanonicalWriter } from './persistence/maintenance.ts';import { suffixedFrontmatterSlugHold } from './persistence/suffixed-slug.ts';-import { maintenanceTransaction, writeTrustOfGate } from './persistence/attribution.ts';+import { maintenanceTransaction, ownerSourceGateInput, writeTrustOfGate } from './persistence/attribution.ts';import { assertImportBase, sameCanonicalImport, sameContentAnyKeyOrder } from './page-state/import-guard.ts';import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';import { decideImportIdentity, collidingSlugOwner, fileOriginUri } from './import-identity.ts';@@ -1133,7 +1133,7 @@ export async function importFromFile(// filename `2024-03-15`.const fileBasename = basename(relativePath, '.md');const imported = await importFromContent(engine, resolvedSlug, content, {- ...opts, preserveGateMarkers: true,+ ...opts, preserveGateMarkers: true, writeGate: await ownerSourceGateInput(engine, opts.sourceId ?? 'default', parsed.frontmatter),filename: fileBasename,sourcePath: relativePath,// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- walks up from the caller's own file path by the depth of its own relative path to recover the import root; import-identity confines every probe under that rootdiff --git a/src/core/persistence/attribution.ts b/src/core/persistence/attribution.tsindex 9386bbc35b..f336f4b449 100644--- a/src/core/persistence/attribution.ts+++ b/src/core/persistence/attribution.ts@@ -4,7 +4,7 @@ import type { BrainEngine } from '../engine.ts';import { withWriteAttribution } from './context.ts';import type { WriteTrust } from '../trust/tier.ts';import { requestChannelTrust } from '../trust/channel.ts';-export { writeTrustOfGate } from '../trust/channel.ts';+export { ownerSourceGateInput, writeTrustOfGate } from '../trust/channel.ts';/*** The actor the database stamps on rows written inside withCoordinatedWritediff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex 58b25020f0..e3f2cccad4 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -16,6 +16,8 @@ import type { OperationError } from '../ops/contract.ts';import { protectedRegions } from '../fence-scan.ts';import { FENCE_ROWS_MAX, fenceOperationError, scanCanonicalFences } from '../fence-repair/refusal.ts';import type { FenceSection } from '../fence-repair/types.ts';+import { guardFenceRows } from '../trust/fence-guard.ts';+import { loadWriteGateConfig } from '../trust/gate-outcomes.ts';const FENCE_PAIRS=[{begin:FACTS_FENCE_BEGIN,end:FACTS_FENCE_END},{begin:TAKES_FENCE_BEGIN,end:TAKES_FENCE_END}];@@ -417,11 +419,11 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Parawait pipelined(tx, timelineRows);return { timelineRowsRemoved: removedSummary(removedDates) };}- if (factRows.length) {- await pipelined(tx, [expireFacts]);- await tx.insertFacts(factRows, { source_id: sourceId }); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction- await pipelined(tx, [...factFields, checkTakes, dropTakes]);- } else await pipelined(tx, [expireFacts, checkTakes, dropTakes]);+ // #5575: rows more trusted than the writer are never expired by it, and new rows pass the write gate (trust/fence-guard.ts).+ const guard = await guardFenceRows(tx, { sourceId, slug, incoming, rows: factRows, cfg: loadWriteGateConfig }, () => pipelined(tx, [expireFacts]));+ if (guard.rows.length) await tx.insertFacts(guard.rows, { source_id: sourceId }); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction+ await guard.finish(tx);+ await pipelined(tx, [...factFields, checkTakes, dropTakes]);if (takes.length) {await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(id, t)));await pipelined(tx, [...resolveTakes, ...timelineRows]);diff --git a/src/core/trust/channel.ts b/src/core/trust/channel.tsindex ff7707e5a7..e9a86e8e03 100644--- a/src/core/trust/channel.ts+++ b/src/core/trust/channel.ts@@ -189,3 +189,11 @@ export async function ownerGateInput(engine: Pick<BrainEngine, 'executeRaw'>, roconst trust = await ownerImportTrust(engine, row, frontmatter, sourceUri);return { tier: trust.tier, origin: { channel: trust.origin?.channel ?? null, source_uri: trust.origin?.source_uri ?? null }, requestId: row.id };}++/** The write-gate input of an unmanaged owner file import (direct sync / import of a source's files): the source default lowered by markers. */+export async function ownerSourceGateInput(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, frontmatter: Record<string, unknown> | null | undefined) {+ const [source] = await engine.executeRaw<{ config: Record<string, unknown> | string | null }>('SELECT config FROM sources WHERE id = $1', [sourceId]);+ const config = typeof source?.config === 'string' ? JSON.parse(source.config) as Record<string, unknown> : source?.config ?? null;+ const trust = ownerPageTrust({ frontmatter, sourceConfig: config, channel: 'import' });+ return { tier: trust.tier, origin: { channel: 'import' }, requestId: null };+}diff --git a/src/core/trust/fence-guard.ts b/src/core/trust/fence-guard.tsnew file mode 100644index 0000000000..a0d1de5a18--- /dev/null+++ b/src/core/trust/fence-guard.ts@@ -0,0 +1,106 @@+/**+ * Trust on the canonical facts-fence re-projection (#5575 A5/I3, ENG-1),+ * called by persistence/canonical-projections.ts inside the page publication.+ *+ * A page publish re-projects its `## Facts` fence: rows that changed or+ * disappeared are expired and new rows inserted. Under the writer's declared+ * tier (the transaction's gbrain.write_trust_tier, `unknown` when undeclared):+ * - Guarded supersession: a row more trusted than the writer is never expired+ * by it. The row is detached from its fence position and stays active; when+ * the writer only renumbered it (same claim and visibility elsewhere in the+ * fence, free slot) it moves there instead. Otherwise the new row at its old+ * position is inserted contested with a `supersede_fact` proposal, or, when+ * the writer removed it, a `forget` proposal asks the owner.+ * - Row gate (ENG-1): every new fence row is gated like other fact writers at+ * the writer's tier; a held row is not inserted (the hold keeps it), a+ * flagged row records its receipt after insert.+ */+import type { BrainEngine, NewFact } from '../engine.ts';+import { currentWriteTrust } from '../persistence/context.ts';+import type { WriteGateConfig } from '../write-gate.ts';+import { decideFactWrite, recordFlaggedRow, recordWriteGateHold, type GatedRowDecision } from '../write-gate-store.ts';+import { gateInput } from './gate-outcomes.ts';+import { insertTrustProposal } from './proposals.ts';+import { recordContestedFact } from './supersede-handlers.ts';+import { compareTrust, storedTrustTier, trustRankSql } from './tier.ts';++type FenceFact = NewFact & { row_num: number };+const WRITER_RANK = trustRankSql(`COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown')`);++export interface FenceGuard<T extends FenceFact> {+ /** The fence rows to insert (held and rejected rows removed, moved rows removed). */+ rows: T[];+ /** After the caller's expiry and insert: proposals for contested rows, receipts for flagged rows. */+ finish(tx: BrainEngine): Promise<void>;+}++/**+ * Before the caller expires stale fence rows: detaches rows the writer may+ * not supersede. `expired()` runs the caller's expiry; then guarded renumbers+ * move and new rows are gated.+ */+export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input: { sourceId: string; slug: string; incoming: string; rows: T[]; cfg: (db: BrainEngine) => Promise<WriteGateConfig> },+ expire: () => Promise<unknown>): Promise<FenceGuard<T>> {+ const { sourceId, slug, incoming } = input;+ const guarded = await tx.executeRaw<{ id: number; row_num: number; fact: string; visibility: string; trust_tier: string }>(+ `SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f+ WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL+ AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%'+ OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num))+ AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text)+ WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility)+ AND ${trustRankSql('f.trust_tier')} > ${WRITER_RANK}+ ORDER BY f.row_num FOR UPDATE`, [sourceId, slug, incoming]);+ if (guarded.length) await tx.executeRaw('UPDATE facts SET row_num = NULL WHERE id = ANY($1::bigint[])', [guarded.map(g => Number(g.id))]);+ await expire();+ const occupied = new Set((await tx.executeRaw<{ row_num: number }>(+ 'SELECT row_num FROM facts WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num IS NOT NULL AND expired_at IS NULL', [sourceId, slug]))+ .map(r => Number(r.row_num)));+ let rows = input.rows;+ const contested: typeof guarded = [];+ for (const g of guarded) {+ const target = rows.find(r => r.fact === g.fact && r.visibility === g.visibility && !occupied.has(r.row_num));+ if (!target) { contested.push(g); continue; }+ await tx.executeRaw('UPDATE facts SET row_num = $2 WHERE id = $1', [Number(g.id), target.row_num]);+ occupied.add(target.row_num);+ rows = rows.filter(r => r !== target);+ }+ const trust = await currentWriteTrust(tx) ?? { tier: 'unknown' as const, origin: null };+ const gated: Array<{ row: T; decision: GatedRowDecision }> = [];+ const inserted: T[] = [];+ // Owner-tier writers (tool_observed and above) are never gated, so they read no gate config.+ const cfg = compareTrust(trust.tier, 'tool_observed') < 0 && rows.some(r => !occupied.has(r.row_num)) ? await input.cfg(tx) : null;+ // Only a row this write inserts at a guarded row's old position replaces it; a moved row never does.+ const fresh = new Set(rows.filter(r => !occupied.has(r.row_num)).map(r => r.row_num));+ for (const row of rows) {+ if (!cfg || occupied.has(row.row_num)) { inserted.push(row); continue; }+ const decision = decideFactWrite({ fact: row.fact, context: row.context ?? null, source: row.source ?? null }, { sourceId, slug,+ payload: { fact: row.fact, kind: row.kind, visibility: row.visibility, entity_slug: row.entity_slug, source: row.source, context: row.context ?? null, row_num: row.row_num },+ input: gateInput(trust, null), cfg });+ if (decision.action === 'hold') { await recordWriteGateHold(tx, decision.hold!); continue; }+ if (decision.action === 'reject') continue;+ inserted.push(row);+ if (decision.assessment.verdict === 'flag') gated.push({ row, decision });+ }+ return {+ rows: inserted,+ async finish(db) {+ const at = async (rowNum: number) => (await db.executeRaw<{ id: number; trust_tier: string }>(+ `SELECT id, trust_tier FROM facts WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num = $3 AND expired_at IS NULL`, [sourceId, slug, rowNum]))[0];+ for (const g of contested) {+ const replacement = fresh.has(Number(g.row_num)) ? await at(Number(g.row_num)) : undefined;+ if (replacement) {+ await recordContestedFact(db, { sourceId, oldId: Number(g.id), oldTier: storedTrustTier(g.trust_tier), newId: Number(replacement.id),+ newTier: storedTrustTier(replacement.trust_tier), guard: 'fence_projection' });+ } else {+ await insertTrustProposal(db, { action: 'forget', sourceId, target: { table: 'facts', id: Number(g.id) }, proposer: 'fence_projection',+ before: { guard: 'fence_projection', fact: { id: Number(g.id), tier: storedTrustTier(g.trust_tier) }, writer_tier: trust.tier, slug } });+ }+ }+ for (const { row, decision } of gated) {+ const stored = await at(row.row_num);+ if (stored) await recordFlaggedRow(db, decision, { table: 'facts', id: Number(stored.id), sourceId });+ }+ },+ };+}diff --git a/test/trust-guarded-supersession.test.ts b/test/trust-guarded-supersession.test.tsindex dbfd8dc699..715168eb54 100644--- a/test/trust-guarded-supersession.test.ts+++ b/test/trust-guarded-supersession.test.ts@@ -192,3 +192,37 @@ describe('write gate on remember (DX-1)', () => {}}), 90_000);});++describe('guarded fence re-projection (A5, ENG-1)', () => {+ const row = (n: number, claim: string) => ({ rowNum: n, claim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true });+ const body = (rows: ReturnType<typeof row>[]) => `Profile.\n\n## Facts\n\n${renderFactsTable(rows as never)}`;+ test('an agent rewrite cannot expire a confirmed fence row: rewritten -> contested, removed -> forget proposal, renumbered -> moved', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const b = await brain(engine);+ const slug = 'people/erin-example';+ await run(b.local, 'put_page', { slug, content: page('Erin', body([row(1, 'Erin lives in Oslo'), row(2, 'Erin owns a boat'), row(3, 'Erin speaks Norwegian')])) });+ const ids = async () => Object.fromEntries((await engine.executeRaw<{ fact: string; id: number }>(+ 'SELECT fact, id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND expired_at IS NULL', [b.sourceId, slug])).map(r => [r.fact, Number(r.id)]));+ const before = await ids();+ for (const id of Object.values(before)) await confirmFact(b, id);+ const current = await operationsByName.get_page.handler(b.remote, { slug, include_content: true }) as Record<string, any>;+ // Row 1 rewritten, row 2 removed, row 3 renumbered to 2 (behind a new row 1 order change).+ await run(b.remote, 'put_page', { slug, content: page('Erin', body([row(1, 'Erin lives in Bergen'), row(2, 'Erin speaks Norwegian')])), expected_revision: current.revision });+ const after = await engine.executeRaw<{ id: number; fact: string; row_num: number | null; expired_at: unknown; trust_tier: string }>(+ 'SELECT id, fact, row_num, expired_at, trust_tier FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY id', [b.sourceId, slug]);+ const by = (fact: string) => after.find(r => r.fact === fact)!;+ expect(by('Erin lives in Oslo')).toMatchObject({ row_num: null, expired_at: null, trust_tier: 'user_confirmed' });+ expect(by('Erin owns a boat')).toMatchObject({ row_num: null, expired_at: null });+ expect(by('Erin speaks Norwegian')).toMatchObject({ id: before['Erin speaks Norwegian'], row_num: 2, expired_at: null, trust_tier: 'user_confirmed' });+ expect(by('Erin lives in Bergen')).toMatchObject({ row_num: 1, expired_at: null, trust_tier: 'agent_written' });+ const proposals = await listTrustProposals(engine, { sourceId: b.sourceId });+ expect(proposals.map(p => [p.action, p.target_id, p.related_id]).sort()).toEqual([+ ['forget', before['Erin owns a boat'], null],+ ['supersede_fact', before['Erin lives in Oslo'], Number(by('Erin lives in Bergen').id)],+ ].sort());+ const supersede = proposals.find(p => p.action === 'supersede_fact')!;+ expect((await decideTrustProposal(engine, supersede.id, 'accept', owner)).status).toBe('accepted');+ expect((await factRow(b, before['Erin lives in Oslo'])).expired_at).not.toBeNull();+ }+ }), 90_000);+});