Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): a fence append never changes the page tier (#5575 ENG-1)
garrytanff5e17bc1831
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex e5498a12fe..b52210b8c4 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -56,6 +56,7 @@ import { logStubGuardEvent } from './stub-guard-audit.ts';import { isFactWithdrawn } from './withdrawal.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';+import { withPageTierKept } from '../trust/fence-append.ts';/** Resolved source binding for the entity page. */export interface FenceTarget {@@ -523,9 +524,10 @@ export async function writeFactsToFence(const reparsed = parseMarkdown(tmpBody, `${target.slug}.md`);const existing = await engine.getPage(target.slug, { sourceId: target.sourceId });if (existing) {- await maintenanceTransaction(engine, tx => tx.refreshPageBody(target.slug, target.sourceId,+ // #5575 ENG-1: the appended rows carry their own tier; the page keeps its tier.+ await maintenanceTransaction(engine, tx => withPageTierKept(tx, target, () => tx.refreshPageBody(target.slug, target.sourceId,sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),- existing.content_hash || contentHash(existing)));+ existing.content_hash || contentHash(existing))));}} catch (err) {// The file is committed; the page cache stays stale until the nextdiff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex d1e63ee7cb..12fc496a69 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -19,6 +19,8 @@ import type { WriteRequest } from './model.ts';import type { ManagedFactIntent, FrozenExtractedFact } from './facts-maintenance.ts';import { assertManagedFactsEmbedding } from './facts-maintenance.ts';import { normalizeTargetFences } from '../fence-repair/import-step.ts';+import { fenceAppendPendingTier, withPendingFenceRows } from '../eligibility/fence-overlay.ts';+import { withPageTierKept } from '../trust/fence-append.ts';import { pageFencesNormalized } from '../fence-repair/report.ts';const requestFix = (row: WriteRequest): Action => row.principal_kind === 'local_cli'@@ -159,8 +161,11 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ}let page: PreparedMutation | undefined;if (snapshot && entries.some(entry => entry.rowNum !== undefined)) {- page = await preparePageMutation(engine, { ...row, intent: { ...p,- content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body, timeline: target!.page.timeline }, snapshot.tags) } }, config);+ // #5575 ENG-1: the appended rows have no facts rows yet; their chunks are cut at the append's tier.+ const rowNums = entries.flatMap(entry => entry.rowNum === undefined ? [] : [entry.rowNum]);+ page = await withPendingFenceRows({ sourceId: row.source_id, slug: row.slug, rowNums, tier: fenceAppendPendingTier() },+ () => preparePageMutation(engine, { ...row, intent: { ...p,+ content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body, timeline: target!.page.timeline }, snapshot.tags) } }, config));if (page.observedRevision !== snapshot.revision) throw factsRefusal('revision_conflict', 'The fact entity changed during preparation.', row,`Entity page ${row.slug} changed while its ## Facts table was being prepared, so none of these facts were published.`);}@@ -176,7 +181,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ`A matching fact in source ${row.source_id} was added or retired before publication, so the deduplication decision for ${row.slug} is stale and none of these facts were published.`);}}, apply: async tx => {- await page?.apply(tx);+ if (page) await withPageTierKept(tx, { sourceId: row.source_id, slug: row.slug }, () => page!.apply(tx));const ids: number[] = [];let inserted = 0;let superseded = 0;diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 022bc90802..84bf8863fc 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -17,6 +17,8 @@ import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';import { inferenceNote } from '../facts/subject-infer-write.ts';import { normalizeTargetFences } from '../fence-repair/import-step.ts';import { pageFencesNormalized } from '../fence-repair/report.ts';+import { fenceAppendPendingTier, withPendingFenceRows } from '../eligibility/fence-overlay.ts';+import { withPageTierKept } from '../trust/fence-append.ts';function receiptFix(row: WriteRequest): Action {return row.principal_kind === 'local_cli'@@ -114,11 +116,13 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst content = serializePageToMarkdown({ ...snapshot.page, compiled_truth: body, timeline: target.page.timeline }, snapshot.tags);// Reuse the canonical parser/chunker and durable filesystem publication.// The original caller revision was checked above; this CAS binds this render.- page = await preparePageMutation(engine, { ...row, intent: { ...p, content, expected_revision: observedRevision, force: false } }, config, undefined, signal);+ // #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() },+ () => preparePageMutation(engine, { ...row, intent: { ...p, content, expected_revision: observedRevision, force: false } }, config, undefined, signal));if (page.observedRevision !== observedRevision) conflict(row);}return { observedRevision, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), validate: async tx => { await validate(tx); await page?.validate?.(tx); }, apply: async tx => {- await page?.apply(tx);+ if (page) await withPageTierKept(tx, { sourceId: row.source_id, slug: row.slug }, () => page!.apply(tx));let id: number;if (rowNum !== undefined) {const inserted = await tx.insertFacts([{ ...fact, row_num: rowNum, source_markdown_slug: row.slug }], { source_id: row.source_id }); // gbrain-allow-direct-insert: coordinator atomically publishes the prepared canonical fact fence and its new indexed rowdiff --git a/src/core/trust/fence-append.ts b/src/core/trust/fence-append.tsnew file mode 100644index 0000000000..3da5a876c5--- /dev/null+++ b/src/core/trust/fence-append.ts@@ -0,0 +1,41 @@+/**+ * A fence append never changes the page tier (#5575 ENG-1).+ *+ * Appending a row to a page's `## Facts` fence rewrites compiled_truth, which+ * the tier trigger (trust/schema.ts) treats as a content rewrite: an+ * agent-tier writer would lower an owner page to its own tier, and an+ * owner-tier writer would restamp an external page to its tier. The appended+ * row carries its own tier on its facts row (the writer's), and chunks show it+ * under that tier (eligibility/fence-overlay.ts), so the page keeps the tier+ * and origin it had before the append.+ *+ * The restore runs in the same transaction, after the page write: lowering+ * back needs nothing; raising back to the page's own prior tier uses the+ * promotion capability (persistence/context.ts) with that tier as the+ * ceiling, so it can never lift a page above what it already was.+ */+import type { BrainEngine } from '../engine.ts';+import { withTrustPromotion } from '../persistence/context.ts';+import { compareTrust, isTrustTier } from './tier.ts';++type Exec = Pick<BrainEngine, 'executeRaw'>;++interface StoredPageTrust { id: number; trust_tier: string; write_origin: unknown }++const sameOrigin = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);+const originText = (value: unknown) => value === null || value === undefined ? null : typeof value === 'string' ? value : JSON.stringify(value);++/** Runs `fn` (the page write of a fence append) and restores the page's prior trust_tier and write_origin. */+export async function withPageTierKept<T>(tx: Exec, page: { sourceId: string; slug: string }, fn: () => Promise<T>): Promise<T> {+ const [prior] = await tx.executeRaw<StoredPageTrust>(+ 'SELECT id, trust_tier, write_origin FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [page.sourceId, page.slug]);+ const result = await fn();+ if (!prior || !isTrustTier(prior.trust_tier)) return result;+ const [after] = await tx.executeRaw<StoredPageTrust>('SELECT id, trust_tier, write_origin FROM pages WHERE id=$1', [prior.id]);+ if (!after || !isTrustTier(after.trust_tier) || (after.trust_tier === prior.trust_tier && sameOrigin(after.write_origin, prior.write_origin))) return result;+ const restore = () => tx.executeRaw('UPDATE pages SET trust_tier=$2, write_origin=$3::text::jsonb WHERE id=$1',+ [prior.id, prior.trust_tier, originText(prior.write_origin)]);+ if (compareTrust(prior.trust_tier, after.trust_tier) > 0) await withTrustPromotion(tx, prior.trust_tier, restore);+ else await restore();+ return result;+}