Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): owner-source sync, import, reconcile and file repair declare operator_curated lowered by frontmatter markers and the source default (#5575 A3, CEO-21)
garrytan0623417f0f3a
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.tsindex 6439205fae..93dca03236 100644--- a/src/core/persistence/file-repair.ts+++ b/src/core/persistence/file-repair.ts@@ -38,6 +38,7 @@ import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { ParsedPage } from '../import-file.ts';import { importFromContent } from '../import-file.ts';+import { ownerImportTrust } from '../trust/channel.ts';import { ContentSanityBlockError } from '../content-sanity.ts';import { loadImportSanityConfig, type ContentRefusal, type ImportSanityConfig } from '../import-screen.ts';import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';@@ -301,7 +302,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:const importContent = p.content.replace(/^\uFEFF/, '');const importOptions = { ...source, noEmbed: true, remote: false, preserveGateMarkers: true, activePack: screenConfig.activePack, filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true };return { observedRevision: snapshot?.revision ?? null, noop: ready.noop && !fileChanges && !moved, contentUnchanged: ready.noop && !fileChanges && !moved,- deferEmbedding: p.noEmbed, ...(moved ? { additionalPageKeys: [{ sourceId: row.source_id, slug: moved.slug }] } : {}),+ trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath), deferEmbedding: p.noEmbed, ...(moved ? { additionalPageKeys: [{ sourceId: row.source_id, slug: moved.slug }] } : {}),...(fileChanges ? { file: { root, path: target, content: bytes, expectedBeforeHash: p.beforeHash, ...(fenceRepair ? { commit: fenceRepairCommit(p.path, fenceRepair.classes) } : {}) } } : {}),validate: async tx => {const current = await getWorktreeBinding(tx, row.source_id);diff --git a/src/core/persistence/grandfather.ts b/src/core/persistence/grandfather.tsindex c4c4678138..edc486c1d0 100644--- a/src/core/persistence/grandfather.ts+++ b/src/core/persistence/grandfather.ts@@ -1,3 +1,4 @@+import { withTrustKeep } from './context.ts';import { randomUUID } from 'node:crypto';import { extname } from 'node:path';import type { BrainEngine } from '../engine.ts';@@ -120,9 +121,10 @@ export async function prepareGrandfatherMutation(engine: BrainEngine, row: Write}return { observedRevision: snapshot.revision, file, ...databaseOnlyPublication(row, file), deferEmbedding: true, apply: async tx => {await tx.createVersion(row.slug, { sourceId: row.source_id });- const updated = await tx.executeRaw(`UPDATE pages SET frontmatter=jsonb_set(COALESCE(frontmatter,'{}'::jsonb),'{validate}','false'::jsonb),content_hash=$4+ // A mechanical validate:false stamp authors nothing: the page keeps its trust tier (#5575).+ const updated = await withTrustKeep(tx, ['pages'], () => tx.executeRaw(`UPDATE pages SET frontmatter=jsonb_set(COALESCE(frontmatter,'{}'::jsonb),'{validate}','false'::jsonb),content_hash=$4WHERE id=$1 AND source_id=$2 AND knowledge_revision=$3::uuid AND NOT(COALESCE(frontmatter,'{}'::jsonb)?'validate') RETURNING id`,- [row.page_id, row.source_id, snapshot.revision, hash]);+ [row.page_id, row.source_id, snapshot.revision, hash]));if (updated.length !== 1) {throw opError('revision_conflict', 'The validation decision changed before publication.',`${row.slug} in ${row.source_id} changed while it was being grandfathered, so the transaction rolled back; the next migration run re-plans from current pages.`);diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex e216586a10..1fbcb5f049 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -3,6 +3,7 @@ import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { Page } from '../types.ts';+import { ownerImportTrust } from '../trust/channel.ts';import { importCodeFile, importFromContent, importImageFile, isImageFilePath, MAX_FILE_SIZE, MAX_IMAGE_BYTES } from '../import-file.ts';import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';import { applyInference } from '../frontmatter-inference.ts';@@ -200,7 +201,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri} as Page, tags));const project = code || image ? undefined : await prepareCanonicalProjections(engine, ready.parsedPage!, row.slug, row.source_id, snapshot, 'file');return { observedRevision: ready.observedRevision, noop: ready.noop && p.targetHash === sha256(rendered),- deferEmbedding: image || p.noEmbed, validate: async tx => { await checkPaths(tx); await ready.validate(tx); },+ trust: await ownerImportTrust(engine, row, ready.parsedPage?.frontmatter, p.sourcePath), deferEmbedding: image || p.noEmbed, validate: async tx => { await checkPaths(tx); await ready.validate(tx); },file: { root, path, content: rendered, expectedBeforeHash: p.targetHash },apply: async tx => {await ready.apply(tx);diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.tsindex 27cdeb30bd..7257c02fc8 100644--- a/src/core/persistence/reconcile-prepare.ts+++ b/src/core/persistence/reconcile-prepare.ts@@ -1,3 +1,4 @@+import { ownerImportTrust } from '../trust/channel.ts';import { basename } from 'node:path';import { readFileSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';@@ -137,7 +138,7 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteReconst content = serializePageToMarkdown({ ...state.snapshot.page, ...prepared.result }, prepared.result.tags);const ready = prepared.ready;return {- observedRevision: state.snapshot.revision,+ observedRevision: state.snapshot.revision, trust: await ownerImportTrust(engine, row, prepared.result.frontmatter, state.path),file: { path: state.path, root: state.root, content, expectedBeforeHash: state.pins.raw_file_hash },// A database-only page matched by its slug path always records that file as its origin.noop: ready.noop && sha256(content) === state.pins.raw_file_hash && state.origin === 'recorded',diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 01dadda694..48cfd73ded 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -6,6 +6,7 @@ import type { Page } from '../types.ts';import { OperationError, opError, type OpErrorOpts } from '../ops/contract.ts';import type { Action } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';+import { ownerImportTrust } from '../trust/channel.ts';import { importFromContent, importCodeFile, verifyPageReadable } from '../import-file.ts';import { screenImportContent, screenNormalized, type ContentRefusal, type ImportScreenResult, type ImportSanityConfig } from '../import-screen.ts';import { ContentSanityBlockError } from '../content-sanity.ts';@@ -354,7 +355,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write`A canonical file now occupies the path of page ${row.slug}, written while ${row.source_id} was unbound; neither copy was overwritten. Rename or remove the file and commit, or copy what you need into the page first.`);}if (p.kind === 'managed_sync_delete') return { observedRevision: snapshot?.revision ?? null, noop: !snapshot || snapshot.page.deleted_at != null,- validate, apply: async (tx, preimage) => {+ trust: await ownerImportTrust(engine, row, snapshot?.page.frontmatter, p.sourcePath), validate, apply: async (tx, preimage) => {if (snapshot && snapshot.page.deleted_at == null) { await tx.createVersion(row.slug, preimage ? { ...source, preimage } : source); await tx.softDeletePage(row.slug, source); }await releaseHold(tx);return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };@@ -378,7 +379,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeconst ready = prepared;if (ready.observedRevision !== (snapshot?.revision ?? null)) throw syncPublicationRefusal('revision_conflict', 'The code page changed during preparation.', row, p,`Page ${row.slug} changed while this sync was being prepared.`);- return { observedRevision: ready.observedRevision,+ return { observedRevision: ready.observedRevision, trust: await ownerImportTrust(engine, row, null, p.sourcePath),validate: async tx => { await validate(tx); await ready.validate(tx); },noop: ready.noop, deferEmbedding: true, apply: async tx => {await ready.apply(tx);@@ -462,6 +463,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write// A rename projects against the moved page (same id), so its pinned timeline rows carry over.const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');const preparedImport: PreparedMutation = { observedRevision: snapshot?.revision ?? null,+ trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath),// Tells the #5470 screen the content is unchanged; publication still queues its effects.contentUnchanged: ready.noop && !moved && !writeback,...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),diff --git a/src/core/trust/channel.ts b/src/core/trust/channel.tsindex 116faa8590..50105fb8eb 100644--- a/src/core/trust/channel.ts+++ b/src/core/trust/channel.ts@@ -21,6 +21,7 @@* publication (persistence/coordinator.ts, group-publish.ts); preparers that* know more (sync markers, derivation inputs) declare their own.*/+import type { BrainEngine } from '../engine.ts';import type { WriteRequest } from '../persistence/model.ts';import { CONNECTOR_SOURCE_KINDS } from '../persistence/connector-identity.ts';import {@@ -160,3 +161,16 @@ export function stampTrustMarker(frontmatter: Record<string, unknown>, tier: Truif (prior === marker) return frontmatter;return { ...frontmatter, trust_tier: marker };}++/**+ * The tier of a journaled owner-source write of one page (managed sync,+ * import, reconcile, file repair, grandfather): `ownerPageTrust` from the+ * source's config, capped at agent_written when a remote caller admitted it.+ */+export async function ownerImportTrust(engine: Pick<BrainEngine, 'executeRaw'>, row: Pick<WriteRequest, 'id' | 'source_id' | 'authority' | 'intent' | 'operation'>,+ frontmatter: Record<string, unknown> | null | undefined, sourceUri?: string | null): Promise<WriteTrust> {+ const [source] = await engine.executeRaw<{ config: Record<string, unknown> | string | null }>('SELECT config FROM sources WHERE id = $1', [row.source_id]);+ const config = typeof source?.config === 'string' ? JSON.parse(source.config) as Record<string, unknown> : source?.config ?? null;+ const trust = ownerPageTrust({ frontmatter, sourceConfig: config, channel: requestChannel(row), requestId: row.id, sourceUri });+ return row.authority?.remote === true ? { ...trust, tier: minTrust(trust.tier, 'agent_written') } : trust;+}diff --git a/test/trust-channel-writes.test.ts b/test/trust-channel-writes.test.tsindex 79c1be0206..d0b7031869 100644--- a/test/trust-channel-writes.test.ts+++ b/test/trust-channel-writes.test.ts@@ -14,7 +14,8 @@*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';-import { mkdtempSync, rmSync } from 'node:fs';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -35,6 +36,9 @@ import {frontmatterTrustCaps, ownerPageTrust, requestChannelTrust, sourceDefaultTier, stampTrustMarker,} from '../src/core/trust/channel.ts';import { listTrustProposals } from '../src/core/trust/proposals.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { renderFactsTable } from '../src/core/facts-fence.ts';const engines: BrainEngine[] = [];const home = mkdtempSync(join(tmpdir(), 'gbrain-trust-channel-'));@@ -200,3 +204,60 @@ describe('channel tiers on journaled writes', () => {}}), 90_000);});++describe('owner-source sync tiers and the git round trip (CEO-21)', () => {+ test('owner sync is operator_curated (or the source default); an agent write-through stamps the marker that survives owner edits until the owner deletes it', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const b = await brain(engine);+ const sourceId = `trust-sync-${randomUUID().slice(0, 8)}`;+ const root = join(home, sourceId);+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ const commit = (message: string) => { git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+ const facts = renderFactsTable([{ rowNum: 1, claim: 'Alice works at acme-example', kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true }] as never);+ mkdirSync(join(root, 'people'), { recursive: true }); git('init', '-q');+ writeFileSync(join(root, 'people/alice-example.md'), page('Alice', `Owner profile.\n\n## Facts\n\n${facts}`));+ writeFileSync(join(root, 'people/bob-example.md'), page('Bob', 'Clipped from the web.', 'trust_tier: external_untrusted\n'));+ commit('fixture');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw(`INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')`, [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const sync = () => performManagedSync(engine, { sourceId, noPull: true });+ const tier = async (slug: string) => (await engine.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]?.trust_tier;+ await sync();+ expect(await tier('people/alice-example')).toBe('operator_curated');+ expect(await tier('people/bob-example')).toBe('external_untrusted');+ const [fact] = await engine.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM facts WHERE source_id=$1', [sourceId]);+ expect(fact?.trust_tier).toBe('operator_curated');++ // An agent rewrite through write-through: tier drops and the canonical file carries the marker.+ const local = { ...b.local, sourceId };+ const current = await operationsByName.get_page.handler(local, { slug: 'people/alice-example', include_content: true }) as Record<string, any>;+ await run(local, 'put_page', { slug: 'people/alice-example', content: page('Alice', 'Agent rewrite.'), expected_revision: current.revision });+ expect(await tier('people/alice-example')).toBe('agent_written');+ const path = join(root, 'people/alice-example.md');+ expect(readFileSync(path, 'utf8')).toMatch(/trust_tier: agent_written/);+ git('add', '-A'); try { commit('agent write'); } catch { /* the git effect may already have committed it */ }++ // The owner edits another line and syncs: the marker keeps the page agent_written.+ writeFileSync(path, readFileSync(path, 'utf8').replace('Agent rewrite.', 'Agent rewrite. Owner tweak.'));+ commit('owner edit');+ await sync();+ expect(await tier('people/alice-example')).toBe('agent_written');++ // Deleting the marker by hand is the owner act that restamps the page on the next sync.+ writeFileSync(path, readFileSync(path, 'utf8').replace(/^trust_tier: agent_written\n/m, '').replace(/^source_kind: .*\n/m, '').replace(/^ingested_via: .*\n/m, ''));+ commit('owner removes the marker');+ await sync();+ expect(await tier('people/alice-example')).toBe('operator_curated');++ // sources set-trust: a per-source default below operator_curated applies to the next sync of a changed page.+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(+ `UPDATE sources SET config = config || '{"trust_tier":"tool_observed"}'::jsonb WHERE id=$1`, [sourceId]), TEST_WRITE_ATTRIBUTION));+ writeFileSync(path, readFileSync(path, 'utf8').replace('Owner tweak.', 'Owner tweak again.'));+ commit('mirror edit');+ await sync();+ expect(await tier('people/alice-example')).toBe('tool_observed');+ }+ }), 120_000);+});