Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(trust): tier a remote write by the stamps it publishes (#7873)

garrytan15c431159f5a
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index d608e15a78..460c5615af 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -91,6 +91,7 @@ import { withoutSafetyAssessments } from './reconcile-safety.ts';
import { preparePagePurge, purgePageInTransaction, type PreparedPagePurge } from './page-purge.ts';
import { withTrustKeep } from './context.ts';
import { isFenceEditWrite, pageGateTrust, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';
+import { compareTrust, type WriteTrust } from '../trust/tier.ts';
import { suppliedTrustMarkerView } from '../trust/channel.ts';
import { gateField, gateInput } from '../trust/gate-outcomes.ts';
import { PUSH_SCAN_MAX_FILE_BYTES } from '../page-size-policy.ts';
@@ -137,8 +138,8 @@ const CALLER_CONTENT_OPERATIONS = ['put_page', 'edit_page', 'append_page', 'capt
* the stored page's kept. A managed put_page (local too) also stamps the first write's provenance.
*/
function putProvenance(row: WriteRequest, snapshot: PageSnapshot | null, parsed: ParsedPage): CanonicalProvenance | undefined {
+ if (!serverOwnsProvenance(row)) return undefined;
const managedPut = row.operation === 'put_page' && !!row.worktree_id;
- if (!managedPut && !(row.authority.remote && CALLER_CONTENT_OPERATIONS.includes(row.operation))) return undefined;
keepStoredProvenance(parsed.frontmatter, snapshot?.page.frontmatter);
if (!managedPut) return undefined;
const tags = [...new Set([...(snapshot?.tags ?? []), ...parsed.tags])].sort();
@@ -158,6 +159,22 @@ function putProvenance(row: WriteRequest, snapshot: PageSnapshot | null, parsed:
Object.assign(parsed.frontmatter, stamp);
return stamp;
}
+function serverOwnsProvenance(row: WriteRequest): boolean {
+ return (row.operation === 'put_page' && !!row.worktree_id) || (row.authority.remote === true && CALLER_CONTENT_OPERATIONS.includes(row.operation));
+}
+/**
+ * #7873: the tier of a write whose provenance stamps are server-owned is the lower of its own frontmatter's and the
+ * frontmatter it publishes (the stored stamps kept), so dropping a stored lowering stamp escapes neither the write gate
+ * nor the page row's tier.
+ */
+export function provenanceWriteTrust(row: WriteRequest, frontmatter: Record<string, unknown> | null, stored: Record<string, unknown> | null | undefined): WriteTrust | undefined {
+ const trust = pageWriteTrust(row, frontmatter);
+ if (!trust || !frontmatter || !serverOwnsProvenance(row)) return trust;
+ const published = { ...frontmatter };
+ keepStoredProvenance(published, stored);
+ const kept = pageWriteTrust(row, published);
+ return kept && compareTrust(kept.tier, trust.tier) < 0 ? kept : trust;
+}
/** The provenance stamps of `stored` replace whatever `frontmatter` carries for them (removed when the stored page has none). */
export function keepStoredProvenance(frontmatter: Record<string, unknown>, stored: Record<string, unknown> | null | undefined): void {
for (const key of ['source_kind', 'ingested_via', 'ingested_at'] as const) {
@@ -882,7 +899,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
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 trust = provenanceWriteTrust(row, typeof content === 'string' && !isFenceEditWrite(row) ? parseMarkdown(content, row.slug, { activePack }).frontmatter : null, snapshot?.page.frontmatter);
const gateTrust = pageGateTrust(row, trust, storedTier);
// The apply diet: the publisher's locked read of row.slug is the import base, and one read after the
// last page write serves the read-back check, the seal, the core notice and the receipt (as sync does).
diff --git a/src/core/persistence/upload-streamed.ts b/src/core/persistence/upload-streamed.ts
index 9b16cfef83..2070d6d875 100644
--- a/src/core/persistence/upload-streamed.ts
+++ b/src/core/persistence/upload-streamed.ts
@@ -21,7 +21,7 @@ import { readPageBodyPolicy } from '../page-body/limits.ts';
import { importStreamedMarkdownFile, type StreamedPreparedImport } from '../page-body/streamed-import.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { contentRefusalError, PAGE_OVER_LIMIT_SUGGESTION } from '../import-screen.ts';
-import { pageGateTrust, pageWriteTrust, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';
+import { pageGateTrust, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';
import type { WriteTrust } from '../trust/tier.ts';
import { sizeStateField } from '../page-embedding-budget.ts';
import { coreMarking } from '../core-memory.ts';
@@ -34,7 +34,7 @@ import type { PageSnapshot } from '../page-state/types.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import { bodyStagingGoneError } from '../engine-sql/page-body.ts';
import { ownerSourceGateInput, writeTrustOfGate } from './attribution.ts';
-import { keepStoredProvenance, pageDatabaseOnlyPublication } from './page-prepare.ts';
+import { keepStoredProvenance, pageDatabaseOnlyPublication, provenanceWriteTrust } from './page-prepare.ts';
import { pageIdentityError } from './page-identity.ts';
import { remoteLinkHint } from './page-advisories.ts';
import { stagedUploadParts, stagedUploadWork, type StagingBodyRef } from './page-upload.ts';
@@ -112,7 +112,7 @@ export async function prepareStreamedUpload(engine: BrainEngine, row: WriteReque
content: { provenance: { source_kind: text(p.source_kind), source_uri: text(p.source_uri), ingested_via: text(p.ingested_via) },
...(remote ? { writer: {
gate: async (frontmatter: Record<string, unknown>) => {
- trust = pageWriteTrust(row, frontmatter);
+ trust = provenanceWriteTrust(row, frontmatter, snapshot?.page.frontmatter);
const gate = pageGateTrust(row, trust, storedTier);
return gate ? { tier: gate.tier, origin: { channel: gate.origin?.channel ?? row.operation }, requestId: null } : ownerSourceGateInput(engine, row.source_id, frontmatter);
},
diff --git a/test/large-pages/upload-provenance-7873.test.ts b/test/large-pages/upload-provenance-7873.test.ts
index b51c5d015d..40ec763cf7 100644
--- a/test/large-pages/upload-provenance-7873.test.ts
+++ b/test/large-pages/upload-provenance-7873.test.ts
@@ -3,9 +3,10 @@
* cannot supply provenance stamps, as a remote put_page cannot.
*
* 1. Protects: commit_page_upload of a 25 MiB page whose frontmatter carries source_kind / ingested_via /
- * ingested_at stores none of the caller's values; a replace keeps the stamps of the page it replaces.
+ * ingested_at stores none of the caller's values; a replace of an unclassified page keeps the stamps of the page it
+ * replaces and is tiered by them.
* 2. Fails when: a caller-written stamp reaches the stored frontmatter through the streamed path, or a replace drops
- * the stored stamps.
+ * the stored stamps or is tiered above them.
* 3. Runs on PGLite, and on Postgres when DATABASE_URL is set (no embedding, no model calls).
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
@@ -70,6 +71,9 @@ for (const kind of testBackends()) {
const stored = { source_kind: 'webhook', ingested_via: 'webhook', ingested_at: '2026-01-02T03:04:05.000Z' };
await engine.putPage(slug, { type: 'note', title: 'Huge restamped', compiled_truth: 'Captured body', timeline: '', frontmatter: stored,
source_kind: 'webhook', ingested_via: 'webhook' } as never);
+ await engine.executeRaw("UPDATE pages SET trust_tier = 'unknown' WHERE source_id = 'default' AND slug = $1", [slug]);
+ // An external-tier write is scanned whole, which a 25 MiB body is too large for; the tier is what this test reads.
+ await engine.executeRaw("INSERT INTO config (key, value) VALUES ('write_gate.external_mode', 'off') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value");
const revision = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision;
const line = 'We agreed to ship the review checklist first and revisit pricing next week.\n\n';
const text = `---\ntitle: Huge restamped\nsource_kind: forged-kind\ningested_via: forged-channel\ningested_at: '2020-01-01T00:00:00.000Z'\n---\n\n${line.repeat(Math.ceil(25 * MiB / line.length))}End.`;
@@ -84,11 +88,12 @@ for (const kind of testBackends()) {
catch (error) { if (!(error instanceof OperationError) || error.code !== 'write_pending' || attempt > 40) throw error; }
}
expect(stagedUploadWork.streamed).toBe(streamed + 1);
- const [row] = await engine.executeRaw<{ body_storage: string; frontmatter: Record<string, unknown> | string }>(
- 'SELECT body_storage, frontmatter FROM pages WHERE source_id = $1 AND slug = $2', ['default', slug]);
+ const [row] = await engine.executeRaw<{ body_storage: string; frontmatter: Record<string, unknown> | string; trust_tier: string }>(
+ 'SELECT body_storage, frontmatter, trust_tier FROM pages WHERE source_id = $1 AND slug = $2', ['default', slug]);
expect(row!.body_storage).toBe('segmented');
const frontmatter = typeof row!.frontmatter === 'string' ? JSON.parse(row!.frontmatter) : row!.frontmatter;
expect({ source_kind: frontmatter.source_kind, ingested_via: frontmatter.ingested_via, ingested_at: frontmatter.ingested_at }).toEqual(stored);
+ expect(row!.trust_tier).toBe('external_untrusted');
}, 600_000);
});
}
diff --git a/test/provenance-stamps-7873.test.ts b/test/provenance-stamps-7873.test.ts
index a9114fcadd..dc4b1cb95a 100644
--- a/test/provenance-stamps-7873.test.ts
+++ b/test/provenance-stamps-7873.test.ts
@@ -145,6 +145,14 @@ for (const kind of testBackends()) {
if (repo) expect(ownerPageTrust({ frontmatter: fileFrontmatter(slug), channel: 'sync' }).tier).toBe('external_untrusted');
});
+ test('a remote edit_page that drops a stored stamp is tiered as the page it publishes, not below the gate', async () => {
+ const slug = 'inbox/edit-drop-tier';
+ await seed(slug, { ingested_via: 'webhook' }, 'unknown');
+ await edit(slug, [['ingested_via: webhook\n', ''], ['Captured body', 'Captured body, edited']]);
+ const [row] = await engine.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE source_id = $1 AND slug = $2', ['default', slug]);
+ expect(row!.trust_tier).toBe('external_untrusted');
+ });
+
test('a remote edit_page that strips another lowering marker from an unclassified page does not raise it on re-derive', async () => {
const slug = 'inbox/edit-transcript';
const before = await seed(slug, { transcript_import: { harness: 'third-party-example' } }, 'unknown');