Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): honor L1b contracts (re-chunk on tier changes, declared tier for pending fence rows, re-gated rewrites drop stale page receipts); trust help golden
garrytan15387396aab1
diff --git a/src/core/import-screen.ts b/src/core/import-screen.tsindex 5f5dd4d579..a0cb67bfd1 100644--- a/src/core/import-screen.ts+++ b/src/core/import-screen.ts@@ -21,7 +21,7 @@ import {assessPageForGate, DEFAULT_WRITE_GATE_CONFIG, parseWriteGateConfig, writeGateDetail, writeGateRejectedError,type WriteGateAssessment, type WriteGateConfig, type WriteGateInput,} from './write-gate.ts';-import { recordPageGateReceipt } from './write-gate-store.ts';+import { clearStalePageGateReceipts, recordPageGateReceipt } from './write-gate-store.ts';import { loadOperatorLiterals } from './content-sanity-literals.ts';import { classifyImportHold, contentSizeHold, parseMarkdown, type ContentHold, type ParseOpts, type ParsedMarkdown } from './markdown.ts';import { isCodeFilePath } from './sync.ts';@@ -249,6 +249,7 @@ export async function settleContentDisposition(engine: BrainEngine, parsed: Parsreturn {quarantined: pageQuarantined, flagged: pageFlagged, ...(pageFlagReason ? { flagReason: pageFlagReason } : {}), gate,persistReceipt: async tx => {+ if (gate?.ran) await clearStalePageGateReceipts(tx, { slug, sourceId: sourceId ?? 'default', contentHash: gate.contentHash });if (gate) await recordPageGateReceipt(tx, { slug, sourceId: sourceId ?? 'default', assessment: gate, requestId: ctx.writeGate?.requestId ?? null });},};diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 4107a0ea65..851bddc45b 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -134,7 +134,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque// Reuse the canonical parser/chunker and durable filesystem publication.// The original caller revision was checked above; this CAS binds this render.// #5575 ENG-1: the new row has no facts row yet; its chunks are cut at the append's tier.- page = await withPendingFenceRows({ sourceId: row.source_id, slug: row.slug, rowNums: [appended.rowNum], tier: fenceAppendPendingTier() },+ page = await withPendingFenceRows({ sourceId: row.source_id, slug: row.slug, rowNums: [appended.rowNum], tier: fenceAppendPendingTier(writerTier) },() => preparePageMutation(engine, { ...row, intent: { ...p, content, expected_revision: observedRevision, force: false } }, config, undefined, signal));if (page.observedRevision !== observedRevision) conflict(row);}diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.tsindex efce52b07b..a9bd1e5630 100644--- a/src/core/trust/page-handlers.ts+++ b/src/core/trust/page-handlers.ts@@ -23,6 +23,7 @@*/import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';+import { queueTierProjection } from './page-write.ts';import type { GBrainConfig } from '../config.ts';import type { OperationContext } from '../ops/contract.ts';import { opError } from '../ops/contract.ts';@@ -135,6 +136,7 @@ export async function setRowTier(engine: BrainEngine, input: {WHERE id = $1 RETURNING id`, [input.id, input.tier, JSON.stringify({ tier: input.tier, at: new Date().toISOString(), ...input.note })]);const rows = input.ceiling ? await withTrustPromotion(tx, input.ceiling, update) : await update();if (rows.length !== 1) return false;+ await queueTierProjection(tx, input.table, input.id);await input.also?.(tx);return true;};diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.tsindex 0b79c52dd4..b4e2675a95 100644--- a/src/core/trust/page-write.ts+++ b/src/core/trust/page-write.ts@@ -18,6 +18,7 @@* fold into it) with the prior owner version to revert to.*/import type { BrainEngine } from '../engine.ts';+import { queuePageProjection } from '../page-state/projections.ts';import type { WriteRequest } from '../persistence/model.ts';import { frontmatterTrustCaps, requestChannelTrust, stampTrustMarker } from './channel.ts';import { insertTrustProposal, updatePendingTrustProposalAfter } from './proposals.ts';@@ -94,3 +95,16 @@ export async function recordAgentPageLowering(tx: BrainEngine, row: Pick<WriteReif (!proposal.created) await updatePendingTrustProposalAfter(tx, proposal.id, after);return { proposal_ref: `tp${proposal.id}` };}++/**+ * L1b contract: chunks render fence rows by their tier relative to the page's+ * (eligibility/fence-overlay.ts), so any tier change of a fact, take or page+ * queues the page's projection rebuild (re-chunk) in the same transaction.+ */+export async function queueTierProjection(tx: BrainEngine, table: 'facts' | 'takes' | 'pages', id: number): Promise<void> {+ const sql = table === 'facts' ? 'SELECT source_id, source_markdown_slug AS slug FROM facts WHERE id = $1 AND source_markdown_slug IS NOT NULL'+ : table === 'takes' ? 'SELECT p.source_id, p.slug FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.id = $1'+ : 'SELECT source_id, slug FROM pages WHERE id = $1';+ const [page] = await tx.executeRaw<{ source_id: string; slug: string }>(sql, [id]);+ if (page) await queuePageProjection(tx, page.source_id, page.slug, 'trust_tier_changed');+}diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.tsindex ca33392838..946ec17b2e 100644--- a/src/core/trust/supersede-handlers.ts+++ b/src/core/trust/supersede-handlers.ts@@ -24,6 +24,7 @@ import {type TrustDecision, type TrustDecisionContext, type TrustProposalAction, type TrustProposalRow,} from './proposals.ts';import { tierRaiseFix } from './confirm.ts';+import { queueTierProjection } from './page-write.ts';import { compareTrust, effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';/** I3: a write at `writer` may supersede, expire or forget a row at `target` only when it is at least as trusted. */@@ -146,12 +147,14 @@ export const TRUST_PAIR_STORE: PairProposalStore = {async onAccept(tx, proposal) {await withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw(`UPDATE facts SET trust_tier = 'user_confirmed' WHERE id = $1 AND source_id = $2`, [proposal.new_fact_id, proposal.source_id]));+ for (const id of [proposal.old_fact_id, proposal.new_fact_id]) await queueTierProjection(tx, 'facts', id);},/** Undo returns the new fact to the tier it had before the accept confirmed it (lowering needs no promotion). */async onUndo(tx, proposal) {const row = await getTrustProposal(tx, proposal.id);const prior = storedTrustTier((row?.before_state.new as { tier?: unknown } | undefined)?.tier);await tx.executeRaw(`UPDATE facts SET trust_tier = $3 WHERE id = $1 AND source_id = $2`, [proposal.new_fact_id, proposal.source_id, prior]);+ for (const id of [proposal.old_fact_id, proposal.new_fact_id]) await queueTierProjection(tx, 'facts', id);},};registerPairProposalStore(TRUST_PAIR_STORE);diff --git a/src/core/write-gate-store.ts b/src/core/write-gate-store.tsindex 134ff2264f..f6b9b2ad7a 100644--- a/src/core/write-gate-store.ts+++ b/src/core/write-gate-store.ts@@ -70,6 +70,17 @@ export async function recordPageGateReceipt(tx: Exec, input: {return rows[0] ? Number(rows[0].id) : null;}+/**+ * ENG-11 (L1b contract): a page rewrite the gate assessed again replaces the+ * verdict of the content it replaced, so receipts on the page for any other+ * content hash are removed (an allowed benign rewrite stops being suppressed).+ */+export async function clearStalePageGateReceipts(tx: Exec, input: { slug: string; sourceId: string; contentHash: string | null }): Promise<void> {+ await tx.executeRaw(`DELETE FROM write_gate_receipts r USING pages p+ WHERE r.target_table = 'pages' AND r.target_id = p.id::text AND p.source_id = $1 AND p.slug = $2 AND r.content_hash IS DISTINCT FROM $3`,+ [input.sourceId, input.slug, input.contentHash]);+}+/** Dedupe key for a held row: its kind plus the normalized text of every gated field. */export function holdFingerprint(kind: WriteGateHoldKind, texts: ReadonlyArray<string | null | undefined>): string {return createHash('sha256').update(`${kind}\u0000${texts.map(t => normalizeForGate(t ?? '').toLowerCase().replace(/\s+/g, ' ').trim()).join('\u0001')}`).digest('hex');diff --git a/test/fixtures/goldens/trust/help.txt b/test/fixtures/goldens/trust/help.txtindex 482f21768b..ed9f6e0fc6 100644--- a/test/fixtures/goldens/trust/help.txt+++ b/test/fixtures/goldens/trust/help.txt@@ -1,4 +1,4 @@-Usage: gbrain trust <review|confirm|release|drop|revert|explain|allow|disable|backfill> [options]+Usage: gbrain trust <review|confirm|release|drop|revert|explain|allow|disable|backfill|scan> [options]review [--from <source>] [--kind <kind>] [--since <7d|date>] [--json]Everything waiting for you: trust proposals (tp<id>), pages an agent edit lowered, unconfirmed standingpreferences (f<id>), held writes (h<id>) and your allow rules (a<id>), grouped by day and page, each with@@ -31,3 +31,8 @@ Usage: gbrain trust backfill [--dry-run] [--resume] [--batch-size N] [--json]the journaled request that wrote the row. Rows with no signal stay "unverified origin"; nothing becomes"confirmed by you". --dry-run is read-only (no migrations, no writes) and works before the trust migration;it reports the projected count per table and tier. --resume continues an interrupted run.++Usage: gbrain trust scan [--batch-size N] [--json]+ Runs the write gate's deterministic detector over agent-written and lower rows written before the gate,+ recording a receipt for each instruction-like row so proactive surfaces stop injecting it until you confirm+ it (gbrain trust review). Changes no row; resumable (rerun to continue); a detector upgrade rescans.diff --git a/test/trust-channel-writes.test.ts b/test/trust-channel-writes.test.tsindex 88da26ae0c..4017b149dd 100644--- a/test/trust-channel-writes.test.ts+++ b/test/trust-channel-writes.test.ts@@ -316,6 +316,10 @@ describe('write gate on page writes (DX-1)', () => {for (const r of receipts) expect(r.tier).toBe(r.trust_tier);const plain = await run(b.remote, 'put_page', { slug: 'notes/plain-example', content: page('Plain', 'Ordinary notes.') });expect(plain.gate).toBeUndefined();+ // ENG-11: a benign rewrite of the flagged page is re-gated and its old verdict is dropped.+ await run(b.remote, 'put_page', { slug: 'notes/flagged-example', content: page('Flagged', 'Now just ordinary notes.'), force: true });+ expect(await engine.executeRaw(`SELECT 1 FROM write_gate_receipts r JOIN pages p ON p.id::text = r.target_id AND r.target_table = 'pages'+ WHERE p.source_id = $1 AND p.slug = 'notes/flagged-example'`, [b.sourceId])).toHaveLength(0);}}), 90_000);});