Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(trust): a server-stamped trust marker never turns an unchanged write into a write (CEO-21)
garrytana35d20bc6ca9
diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 1ce5485854..71449fa296 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, ownerSourceGateInput, trustMarkerChanged, writeTrustOfGate } from './persistence/attribution.ts';+import { maintenanceTransaction, ownerSourceGateInput, suppliedTrustMarkerView, trustMarkerChanged, 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';@@ -474,6 +474,9 @@ export async function importFromContent(// formula (byte-parity pinned by test/content-hash-parity-3694.test.ts).// Sort tags in place first to preserve the pre-#3694 downstream behavior// (parsedPage.tags was sorted by the old inline `.sort()` mutation).+ // #5575 CEO-21: prepareFrontmatter may stamp the server's lower-only trust_tier marker; whether the write is a+ // no-op is decided on the caller's own frontmatter, so an unchanged round trip stays an unstamped no-op.+ const suppliedTrustMarker = parsed.frontmatter.trust_tier;if (opts.prepare) opts.prepareFrontmatter?.(parsed);parsed.tags.sort();const hash = contentHash({@@ -521,9 +524,13 @@ export async function importFromContent(timeline: parsed.timeline,frontmatter: parsed.frontmatter,});- const unchanged = !!existing && !existing.deleted_at && !opts.forceRechunk && !needsProjectionRebuild && !embedSkipChanged && !trustMarkerChanged(existing.frontmatter, parsed.frontmatter) && (existing.content_hash === hash- ? !opts.prepare || sameCanonicalImport(existingSnapshot, parsedPage)- : !legacyHashMatch && await sameContentAnyKeyOrder(engine, existing, existingSnapshot?.tags ?? null, parsedPage, sourceId ?? 'default'));+ const unchangedAs = async (page: ParsedPage) => !!existing && !existing.deleted_at && !opts.forceRechunk && !needsProjectionRebuild && !embedSkipChanged+ && !trustMarkerChanged(existing.frontmatter, page.frontmatter) && (existing.content_hash === hash+ ? !opts.prepare || sameCanonicalImport(existingSnapshot, page)+ : !legacyHashMatch && await sameContentAnyKeyOrder(engine, existing, existingSnapshot?.tags ?? null, page, sourceId ?? 'default'));+ // Unchanged as stamped (the stored page already carries the marker), or as the caller sent it (the marker would be new).+ const suppliedPage: ParsedPage = { ...parsedPage, frontmatter: suppliedTrustMarkerView(parsed.frontmatter, suppliedTrustMarker) };+ const unchanged = await unchangedAs(parsedPage) || (suppliedTrustMarker !== parsed.frontmatter.trust_tier && await unchangedAs(suppliedPage));if (existing && unchanged) {// #5050: unchanged content chunked before the safe-chunk fence is re-sealed// projection-only; the canonical write stays a no-op.diff --git a/src/core/persistence/attribution.ts b/src/core/persistence/attribution.tsindex f8aaf5c579..634a0e829d 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 { ownerSourceGateInput, trustMarkerChanged, writeTrustOfGate } from '../trust/channel.ts';+export { ownerSourceGateInput, suppliedTrustMarkerView, trustMarkerChanged, writeTrustOfGate } from '../trust/channel.ts';/*** The actor the database stamps on rows written inside withCoordinatedWritediff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 5eacee5bf0..88dfd3da75 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -55,6 +55,7 @@ import { fenceRepairCommit } from './effect-model.ts';import { purgePageInTransaction } from './page-purge.ts';import { withTrustKeep } from './context.ts';import { isFenceEditWrite, pageGateTrust, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';+import { suppliedTrustMarkerView } from '../trust/channel.ts';import { gateField, gateInput } from '../trust/gate-outcomes.ts';@@ -371,6 +372,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest}let prepared: PreparedContentImport | undefined;let provenance: CanonicalProvenance | undefined;+ let suppliedTrustMarker: unknown;// #5575: the page's tier, computed once before import so the write gate sees exactly it (ENG-18).const trust = pageWriteTrust(row, typeof content === 'string' && !isFenceEditWrite(row) ? parseMarkdown(content, row.slug, { activePack }).frontmatter : null);const gateTrust = pageGateTrust(row, trust, storedTier);@@ -384,9 +386,11 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestsource_uri: typeof p.source_uri === 'string' ? p.source_uri : null,ingested_via: typeof p.ingested_via === 'string' ? p.ingested_via : null,...(gateTrust ? { writeGate: gateInput(gateTrust, row.id) } : {}),+ // Provenance compares the caller's page with the stored one, so it runs before the server's trust marker is stamped.prepareFrontmatter: page => {- stampPageTrustMarker(row, page.frontmatter, trust, storedTier);provenance = putProvenance(row, snapshot, page);+ suppliedTrustMarker = page.frontmatter.trust_tier;+ stampPageTrustMarker(row, page.frontmatter, trust, storedTier);},prepare: async value => { prepared = value; return value.result; },}).catch(error => {@@ -427,7 +431,9 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst tags = versionTags ?? [...new Set([...(snapshot?.tags ?? []), ...ready.parsedPage.tags])].sort();const renderedPage: Page = { ...(snapshot?.page ?? { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage };const rendered = serializePageToMarkdown(renderedPage, tags);- const logicalNoop = snapshot !== null && digest(canonical(snapshot.page, snapshot.tags)) === digest(canonical(ready.parsedPage, tags));+ // CEO-21: the server-stamped trust marker alone never makes a write: unchanged as stamped or as the caller sent it.+ const callerPage = { ...ready.parsedPage, frontmatter: suppliedTrustMarkerView(ready.parsedPage.frontmatter, suppliedTrustMarker) };+ const logicalNoop = snapshot !== null && [ready.parsedPage, callerPage].some(page => digest(canonical(snapshot.page, snapshot.tags)) === digest(canonical(page, tags)));const noop = logicalNoop && (snapshot?.page.deleted_at != null) === targetDeleted;const project = projected ? await prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer,timelinePolicy) : undefined;const ordinaryPage = ['put_page','capture','restore_page','revert_version','edit_page'].includes(row.operation);diff --git a/src/core/trust/channel.ts b/src/core/trust/channel.tsindex 7ebd102b4b..0d3f060f04 100644--- a/src/core/trust/channel.ts+++ b/src/core/trust/channel.ts@@ -216,6 +216,16 @@ export async function ownerSourceGateInput(engine: Pick<BrainEngine, 'executeRaw* change is adding or removing it would read as unchanged; removing it by hand* is the owner act that restamps a page on the next sync (CEO-21), so it counts.*/+/**+ * CEO-21: `frontmatter` with its trust_tier marker set back to what the caller+ * supplied (removed when it supplied none). No-op detection compares this+ * view, so a server-stamped marker never turns an unchanged write into a write.+ */+export function suppliedTrustMarkerView(frontmatter: Record<string, unknown>, supplied: unknown): Record<string, unknown> {+ const { trust_tier: _stamped, ...rest } = frontmatter;+ return supplied === undefined ? rest : { ...rest, trust_tier: supplied };+}+export function trustMarkerChanged(prior: Record<string, unknown> | null | undefined, next: Record<string, unknown> | null | undefined): boolean {return (prior?.trust_tier ?? null) !== (next?.trust_tier ?? null);}diff --git a/test/ingestion/put-page-write-through.test.ts b/test/ingestion/put-page-write-through.test.tsindex 103348492d..6508527096 100644--- a/test/ingestion/put-page-write-through.test.ts+++ b/test/ingestion/put-page-write-through.test.ts@@ -404,8 +404,9 @@ ${subtypes}`);fs.writeFileSync(file, content);await putPage.handler(makeCtx({ remote: true }), { slug, content: content.replace('Existing body', 'Edited body'), force: true });const after = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ // The edit is a remote agent write over an unknown-tier page, so it also carries the lower-only trust marker (#5575 CEO-21).expect(after.page.frontmatter).toEqual({ source_kind: 'mcp:put_page', ingested_via: 'mcp:put_page',- ingested_at: before.page.ingested_at!.toISOString() });+ ingested_at: before.page.ingested_at!.toISOString(), trust_tier: 'unknown' });expect(after.page.source_kind).toBe('mcp:put_page');expect(after.page.ingested_at).toEqual(before.page.ingested_at);expect(parseMarkdown(fs.readFileSync(file, 'utf8'), slug).frontmatter).toEqual(after.page.frontmatter);