Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): agent page writes stamp the lower-only trust_tier marker, fence edits keep the page tier, agent rewrites of higher-tier pages file lower_page proposals (#5575 CEO-12, CEO-21, ENG-1)
garrytan133f415621ed
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 140dd8c697..6ee167e689 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -17,6 +17,7 @@ import { sha256 } from './digest.ts';import { assertPersistenceAccepting, estimatedRetryAfterMs, waitForWrite, writeResponse } from './service.ts';import { parseWireWriteWaitMs } from './write-wait.ts';import { assertTimelineNotOmitted, isTimelineSection, timelineSectionOf, type TimelineSection } from './timeline-omission.ts';+import { contentOriginTier } from '../trust/tier.ts';import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequest, intentDigest, type WriteAdmission } from './journal.ts';import { submissionAuthority, authorizeStoredRequest } from './authority.ts';import { currentVerifiedLocalWriter, localHostId, readLocalWriter, registerLocalWriter, withVerifiedLocalRegistration } from './identity.ts';@@ -208,6 +209,7 @@ export async function preparePageAdmission(ctx: OperationContext,}const { page_batch: _forged, timeline_section: _section, ...params } = input.params;const p: Record<string, unknown> = { ...params, ...parseMutationPrecondition(params) };+ if (p.content_origin !== undefined) contentOriginTier(p.content_origin);if (input.batch) p.page_batch = { id: input.batch.id, index: input.batch.index, size: input.batch.size };const requestId = input.batch ? input.batch.requestId : typeof p.request_id === 'string' ? p.request_id : randomUUID();const sourceId = pageMutationSource(ctx, p, input.operation);diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex be73e048f1..c39ea97197 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -53,6 +53,9 @@ import { pageFencesNormalized } from '../fence-repair/report.ts';import { parseFenceRepairReceipt } from '../fence-repair/receipt.ts';import { fenceRepairCommit } from './effect-model.ts';import { purgePageInTransaction } from './page-purge.ts';+import { withTrustKeep } from './context.ts';+import { isFenceEditWrite, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';+import type { WriteTrust } from '../trust/tier.ts';const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its pending, failed and recovering requests, read-only.`,@@ -352,6 +355,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst { timeline, materialized } = await materializeTimeline(engine,parsed,row.slug,snapshot,writer,timelinePolicy);if (materialized) content = serializePageToMarkdown({...snapshot.page,...parsed,timeline,type:parsed.typeExplicit ? parsed.type : snapshot.page.type},parsed.tags);}+ const storedTier = snapshot ? await storedPageTier(engine, row.source_id, row.slug) : null;// Detect an exact canonical no-op before ingestion can invoke any provider.// Revision/identity checks above still apply to stale identical replacements.if (snapshot && (snapshot.page.deleted_at != null) === targetDeleted && typeof content === 'string') {@@ -367,6 +371,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest}let prepared: PreparedContentImport | undefined;let provenance: CanonicalProvenance | undefined;+ let trust: WriteTrust | undefined;const result = await importFromContent(engine, row.slug, content, {...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient',forceRechunk: row.operation === 'restore_page' || row.operation === 'revert_version',@@ -374,7 +379,11 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestsource_kind: typeof p.source_kind === 'string' ? p.source_kind : null,source_uri: typeof p.source_uri === 'string' ? p.source_uri : null,ingested_via: typeof p.ingested_via === 'string' ? p.ingested_via : null,- prepareFrontmatter: page => { provenance = putProvenance(row, snapshot, page); },+ prepareFrontmatter: page => {+ trust = pageWriteTrust(row, page.frontmatter);+ stampPageTrustMarker(row, page.frontmatter, trust, storedTier);+ provenance = putProvenance(row, snapshot, page);+ },prepare: async value => { prepared = value; return value.result; },}).catch(error => {if (!(error instanceof ContentSanityBlockError)) throw error;@@ -439,12 +448,16 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest// Always-loaded core tier: owner-only marking, brain-wide budget, remote-edit policy (core-guard.ts).const core = noop ? null : await prepareCoreGuard(engine, { row, snapshot, incoming: targetDeleted ? null : ready.parsedPage });return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...await pageDatabaseOnlyPublication(engine, row, file),- ...(core ? { exclusiveSources: core.exclusiveSources } : {}),+ ...(core ? { exclusiveSources: core.exclusiveSources } : {}), ...(trust ? { trust } : {}),validate: async tx => { await ready.validate(tx); await core?.validate(tx); }, apply: async tx => {let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;let removedTimeline: TimelineRowsRemoved | null = null;+ let lowered: { proposal_ref: string } | null = null;if (!noop) {- const applied = await ready.apply(tx);+ const prior = snapshot ? await storedPageTier(tx, row.source_id, row.slug) : null;+ // ENG-1: a managed fence edit keeps the page's tier; CEO-12: an agent rewrite that lowers a page files a queue item.+ const applied = isFenceEditWrite(row) ? await withTrustKeep(tx, ['pages'], () => ready.apply(tx)) : await ready.apply(tx);+ lowered = prior ? await recordAgentPageLowering(tx, row, { tier: prior, revision: snapshot!.revision }) : null;// Mandatory metadata shares publication rollback; exact no-ops never heal it.if (sourcePath && !snapshot?.page.source_path) await tx.executeRaw(`UPDATE pages SET source_path = $1WHERE source_id=$2 AND slug=$3 AND source_path IS NULL`, [sourcePath, row.source_id, row.slug]);@@ -479,7 +492,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped': isEmbedSkipped(ready.parsedPage.frontmatter) || isQuarantined(ready.parsedPage.frontmatter) ? 'embed_skip' : 'empty_body'} : {}),...(row.operation === 'capture' ? { channel: 'capture', content_hash: p.capture_hash } : {}),- ...(edited ? editDiff(row.slug, edited.before, edited.after) : {}), ...fencesNormalized, ...fenceRepairOutcome };+ ...(edited ? editDiff(row.slug, edited.before, edited.after) : {}), ...fencesNormalized, ...fenceRepairOutcome,+ ...(lowered ? { trust_lowered: lowered } : {}) };} };}diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.tsnew file mode 100644index 0000000000..774d25dbbb--- /dev/null+++ b/src/core/trust/page-write.ts@@ -0,0 +1,85 @@+/**+ * Trust on journaled page writes (#5575: A3, CEO-12, CEO-21, ENG-1), used by+ * persistence/page-prepare.ts.+ *+ * - The page's tier is the request's channel tier lowered by the page's own+ * frontmatter markers (they can only lower).+ * - CEO-21: an ordinary content write below operator_curated stamps the+ * lower-only `trust_tier` marker into the frontmatter it publishes, at the+ * lower of the write's tier and the page's stored tier, so the tier survives+ * the git round trip (sync honors it; an owner restamp needs the marker gone).+ * - ENG-1: gbrain-managed fence edits (remember / takes fence appends, proposal+ * accept strikes, loop and relink maintenance) rewrite the page body without+ * authoring it, so the page keeps its stored tier (withTrustKeep); the fence+ * row carries the writer's tier.+ * - CEO-12: an agent write that replaces the body of a higher-tier page lowers+ * the page and files one `lower_page` trust proposal per page (later edits+ * fold into it) with the prior owner version to revert to.+ */+import type { BrainEngine } from '../engine.ts';+import type { WriteRequest } from '../persistence/model.ts';+import { frontmatterTrustCaps, requestChannelTrust, stampTrustMarker } from './channel.ts';+import { insertTrustProposal, updatePendingTrustProposalAfter } from './proposals.ts';+import { compareTrust, effectiveWriteTrust, minTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';++/** Page writes that only edit a gbrain-managed fence (or strike a row) and keep the page's tier. */+const FENCE_EDIT_OPERATIONS = ['remember', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove',+ 'decide_proposal', 'loops_close', 'relink_facts'];+/** Page writes whose caller supplies the page content: they stamp the marker and can lower the page (CEO-12). */+const CONTENT_OPERATIONS = ['put_page', 'capture', 'edit_page', 'revert_version', 'restore_page'];++export function isFenceEditWrite(row: Pick<WriteRequest, 'operation' | 'intent'>): boolean {+ return FENCE_EDIT_OPERATIONS.includes(row.operation) || row.intent?.kind === 'managed_facts_entity';+}++/** The tier of one journaled page write, or undefined when the request's channel declares none. */+export function pageWriteTrust(row: Pick<WriteRequest, 'id' | 'operation' | 'authority' | 'intent'>, frontmatter: Record<string, unknown> | null | undefined): WriteTrust | undefined {+ const channel = requestChannelTrust(row);+ if (!channel || isFenceEditWrite(row)) return channel;+ const caps = frontmatterTrustCaps(frontmatter);+ return caps.length ? effectiveWriteTrust({ channel: channel.tier, lowerTo: caps, origin: channel.origin ?? { channel: row.operation } }) : channel;+}++export async function storedPageTier(engine: BrainEngine, sourceId: string, slug: string): Promise<TrustTier | null> {+ const [row] = await engine.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, slug]);+ return row ? storedTrustTier(row.trust_tier) : null;+}++/** CEO-21: the marker an ordinary content write stamps (in place); `stored` is the page's tier before the write. */+export function stampPageTrustMarker(row: Pick<WriteRequest, 'operation'>, frontmatter: Record<string, unknown>, trust: WriteTrust | undefined, stored: TrustTier | null): void {+ if (!trust || !CONTENT_OPERATIONS.includes(row.operation)) return;+ const tier = stored ? minTrust(trust.tier, stored) : trust.tier;+ const stamped = stampTrustMarker(frontmatter, tier);+ if (stamped !== frontmatter) frontmatter.trust_tier = stamped.trust_tier;+}++/**+ * CEO-12, inside the publication transaction after the page write: when the+ * write lowered a page's tier, file (or refresh) its `lower_page` proposal.+ * `prior` is the tier and revision read under the page lock before the write.+ */+export async function recordAgentPageLowering(tx: BrainEngine, row: Pick<WriteRequest, 'operation' | 'source_id' | 'slug'>,+ prior: { tier: TrustTier; revision: string | null } | null): Promise<{ proposal_ref: string } | null> {+ if (!prior || !CONTENT_OPERATIONS.includes(row.operation)) return null;+ const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ const [page] = snapshot ? await tx.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE id = $1', [snapshot.page.id]) : [];+ if (!snapshot || !page) return null;+ const pageId = Number(snapshot.page.id);+ const after = { tier: storedTrustTier(page.trust_tier), revision: snapshot.revision };+ if (compareTrust(after.tier, prior.tier) >= 0) {+ // A later edit of an already-lowered page folds into its pending item (ENG-22): the revert binds to the newest revision.+ const [pending] = await tx.executeRaw<{ id: number }>(`SELECT id FROM trust_proposals WHERE status = 'pending' AND action = 'lower_page'+ AND target_table = 'pages' AND target_id = $1 LIMIT 1`, [pageId]);+ if (!pending) return null;+ await updatePendingTrustProposalAfter(tx, Number(pending.id), after);+ return { proposal_ref: `tp${pending.id}` };+ }+ const [version] = await tx.executeRaw<{ id: number }>(+ 'SELECT id FROM page_versions WHERE page_id = $1 AND trust_tier = $2 ORDER BY id DESC LIMIT 1', [pageId, prior.tier]);+ const proposal = await insertTrustProposal(tx, {+ action: 'lower_page', sourceId: row.source_id, target: { table: 'pages', id: pageId }, proposer: `agent_page_edit:${row.operation}`,+ before: { slug: row.slug, prior_tier: prior.tier, prior_revision: prior.revision, version_id: version ? Number(version.id) : null }, after,+ });+ if (!proposal.created) await updatePendingTrustProposalAfter(tx, proposal.id, after);+ return { proposal_ref: `tp${proposal.id}` };+}diff --git a/src/core/trust/proposals.ts b/src/core/trust/proposals.tsindex 4c23a30107..bdb4ee3d03 100644--- a/src/core/trust/proposals.ts+++ b/src/core/trust/proposals.ts@@ -148,6 +148,11 @@ export async function pendingTrustProposalsFor(engine: BrainEngine, table: Trustreturn rows.map(normalize);}+/** Refreshes a pending proposal's after state (a later write folded into the same queue item). */+export async function updatePendingTrustProposalAfter(tx: BrainEngine, id: number, after: Record<string, unknown>): Promise<void> {+ await tx.executeRaw(`UPDATE trust_proposals SET after_state = $2::text::jsonb, updated_at = now() WHERE id = $1 AND status = 'pending'`, [id, JSON.stringify(after)]);+}+/** Compare-and-set on status; records the decider and an after state. False when the proposal was not in `from`. */export async function transitionTrustProposal(tx: BrainEngine, id: number, from: TrustProposalStatus, to: TrustProposalStatus,opts: { after?: Record<string, unknown>; decidedBy?: Principal | null } = {}): Promise<boolean> {diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 42a2d26e35..f3e35061aa 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -24,7 +24,7 @@*/import type { Operation } from './operations.ts';-import { WRITE_RECEIPT_SCHEMA, WRITE_REQUEST_PARAM, AGENT_CONTENT_PARAMS } from './persistence/params.ts';+import { WRITE_RECEIPT_SCHEMA, WRITE_REQUEST_PARAM, AGENT_CONTENT_PARAMS, CONTENT_ORIGIN_PARAM } from './persistence/params.ts';import { WRITE_ERROR_CODES } from './persistence/types.ts';/** Frozen protocol version for the MEMORY_VERBS v1 verb set. Single source of truth. */@@ -158,6 +158,10 @@ const remember: Operation = {'Use "world" (default — agents can recall it) or "private" (local CLI reads only).',);}+ if (p.content_origin !== undefined && !CONTENT_ORIGIN_PARAM.enum!.includes(p.content_origin as string)) {+ throw verbError('invalid_params', `content_origin must be one of ${CONTENT_ORIGIN_PARAM.enum!.join(', ')}; got ${JSON.stringify(p.content_origin)}.`,+ 'Pass content_origin as user_said, tool_output (text from a web page, email, file or other tool) or inferred, or omit it.');+ }const replaces = typeof p.replaces === 'string' ? p.replaces.trim() : typeof p.replaces === 'number' ? String(p.replaces) : undefined;if (replaces !== undefined && (!/^\d+$/.test(replaces) || Number(replaces) <= 0)) {throw verbError(diff --git a/test/trust-channel-writes.test.ts b/test/trust-channel-writes.test.tsnew file mode 100644index 0000000000..79c1be0206--- /dev/null+++ b/test/trust-channel-writes.test.ts@@ -0,0 +1,202 @@+/**+ * Channel trust tiers on journaled writes (#5575: A3, CEO-12, CEO-21,+ * CEO-26/DX-8, ENG-1, ENG-18).+ *+ * Protects: remote and local agent writes land agent_written; content_origin+ * tool_output lowers to external_untrusted and an unknown value is+ * invalid_params listing the accepted values; an agent page write stamps the+ * lower-only `trust_tier` frontmatter marker; frontmatter markers lower and+ * never raise; an agent rewrite of a higher-tier page lowers it and files one+ * lower_page trust proposal that later edits fold into; a remember fence+ * append keeps the page's tier while the fact gets the writer's tier; the+ * pure channel and marker rules. Runs on PGLite, and on Postgres when+ * DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { registerLocalWriter, readLocalWriter } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import type { Principal } from '../src/core/persistence/model.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { withCoordinatedWrite, withTrustBackfill } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import {+ frontmatterTrustCaps, ownerPageTrust, requestChannelTrust, sourceDefaultTier, stampTrustMarker,+} from '../src/core/trust/channel.ts';+import { listTrustProposals } from '../src/core/trust/proposals.ts';++const engines: BrainEngine[] = [];+const home = mkdtempSync(join(tmpdir(), 'gbrain-trust-channel-'));+let closePostgres: (() => Promise<void>) | undefined;+const quiet = { info() {}, warn() {}, error() {} };++beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}), 120_000);+afterAll(async () => {+ resetGateway();+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++interface Brain { engine: BrainEngine; sourceId: string; remote: OperationContext; local: OperationContext }+async function brain(engine: BrainEngine): Promise<Brain> {+ const sourceId = `trust-${randomUUID().slice(0, 8)}`;+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ await registerLocalWriter(engine, 'cli');+ const minted = await mintLegacyToken(engine, { name: `token-${sourceId}`, scopes: ['read', 'write'], sourceGrant: [sourceId], takesHolders: ['world'] });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const base = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId, dryRun: false, logger: quiet };+ await readLocalWriter(engine, 'cli');+ return {+ engine, sourceId,+ remote: { ...base, remote: true, transport: 'http', takesHoldersAllowList: ['world'],+ auth: { token: '', clientId: minted.id, principal: { kind: 'legacy_token', id: minted.id } as Principal, sourceId, allowedSources: [sourceId], scopes: ['read', 'write'] } },+ local: { ...base, remote: false },+ } as Brain;+}+const run = (ctx: OperationContext, op: string, params: Record<string, unknown>) =>+ operationsByName[op].handler(ctx, { request_id: randomUUID(), ...params }) as Promise<Record<string, any>>;+const page = (title: string, body: string, extra = '') => `---\ntype: note\ntitle: ${title}\n${extra}---\n${body}\n`;+async function pageRow(b: Brain, slug: string) {+ const [row] = await b.engine.executeRaw<{ trust_tier: string; frontmatter: Record<string, unknown>; id: number; compiled_truth: string }>(+ 'SELECT id, trust_tier, frontmatter, compiled_truth FROM pages WHERE source_id=$1 AND slug=$2', [b.sourceId, slug]);+ return row;+}+/** An owner page: imported, then classified operator_curated through the deterministic backfill seam. */+async function ownerPage(b: Brain, slug: string, body: string) {+ await run(b.local, 'put_page', { slug, content: page('Owner', body) });+ // Lowering to unknown is always allowed; the backfill may then raise unknown to operator_curated (CEO-10).+ await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], async () => {+ await tx.executeRaw(`UPDATE pages SET trust_tier='unknown', frontmatter = frontmatter - 'trust_tier' - 'source_kind' - 'ingested_via' WHERE source_id=$1 AND slug=$2`, [b.sourceId, slug]);+ await withTrustBackfill(tx, () => tx.executeRaw(`UPDATE pages SET trust_tier='operator_curated' WHERE source_id=$1 AND slug=$2`, [b.sourceId, slug]));+ }, TEST_WRITE_ATTRIBUTION));+ return (await pageRow(b, slug))!;+}++describe('channel tier rules (pure)', () => {+ const row = (operation: string, remote: boolean, intent: Record<string, unknown> = {}) =>+ ({ id: 'r1', operation, authority: { remote } as never, intent });+ test('remote and local agent verbs are agent_written; tool_output lowers; connectors are external; owner and derived intents are left to their preparer', () => {+ expect(requestChannelTrust(row('put_page', true))?.tier).toBe('agent_written');+ expect(requestChannelTrust(row('remember', false))?.tier).toBe('agent_written');+ expect(requestChannelTrust(row('capture', true, { content_origin: 'tool_output' }))?.tier).toBe('external_untrusted');+ expect(requestChannelTrust(row('remember', false, { content_origin: 'user_said' }))?.tier).toBe('agent_written');+ expect(requestChannelTrust(row('submit_job', false, { kind: 'connector_v2_google' }))?.tier).toBe('external_untrusted');+ expect(requestChannelTrust(row('submit_job', false, { kind: 'managed_sync_batch' }))).toBeUndefined();+ expect(requestChannelTrust(row('put_page', false, { kind: 'managed_file_import' }))).toBeUndefined();+ expect(requestChannelTrust(row('put_page', true))?.origin?.channel).toBe('mcp:put_page');+ });+ test('frontmatter markers only lower; sources set-trust never exceeds operator_curated; connector sources are external', () => {+ expect(frontmatterTrustCaps({ trust_tier: 'agent_written' })).toEqual(['agent_written']);+ expect(frontmatterTrustCaps({ source_kind: 'mcp:put_page' })).toEqual(['agent_written']);+ expect(frontmatterTrustCaps({ source_kind: 'webhook' })).toEqual(['external_untrusted']);+ expect(frontmatterTrustCaps({ transcript_import: { harness: 'claude-code' } })).toEqual(['agent_written']);+ expect(frontmatterTrustCaps({ transcript_import: { harness: 'meeting-vendor' } })).toEqual(['external_untrusted']);+ expect(frontmatterTrustCaps({ source_url: 'https://acme-example.com/a', clipped_at: '2026-01-01' })).toEqual(['external_untrusted']);+ expect(ownerPageTrust({ frontmatter: { trust_tier: 'user_confirmed' }, channel: 'sync' }).tier).toBe('operator_curated');+ expect(ownerPageTrust({ frontmatter: {}, channel: 'sync' }).tier).toBe('operator_curated');+ expect(ownerPageTrust({ frontmatter: { trust_tier: 'agent_written' }, channel: 'sync' }).tier).toBe('agent_written');+ expect(ownerPageTrust({ frontmatter: {}, sourceConfig: { kind: 'google' }, channel: 'sync' }).tier).toBe('external_untrusted');+ expect(sourceDefaultTier({ trust_tier: 'user_confirmed' })).toBe('operator_curated');+ expect(sourceDefaultTier({ trust_tier: 'tool_observed' })).toBe('tool_observed');+ expect(stampTrustMarker({}, 'operator_curated')).toEqual({});+ expect(stampTrustMarker({ trust_tier: 'external_untrusted' }, 'agent_written')).toEqual({ trust_tier: 'external_untrusted' });+ expect(stampTrustMarker({ trust_tier: 'agent_written' }, 'external_untrusted')).toEqual({ trust_tier: 'external_untrusted' });+ });+});++describe('channel tiers on journaled writes', () => {+ test('agent page writes are agent_written and stamp the lower-only marker; tool_output lowers to external_untrusted', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const b = await brain(engine);+ await run(b.remote, 'put_page', { slug: 'notes/remote-example', content: page('Remote', 'From an agent.') });+ const remote = await pageRow(b, 'notes/remote-example');+ expect(remote.trust_tier).toBe('agent_written');+ expect(remote.frontmatter.trust_tier).toBe('agent_written');+ await run(b.local, 'put_page', { slug: 'notes/tool-example', content: page('Tool', 'Pasted web text.'), content_origin: 'tool_output' });+ const tool = await pageRow(b, 'notes/tool-example');+ expect(tool.trust_tier).toBe('external_untrusted');+ expect(tool.frontmatter.trust_tier).toBe('external_untrusted');+ // A hand-typed raising marker is ignored: content cannot claim owner tiers.+ await run(b.local, 'put_page', { slug: 'notes/claims-example', content: page('Claims', 'Claims to be confirmed.', 'trust_tier: user_confirmed\n') });+ expect((await pageRow(b, 'notes/claims-example')).trust_tier).toBe('agent_written');+ }+ }), 60_000);++ test('an unknown content_origin is invalid_params listing the accepted values, on remember and put_page', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const b = await brain(engines[0]!);+ const failure = async (p: Promise<unknown>) => { try { await p; return null; } catch (e) { return e as { code?: string; message: string }; } };+ const remember = await failure(run(b.local, 'remember', { fact: 'Prefers tea', provenance: 'chat', content_origin: 'web' }));+ expect(remember?.code).toBe('invalid_params');+ expect(remember?.message).toContain('user_said, tool_output, inferred');+ const put = await failure(run(b.local, 'put_page', { slug: 'notes/x-example', content: page('X', 'y'), content_origin: 'web' }));+ expect(put?.code).toBe('invalid_params');+ expect(put?.message).toContain('user_said, tool_output, inferred');+ }), 60_000);++ test('remember: the fact is agent_written (external with tool_output); a fence append keeps the owner page tier (ENG-1)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const b = await brain(engine);+ const owner = await ownerPage(b, 'people/alice-example', 'Alice is a person.');+ expect(owner.trust_tier).toBe('operator_curated');+ const saved = await run(b.local, 'remember', { fact: 'Alice prefers green tea', provenance: 'chat', entity: 'people/alice-example' });+ const [fact] = await engine.executeRaw<{ trust_tier: string; write_origin: Record<string, unknown> | string }>('SELECT trust_tier, write_origin FROM facts WHERE id=$1', [Number(saved.id)]);+ expect(fact.trust_tier).toBe('agent_written');+ const fenced = await pageRow(b, 'people/alice-example');+ expect(fenced.compiled_truth).toContain('Alice prefers green tea');+ expect(fenced.trust_tier).toBe('operator_curated');+ const tool = await run(b.remote, 'remember', { fact: 'Alice moved to acme-example', provenance: 'email', entity: 'people/alice-example', content_origin: 'tool_output' });+ const [external] = await engine.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM facts WHERE id=$1', [Number(tool.id)]);+ expect(external.trust_tier).toBe('external_untrusted');+ expect(await listTrustProposals(engine, { sourceId: b.sourceId, action: 'lower_page' })).toHaveLength(0);+ }+ }), 60_000);++ test('CEO-12: an agent rewrite of an owner page lowers it and files one lower_page proposal that later edits fold into', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const b = await brain(engine);+ const slug = 'notes/owner-example';+ const owner = await ownerPage(b, slug, 'My own notes.');+ const first = await run(b.remote, 'put_page', { slug, content: page('Owner', 'Rewritten by an agent.'), force: true });+ expect(first.trust_lowered?.proposal_ref).toMatch(/^tp\d+$/);+ expect((await pageRow(b, slug)).trust_tier).toBe('agent_written');+ const [proposal] = await listTrustProposals(engine, { sourceId: b.sourceId, action: 'lower_page' });+ expect(proposal).toMatchObject({ target_table: 'pages', target_id: owner.id, status: 'pending' });+ expect(proposal!.before_state).toMatchObject({ slug, prior_tier: 'operator_curated' });+ expect(typeof proposal!.before_state.version_id).toBe('number');+ const [version] = await engine.executeRaw<{ trust_tier: string; compiled_truth: string }>('SELECT trust_tier, compiled_truth FROM page_versions WHERE id=$1', [proposal!.before_state.version_id]);+ expect(version).toMatchObject({ trust_tier: 'operator_curated' });+ expect(version!.compiled_truth).toContain('My own notes.');+ const second = await run(b.remote, 'put_page', { slug, content: page('Owner', 'Edited again.'), force: true });+ expect(second.trust_lowered?.proposal_ref).toBe(first.trust_lowered.proposal_ref);+ const all = await listTrustProposals(engine, { sourceId: b.sourceId, action: 'lower_page' });+ expect(all).toHaveLength(1);+ expect(all[0]!.after_state.revision).toBe(second.revision);+ // An external page edited by an agent stays external: min(prior, writer), no queue item.+ await run(b.local, 'put_page', { slug: 'notes/web-example', content: page('Web', 'Clipped.'), content_origin: 'tool_output' });+ await run(b.remote, 'put_page', { slug: 'notes/web-example', content: page('Web', 'Clipped. '), force: true });+ expect((await pageRow(b, 'notes/web-example')).trust_tier).toBe('external_untrusted');+ expect(await listTrustProposals(engine, { sourceId: b.sourceId, action: 'lower_page' })).toHaveLength(1);+ }+ }), 90_000);+});