Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(trust): tier vocabulary, trigger/seam/guard on both engines, confirm/scope/floors, backfill and doctor (#5575 lane F)
garrytanf6aa0e7cf728
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txtindex 515f295a91..93bdf328d5 100644--- a/scripts/e2e-backend-matrix.txt+++ b/scripts/e2e-backend-matrix.txt@@ -55,3 +55,4 @@ test/e2e/mentions-parity.test.tstest/e2e/persistence-publish-lock-order-postgres.test.tstest/e2e/p8-memory-writes-postgres.test.tstest/e2e/delta-cursor-integrity-postgres.test.ts+test/e2e/trust-tier-postgres.test.tsdiff --git a/test/e2e/trust-backfill-postgres.test.ts b/test/e2e/trust-backfill-postgres.test.tsnew file mode 100644index 0000000000..851e1ad5d9--- /dev/null+++ b/test/e2e/trust-backfill-postgres.test.ts@@ -0,0 +1,5 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++// `gbrain trust backfill` and doctor `trust_tiers` (#5575) on Postgres: the+// read-only dry run, the coordinated apply on a managed brain and the JSONB origin.+await registerPostgresTests(() => import('../trust-backfill.test.ts'));diff --git a/test/e2e/trust-tier-postgres.test.ts b/test/e2e/trust-tier-postgres.test.tsnew file mode 100644index 0000000000..f83ce7c042--- /dev/null+++ b/test/e2e/trust-tier-postgres.test.ts@@ -0,0 +1,6 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++// Memory trust tiers (#5575) on Postgres: the tier trigger, the attribution-seam+// settings and the write_origin JSONB binding, direct and through transaction-mode+// PgBouncer (scripts/e2e-backend-matrix.txt).+await registerPostgresTests(() => import('../trust-tier-schema.test.ts'));diff --git a/test/scope.test.ts b/test/scope.test.tsindex dd7943361e..f0416da569 100644--- a/test/scope.test.ts+++ b/test/scope.test.ts@@ -134,7 +134,7 @@ describe('F3 refresh-token subset semantics under hasScope', () => {describe('ALLOWED_SCOPES — exact list pinned', () => {test('contains the 6 canonical scopes (v0.38: agent added)', () => {- expect(ALLOWED_SCOPES.size).toBe(9);+ expect(ALLOWED_SCOPES.size).toBe(10);expect(ALLOWED_SCOPES.has('read')).toBe(true);expect(ALLOWED_SCOPES.has('write')).toBe(true);expect(ALLOWED_SCOPES.has('admin')).toBe(true);@@ -144,11 +144,13 @@ describe('ALLOWED_SCOPES — exact list pinned', () => {expect(ALLOWED_SCOPES.has('skill_editor')).toBe(true);expect(ALLOWED_SCOPES.has('skill_publisher')).toBe(true);expect(ALLOWED_SCOPES.has('skills_member_self')).toBe(true);+ expect(ALLOWED_SCOPES.has('memory_confirm')).toBe(true);});test('list is sorted alphabetically (deterministic for wire/drift check)', () => {expect([...ALLOWED_SCOPES_LIST]).toEqual(['admin','agent',+ 'memory_confirm','read','skill_editor','skill_publisher',@@ -242,10 +244,10 @@ describe('scopesSupportedForDiscovery', () => {test('DCR on: exactly the self-registration ceiling, in ALLOWED_SCOPES_LIST order', () => {expect(scopesSupportedForDiscovery({ enableDcr: true })).toEqual(['read', 'write']);});- test('DCR off: every scope except operator-only agent (the pre-ceiling advertisement)', () => {+ test('DCR off: every scope except operator-only agent and local-CLI-only memory_confirm (the pre-ceiling advertisement)', () => {const list = scopesSupportedForDiscovery({ enableDcr: false });expect(list).toEqual(['admin', 'read', 'skill_editor', 'skill_publisher', 'skills_member_self', 'sources_admin', 'users_admin', 'write']);- expect(list).toEqual(ALLOWED_SCOPES_LIST.filter((s) => s !== 'agent'));+ expect(list).toEqual(ALLOWED_SCOPES_LIST.filter((s) => s !== 'agent' && s !== 'memory_confirm'));});test('neither list advertises agent (delegation bindings are operator-only)', () => {expect(scopesSupportedForDiscovery({ enableDcr: true })).not.toContain('agent');diff --git a/test/trust-backfill.test.ts b/test/trust-backfill.test.tsnew file mode 100644index 0000000000..c5298adfcb--- /dev/null+++ b/test/trust-backfill.test.ts@@ -0,0 +1,223 @@+/**+ * `gbrain trust backfill` and doctor `trust_tiers` (#5575: A8, CEO-10, CEO-17,+ * CEO-25, DX-5).+ *+ * Protects: legacy rows are classified from deterministic signals only+ * (connector source, pages.source_kind, transcript/extraction/dream+ * provenance, facts and takes source tags, the page a row lives on, and the+ * journaled request through write_request_id, one class per operation),+ * rows with no signal stay unknown and nothing becomes user_confirmed; the dry+ * run is strictly read-only, matches what an apply writes, reports counts by+ * table x tier and the share at agent_written or below, and works on a schema+ * without the trust columns; an apply resumes from its op_checkpoints cursor+ * and runs inside the coordinator on a managed brain; doctor warns with a+ * `run` fix until a backfill completes. Fails if a signal maps to the wrong+ * tier, a dry run writes anything, or the doctor fix stops naming the command.+ * Runs on PGLite, and on Postgres through test/e2e/trust-backfill-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { readTrustBackfillState, runTrustBackfill, TRUST_BACKFILL_COMPLETED_KEY } from '../src/core/trust/backfill.ts';+import { withWriteAttribution } from '../src/core/persistence/context.ts';+import { trustTiersEntry } from '../src/commands/doctor/checks/trust-tiers.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';+import { renderAction } from '../src/core/agent-output.ts';++interface Backend { name: string; engine: BrainEngine; close: () => Promise<void> }+const backends: Backend[] = [];+beforeAll(async () => {+ for (const name of testBackends()) {+ if (name === 'pglite') {+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ backends.push({ name, engine, close: () => engine.disconnect() });+ } else {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ backends.push({ name, engine: pg.engine, close: pg.close });+ }+ }+}, 180_000);+afterAll(async () => { for (const b of backends) await b.close(); });++const quiet = () => {};+const REQUEST = `principal_kind, principal_id, request_id, operation, source_id, source_incarnation, slug, digest, authority, intent,+ intent_bytes, terminal_reservation, state, outcome`;++/** Fresh fixture rows (all `unknown`): one per signal class, in a source of their own, plus a connector source. */+async function seed(engine: BrainEngine) {+ const tag = randomUUID().slice(0, 8);+ const src = `bf-${tag}`, connector = `bf-gh-${tag}`;+ await engine.executeRaw(`INSERT INTO sources(id,name) VALUES($1,$1)`, [src]);+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES($1,$1,'{"kind":"github"}'::jsonb)`, [connector]);+ const pages: Record<string, number> = {};+ const addPage = async (key: string, source: string, sourceKind: string | null, frontmatter: Record<string, unknown> = {}) => {+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO pages(slug,type,title,compiled_truth,source_id,source_kind,frontmatter)+ VALUES($1,'note','T','body',$2,$3,$4::text::jsonb) RETURNING id`, [`p/${key}`, source, sourceKind, JSON.stringify(frontmatter)]);+ pages[key] = Number(row!.id);+ };+ await addPage('webhook', src, 'webhook');+ await addPage('mcp', src, 'mcp:put_page');+ await addPage('dream', src, null, { dream_generated: true });+ await addPage('transcript', src, null, { transcript_import: { harness: 'codex', session_id: 's1' } });+ await addPage('extracted', src, null, { provenance: 'auto-extracted' });+ await addPage('plain', src, null);+ await addPage('connector', connector, null);++ const [incarnation] = await engine.executeRaw<{ i: string }>('SELECT incarnation::text AS i FROM sources WHERE id=$1', [src]);+ const request = async (operation: string, intent: Record<string, unknown> | null, remote: boolean) => {+ const [row] = await engine.executeRaw<{ id: string }>(`INSERT INTO persistence_requests (${REQUEST})+ VALUES('local_cli','cli:example',gen_random_uuid(),$1,$2,$3::uuid,'p/x','d',$4::text::jsonb,$5::text::jsonb,1,16384,'committed','{}'::jsonb) RETURNING id::text AS id`,+ [operation, src, incarnation!.i, JSON.stringify({ version: 1, remote, sourceId: src }), intent === null ? null : JSON.stringify(intent)]);+ return row!.id;+ };+ const facts: Record<string, number> = {};+ const addFact = async (key: string, opts: { source?: string; fenced?: string; requestId?: string; sourceId?: string } = {}) => {+ const insert = (db: BrainEngine) => db.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,entity_slug,fact,kind,source,source_markdown_slug,row_num)+ VALUES($1,'e',$2,'fact',$3,$4,$5) RETURNING id`, [opts.sourceId ?? src, `claim ${key}`, opts.source ?? 'manual', opts.fenced ?? null, opts.fenced ? 1 : null]);+ const rows = opts.requestId+ ? await engine.transaction(tx => withWriteAttribution(tx, { requestId: opts.requestId!, principal: { kind: 'local_cli', id: 'cli:example' } }, () => insert(tx)))+ : await insert(engine);+ facts[key] = Number(rows[0]!.id);+ };+ await addFact('sync_request', { requestId: await request('submit_job', { kind: 'managed_sync_import' }, false) });+ await addFact('put_page_request', { requestId: await request('put_page', {}, false) });+ await addFact('remote_request', { requestId: await request('remember', {}, true) });+ await addFact('connector_request', { requestId: await request('submit_job', { kind: 'connector_v2_items' }, false) });+ await addFact('other_request', { requestId: await request('loops_close', { kind: 'retire_loop_fact' }, false) });+ await addFact('compacted_request', { requestId: await request('put_page', null, false) });+ await addFact('lane', { source: 'hook:writeback' });+ await addFact('fenced_external', { fenced: 'p/webhook' });+ await addFact('plain');+ await addFact('connector', { sourceId: connector });+ const [take] = await engine.executeRaw<{ id: number }>(`INSERT INTO takes(page_id,row_num,claim,kind,holder,weight,source) VALUES($1,1,'c','take','world',0.5,'take_proposals#7') RETURNING id`, [pages.plain]);+ const [entry] = await engine.executeRaw<{ id: number }>(`INSERT INTO timeline_entries(page_id,date,summary,detail,source) VALUES($1,'2026-01-01','s','d','x') RETURNING id`, [pages.webhook]);+ return { src, connector, pages, facts, take: Number(take!.id), entry: Number(entry!.id) };+}+type Fixture = Awaited<ReturnType<typeof seed>>;+const EXPECTED_PAGES = { webhook: 'external_untrusted', mcp: 'agent_written', dream: 'agent_written', transcript: 'agent_written', extracted: 'agent_written', plain: 'unknown', connector: 'external_untrusted' };+const EXPECTED_FACTS = {+ sync_request: 'operator_curated', put_page_request: 'agent_written', remote_request: 'agent_written', connector_request: 'external_untrusted',+ other_request: 'unknown', compacted_request: 'unknown', lane: 'agent_written', fenced_external: 'external_untrusted', plain: 'unknown', connector: 'external_untrusted',+};+async function tiers(engine: BrainEngine, f: Fixture) {+ const read = async (table: string, ids: Record<string, number>) => {+ const rows = await engine.executeRaw<{ id: number; t: string }>(`SELECT id, trust_tier AS t FROM ${table} WHERE id = ANY($1::bigint[])`, [Object.values(ids)]);+ const byId = new Map(rows.map(r => [Number(r.id), r.t]));+ return Object.fromEntries(Object.entries(ids).map(([k, id]) => [k, byId.get(id)]));+ };+ return { pages: await read('pages', f.pages), facts: await read('facts', f.facts), take: (await read('takes', { t: f.take })).t, entry: (await read('timeline_entries', { e: f.entry })).e };+}+/** Everything a dry run could have written: tiers, origins, checkpoints and config. */+async function writableState(engine: BrainEngine) {+ const [row] = await engine.executeRaw<{ s: string }>(`SELECT md5(concat(+ (SELECT string_agg(id || trust_tier || COALESCE(write_origin::text,''), ',' ORDER BY id) FROM pages),+ (SELECT string_agg(id || trust_tier || COALESCE(write_origin::text,''), ',' ORDER BY id) FROM facts),+ (SELECT string_agg(id || trust_tier, ',' ORDER BY id) FROM takes),+ (SELECT string_agg(id || trust_tier, ',' ORDER BY id) FROM timeline_entries),+ (SELECT string_agg(op || fingerprint || completed_keys::text, ',' ORDER BY op, fingerprint) FROM op_checkpoints),+ (SELECT string_agg(key || value, ',' ORDER BY key) FROM config))) AS s`);+ return row!.s;+}+const resetTrust = (engine: BrainEngine) => engine.transaction(async tx => {+ await tx.executeRaw('SET LOCAL session_replication_role = replica');+ for (const table of ['pages', 'facts', 'takes', 'timeline_entries']) await tx.executeRaw(`UPDATE ${table} SET trust_tier='unknown', write_origin=NULL`);+ await tx.executeRaw(`DELETE FROM op_checkpoints WHERE op='trust-backfill'`);+ await tx.executeRaw(`DELETE FROM config WHERE key=$1`, [TRUST_BACKFILL_COMPLETED_KEY]);+});+const doctor = async (engine: BrainEngine) => (await trustTiersEntry.run({ engine } as unknown as DoctorContext) as Check[])[0]!;++for (const backendName of testBackends()) {+ const engineOf = () => backends.find(b => b.name === backendName)!.engine;++ describe(`trust backfill (${backendName})`, () => {+ test('classifies each signal class; the read-only dry run projects exactly what the apply writes', async () => {+ const engine = engineOf();+ await resetTrust(engine);+ const f = await seed(engine);+ const before = await writableState(engine);+ const preview = await runTrustBackfill(engine, { dryRun: true, batchSize: 3 });+ expect(await writableState(engine)).toBe(before);+ expect(preview).toMatchObject({ mode: 'dry_run', schema: 'trust_columns', status: 'complete' });+ expect(preview.tables.map(t => t.table)).toEqual(['pages', 'facts', 'takes', 'timeline_entries']);+ expect(preview.projected.user_confirmed).toBe(0);+ expect(preview.signals).toEqual(expect.arrayContaining(['connector_source', 'pages_source_kind', 'frontmatter_provenance', 'facts_source_lane', 'write_request']));++ const doc = await doctor(engine);+ expect(doc.status).toBe('warn');+ const fix = renderAction(doc.fix!, { transport: 'cli', isCallable: () => false, preapproved: () => true });+ expect({ next: fix.next, argv: fix.argv }).toEqual({ next: 'run', argv: ['gbrain', 'trust', 'backfill'] });++ const applied = await runTrustBackfill(engine, { log: quiet, batchSize: 4 });+ expect(await tiers(engine, f)).toEqual({ pages: EXPECTED_PAGES, facts: EXPECTED_FACTS, take: 'agent_written', entry: 'external_untrusted' });+ for (const t of applied.tables) expect({ table: t.table, counts: t.projected }).toEqual({ table: t.table, counts: preview.tables.find(p => p.table === t.table)!.projected });+ const low = preview.projected.agent_written + preview.projected.unknown + preview.projected.external_untrusted;+ expect(preview.at_or_below_agent_written).toBe(low);+ expect(preview.at_or_below_agent_written_pct).toBe(Math.round((low / preview.rows) * 10_000) / 100);+ const [origin] = await engine.executeRaw<{ o: unknown }>('SELECT write_origin AS o FROM pages WHERE id=$1', [f.pages.webhook]);+ expect(origin!.o).toEqual({ channel: 'trust_backfill' });+ expect((await doctor(engine)).status).toBe('ok');+ expect(await runTrustBackfill(engine, { log: quiet })).toMatchObject({ tables: expect.arrayContaining([expect.objectContaining({ table: 'facts', updated: 0 })]) });+ const chunkColumns = await engine.executeRaw(`SELECT 1 FROM information_schema.columns WHERE table_name='content_chunks' AND column_name='trust_tier'`);+ expect(chunkColumns).toHaveLength(0);+ });++ test('--resume continues from the stored cursor; without it every unknown row is scanned', async () => {+ const engine = engineOf();+ await resetTrust(engine);+ const f = await seed(engine);+ const cursor = Math.max(...Object.values(f.pages));+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('trust-backfill','v1',$1::text::jsonb)`, [JSON.stringify([{ pages: cursor }])]);+ expect(await readTrustBackfillState(engine)).toMatchObject({ interrupted: true });+ const doc = await doctor(engine);+ expect(renderAction(doc.fix!, { transport: 'cli', isCallable: () => false, preapproved: () => true }).argv).toEqual(['gbrain', 'trust', 'backfill', '--resume']);+ await runTrustBackfill(engine, { resume: true, log: quiet });+ expect((await tiers(engine, f)).pages.webhook).toBe('unknown');+ expect((await tiers(engine, f)).facts.lane).toBe('agent_written');+ expect(await readTrustBackfillState(engine)).toMatchObject({ interrupted: false });+ await runTrustBackfill(engine, { log: quiet });+ expect((await tiers(engine, f)).pages.webhook).toBe('external_untrusted');+ });++ test('runs inside the coordinator on a managed brain', async () => {+ const engine = engineOf();+ await resetTrust(engine);+ const f = await seed(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ await expect(engine.executeRaw(`UPDATE pages SET trust_tier='external_untrusted' WHERE id=$1`, [f.pages.webhook])).rejects.toThrow(/writer_coordinator_required/);+ await runTrustBackfill(engine, { log: quiet, batchSize: 2 });+ } finally {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ expect(await tiers(engine, f)).toMatchObject({ pages: EXPECTED_PAGES, facts: EXPECTED_FACTS });+ });+ });+}++describe('trust backfill dry run before the trust migration', () => {+ test('classifies from existing columns only and writes nothing', async () => {+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ try {+ const f = await seed(engine);+ for (const table of ['facts', 'takes', 'timeline_entries', 'pages']) await engine.executeRaw(`ALTER TABLE ${table} DROP COLUMN trust_tier CASCADE, DROP COLUMN write_origin`);+ const [before] = await engine.executeRaw<{ n: number }>(`SELECT (SELECT count(*) FROM op_checkpoints) + (SELECT count(*) FROM config) AS n`);+ const report = await runTrustBackfill(engine, { dryRun: true });+ const [after] = await engine.executeRaw<{ n: number }>(`SELECT (SELECT count(*) FROM op_checkpoints) + (SELECT count(*) FROM config) AS n`);+ expect(Number(after!.n)).toBe(Number(before!.n));+ expect(report.schema).toBe('pre_trust');+ expect(report.tables.every(t => t.current === undefined)).toBe(true);+ expect(report.projected).toEqual({ user_confirmed: 0, operator_curated: 1, tool_observed: 0, agent_written: 8, unknown: 4, external_untrusted: 6 });+ expect(report.rows).toBe(Object.keys(f.pages).length + Object.keys(f.facts).length + 2);+ expect((await doctor(engine)).details).toEqual({ schema: 'pre_trust' });+ await expect(runTrustBackfill(engine, { log: quiet })).rejects.toMatchObject({ code: 'migrations_pending' });+ } finally {+ await engine.disconnect();+ }+ }, 120_000);+});diff --git a/test/trust-confirm-scope.test.ts b/test/trust-confirm-scope.test.tsnew file mode 100644index 0000000000..7c2977be0c--- /dev/null+++ b/test/trust-confirm-scope.test.ts@@ -0,0 +1,217 @@+/**+ * The owner-confirmation capability for memory trust (#5575: CEO-6, CEO-9,+ * CEO-14, CEO-18, DX-3, ENG-15).+ *+ * Protects: `memory_confirm` implies only itself, admin never implies it, it+ * is never DCR-registrable or advertised in discovery (both modes), never in a+ * grant profile, never on a grandfathered null-scope token, and every admin+ * HTTP mint surface refuses it while the local CLI mints it; the typed-token+ * TTY confirmation (the user types the ref, not y/N) through the isInteractive+ * seam's test override; `--yes` never confirms and tier-raising fixes are+ * `tell_user_to_run`; the per-token `min_trust` floor reaches+ * `AuthInfo.minTrust` on both legacy tokens and OAuth clients and is changed+ * only through the local `auth set-min-trust` path. Fails if admin starts+ * implying the scope, a mint path accepts it remotely, a y/N answer or+ * piped input confirms, or the floor drops out of token verification.+ * PGLite only (the verify path's SQL is shared with Postgres and covered by+ * the OAuth suites).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PassThrough } from 'node:stream';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ ALLOWED_SCOPES, dcrScopeViolation, hasScope, localCliOnlyScopeViolation, normalizeScopesInput, scopesSupportedForDiscovery,+} from '../src/core/scope.ts';+import { GRANT_PROFILES, grantFromTokenRow } from '../src/core/grants/model.ts';+import { resolveGrantProfile } from '../src/core/grants/profiles.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { generateToken, hashToken } from '../src/core/utils.ts';+import { parseApiKeyMintRequest } from '../src/commands/serve-http-api-keys.ts';+import { parseAuthCreateArgs } from '../src/commands/auth.ts';+import { renderAction } from '../src/core/agent-output.ts';+import { OperationError, type AuthInfo, type OperationContext } from '../src/core/ops/contract.ts';+import {+ __setConfirmationIoForTests, promptTypedConfirmation, requireOwnerConfirmation, tierRaiseFix, type ConfirmationTarget,+} from '../src/core/trust/confirm.ts';+import { setMinTrust, setTokenMinTrust } from '../src/core/trust/min-trust.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);+afterAll(async () => {+ __setConfirmationIoForTests(null);+ await engine.disconnect();+});++describe('memory_confirm scope (CEO-6)', () => {+ test('implies only itself; admin and write never imply it', () => {+ expect(ALLOWED_SCOPES.has('memory_confirm')).toBe(true);+ expect(hasScope(['admin'], 'memory_confirm')).toBe(false);+ expect(hasScope(['admin', 'agent', 'write'], 'memory_confirm')).toBe(false);+ expect(hasScope(['memory_confirm'], 'memory_confirm')).toBe(true);+ expect(hasScope(['memory_confirm'], 'read')).toBe(false);+ });++ test('never advertised in discovery, in either DCR mode', () => {+ expect(scopesSupportedForDiscovery({ enableDcr: true })).not.toContain('memory_confirm');+ expect(scopesSupportedForDiscovery({ enableDcr: false })).not.toContain('memory_confirm');+ });++ test('dynamic registration refuses it with the local command', () => {+ for (const grants of [['authorization_code'], ['client_credentials']]) {+ const violation = dcrScopeViolation(['read', 'memory_confirm'], grants);+ expect(violation).toContain('memory_confirm');+ expect(violation).toContain('gbrain auth create');+ }+ });++ test('the admin HTTP normalizer refuses it; plain scopes still pass', () => {+ expect(() => normalizeScopesInput('read memory_confirm')).toThrow(/local CLI/);+ expect(() => normalizeScopesInput(['memory_confirm'])).toThrow(/local CLI/);+ expect(normalizeScopesInput('write read')).toBe('read write');+ expect(localCliOnlyScopeViolation(['read', 'write', 'admin'])).toBeNull();+ });++ test('admin API key minting refuses it with a user-run fix', async () => {+ try { await parseApiKeyMintRequest(engine, { name: 'k', scopes: ['read', 'memory_confirm'] }); throw new Error('accepted'); }+ catch (e) {+ expect((e as OperationError).code).toBe('invalid_params');+ expect((e as OperationError).fix?.argv).toContain('read,write,memory_confirm');+ expect((e as OperationError).fix?.actor).toBe('user');+ }+ });++ test('no grant profile carries it', () => {+ for (const profile of GRANT_PROFILES) {+ const patch = resolveGrantProfile({ profile, sourceId: 'default', boundTools: ['search'], boundSlugPrefixes: ['wiki/agents/'] });+ expect({ profile, confirm: hasScope(patch.scopes ?? [], 'memory_confirm') }).toEqual({ profile, confirm: false });+ }+ });++ test('a grandfathered null-scope token never holds it', () => {+ const grant = grantFromTokenRow({ id: randomUUID(), scopes: null, permissions: null, source_grant: null });+ expect(grant.scopes).toEqual(['read', 'write', 'admin']);+ expect(hasScope(grant.scopes, 'memory_confirm')).toBe(false);+ });++ test('the local CLI mints it explicitly, and verification carries it', async () => {+ const minted = await mintLegacyToken(engine, { name: `confirm-${randomUUID().slice(0, 6)}`, scopes: ['read', 'write', 'memory_confirm'], takesHolders: ['world'] });+ const auth = await provider().verifyAccessToken(minted.token) as unknown as AuthInfo;+ expect(hasScope(auth.scopes, 'memory_confirm')).toBe(true);+ });+});++const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });++describe('per-token min_trust floor (CEO-18)', () => {+ test('auth create parses --min-trust and refuses a non-tier', () => {+ expect(parseAuthCreateArgs(['bot', '--scopes', 'read', '--min-trust', 'agent_written'])).toEqual({ name: 'bot', scopes: ['read'], minTrust: 'agent_written' });+ expect(parseAuthCreateArgs(['bot', '--min-trust', 'high']).error).toContain('agent_written');+ expect(parseAuthCreateArgs(['bot']).minTrust).toBeUndefined();+ });++ test('a legacy token floor reaches AuthInfo.minTrust; none leaves it undefined', async () => {+ const minted = await mintLegacyToken(engine, { name: `floor-${randomUUID().slice(0, 6)}`, scopes: ['read'], takesHolders: ['world'] });+ expect((await provider().verifyAccessToken(minted.token) as unknown as AuthInfo).minTrust).toBeUndefined();+ await setTokenMinTrust(engine, minted.id, 'tool_observed');+ expect((await provider().verifyAccessToken(minted.token) as unknown as AuthInfo).minTrust).toBe('tool_observed');+ const change = await setMinTrust(engine, minted.name, null);+ expect(change).toMatchObject({ kind: 'legacy_token', id: minted.id, before: 'tool_observed', after: null });+ expect((await provider().verifyAccessToken(minted.token) as unknown as AuthInfo).minTrust).toBeUndefined();+ });++ test('an OAuth client floor reaches AuthInfo.minTrust', async () => {+ const clientId = `client-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id) VALUES($1,'fixture-hash','floor-client','read','default')`, [clientId]);+ const token = generateToken('gbrain_at_');+ await engine.executeRaw(`INSERT INTO oauth_tokens(token_hash,token_type,client_id,scopes,expires_at) VALUES($1,'access',$2,'{read}'::text[],$3)`,+ [hashToken(token), clientId, Math.floor(Date.now() / 1000) + 3600]);+ expect((await provider().verifyAccessToken(token) as unknown as AuthInfo).minTrust).toBeUndefined();+ expect(await setMinTrust(engine, clientId, 'agent_written')).toMatchObject({ kind: 'oauth_client', before: null, after: 'agent_written' });+ expect((await provider().verifyAccessToken(token) as unknown as AuthInfo).minTrust).toBe('agent_written');+ });++ test('the column refuses a value that names no tier', async () => {+ const minted = await mintLegacyToken(engine, { name: `bad-${randomUUID().slice(0, 6)}`, scopes: ['read'], takesHolders: ['world'] });+ await expect(engine.executeRaw(`UPDATE access_tokens SET min_trust='high' WHERE id=$1::uuid`, [minted.id])).rejects.toThrow(/min_trust_check/);+ });++ test('an unknown target is not_found', async () => {+ await expect(setMinTrust(engine, 'no-such-client', 'unknown')).rejects.toMatchObject({ code: 'not_found' });+ });+});++const target: ConfirmationTarget = { ref: 'f42', summary: 'Raise fact f42 to confirmed by you', command: ['gbrain', 'trust', 'confirm', 'f42'] };+const local = { remote: false } as OperationContext;+function tty(answer: string | null) {+ const input = new PassThrough();+ const output = new PassThrough();+ let prompt = '';+ output.on('data', chunk => { prompt += String(chunk); });+ __setConfirmationIoForTests({ probe: { stdinIsTTY: true, stdoutIsTTY: true, env: { GBRAIN_INTERACTIVE: '1' } }, input, output, timeoutMs: 2000 });+ if (answer === null) input.end(); else input.write(`${answer}\n`);+ return { prompt: () => prompt };+}++describe('typed-token owner confirmation (CEO-9, CEO-14, ENG-15, DX-3)', () => {+ test('on a TTY the user types the target token and it confirms', async () => {+ const io = tty('f42');+ expect(await requireOwnerConfirmation(local, target)).toEqual({ via: 'tty' });+ expect(io.prompt()).toContain('Type f42 to confirm');+ });++ test('y, yes or a wrong token decline with confirmation_required', async () => {+ for (const answer of ['y', 'yes', 'f43']) {+ tty(answer);+ await expect(requireOwnerConfirmation(local, target)).rejects.toMatchObject({ code: 'confirmation_required' });+ }+ });++ test('a custom token (hash8) is what must be typed', async () => {+ tty('a1b2c3d4');+ expect(await promptTypedConfirmation({ ...target, token: 'a1b2c3d4' })).toBe('confirmed');+ tty('f42');+ expect(await promptTypedConfirmation({ ...target, token: 'a1b2c3d4' })).toBe('declined');+ });++ test('without a TTY nothing is asked and the refusal is a user-run fix with no --yes', async () => {+ __setConfirmationIoForTests({ probe: { stdinIsTTY: false, stdoutIsTTY: false, env: {} } });+ expect(await promptTypedConfirmation(target)).toBe('non_interactive');+ try { await requireOwnerConfirmation(local, target); throw new Error('accepted'); }+ catch (e) {+ const err = e as OperationError;+ expect(err.code).toBe('confirmation_required');+ const rendered = renderAction(err.fix!, { transport: 'cli', isCallable: () => false, preapproved: () => true });+ expect(rendered.next).toBe('tell_user_to_run');+ expect(rendered.argv).toEqual(['gbrain', 'trust', 'confirm', 'f42']);+ expect(rendered.argv).not.toContain('--yes');+ }+ });++ test('an agent-marker environment on two TTYs still cannot confirm', async () => {+ __setConfirmationIoForTests({ probe: { stdinIsTTY: true, stdoutIsTTY: true, env: { CLAUDECODE: '1' } } });+ await expect(requireOwnerConfirmation(local, target)).rejects.toMatchObject({ code: 'confirmation_required' });+ });++ test('a remote connection needs memory_confirm: admin gets insufficient_scope with a user-run fix', async () => {+ const remote = (scopes: string[]) => ({ remote: true, auth: { token: 't', clientId: 'c', scopes } }) as unknown as OperationContext;+ try { await requireOwnerConfirmation(remote(['read', 'write', 'admin']), target); throw new Error('accepted'); }+ catch (e) {+ expect((e as OperationError).code).toBe('insufficient_scope');+ expect(renderAction((e as OperationError).fix!, { transport: 'http', isCallable: () => true, preapproved: () => true }).next).toBe('tell_user_to_run');+ }+ expect(await requireOwnerConfirmation(remote(['read', 'memory_confirm']), target)).toEqual({ via: 'memory_confirm_scope' });+ });++ test('a tier-raising fix refuses to carry --yes', () => {+ expect(() => tierRaiseFix(['gbrain', 'trust', 'confirm', 'f1', '--yes'], 'why')).toThrow(/--yes/);+ expect(() => tierRaiseFix(['gbrain', 'trust', 'confirm', 'f1', '-y'], 'why')).toThrow(/--yes/);+ expect(tierRaiseFix(['gbrain', 'trust', 'confirm', 'f1'], 'why')).toMatchObject({ actor: 'user', consent: [] });+ });+});diff --git a/test/trust-tier-schema.test.ts b/test/trust-tier-schema.test.tsnew file mode 100644index 0000000000..7900137c0c--- /dev/null+++ b/test/trust-tier-schema.test.ts@@ -0,0 +1,298 @@+/**+ * Memory trust tiers in the database (#5575: A1, A2, CEO-10, CEO-12, CEO-16,+ * CEO-1, ENG-2, ENG-10, ENG-13, ENG-18).+ *+ * Protects: the BEFORE ROW tier trigger on facts, takes, timeline_entries and+ * pages (INSERT forced to the writer's tier or `unknown`; content rewrites+ * restamp for owner writers and take min(prior, writer) otherwise; unchanged+ * content keeps the tier without error; a direct raise is refused with+ * trust_raise_refused; the backfill exception), the TRUST_CONTENT_COLUMNS+ * classification and its drift against attribution and the page revision+ * tuple, the trigger firing last, the page_versions snapshot, min(outer,+ * inner) nesting through the attribution seam with the group per-member reset,+ * the managed-writer guard treating a page or fact tier change as guarded+ * content, the write_origin JSONB binding, and get_write_attribution's trust+ * fields. Fails if any of those regress on either engine. Runs on PGLite, and+ * on Postgres (direct and transaction-mode PgBouncer) through+ * test/e2e/trust-tier-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { TRUST_CONTENT_COLUMNS, TRUST_EPHEMERAL_FRONTMATTER_KEYS, TRUST_TABLES, TRUST_TIER_TRIGGER, TRUST_TIER_TRIGGER_PREDECESSORS } from '../src/core/trust/schema.ts';+import { WRITE_ATTRIBUTION_CONTENT_COLUMNS } from '../src/core/persistence/attribution-schema.ts';+import { PAGE_STATE_SCHEMA_SQL } from '../src/core/page-state/schema.ts';+import { HASH_EPHEMERAL_FRONTMATTER_KEYS } from '../src/core/utils.ts';+import { QUARANTINE_OVERRIDE_KEY } from '../src/core/quarantine-override.ts';+import {+ currentWriteTrust, setMemberAttribution, withCoordinatedWrite, withTrustBackfill, withTrustPromotion, withWriteAttribution, withWriteTrust,+} from '../src/core/persistence/context.ts';+import { databaseRefusal } from '../src/core/persistence/publication-failure.ts';+import { trustRaiseRefusal } from '../src/core/trust/confirm.ts';+import { effectiveWriteTrust, type TaintInput, type TrustTier, type WriteTrust } from '../src/core/trust/tier.ts';+import { operationsByName } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import type { WriteAttribution } from '../src/core/persistence/attribution.ts';++describe('TRUST_CONTENT_COLUMNS (ENG-2)', () => {+ test('facts, takes and timeline content is attribution content; the rest of attribution content is lifecycle or placement', () => {+ const lifecycle: Record<'facts' | 'takes' | 'timeline_entries', string[]> = {+ facts: ['id', 'source_id', 'visibility', 'notability', 'valid_from', 'valid_until', 'expired_at', 'superseded_by', 'consolidated_at',+ 'consolidated_into', 'source', 'source_session', 'confidence', 'created_at', 'row_num', 'source_markdown_slug', 'value_hash', 'dim_status', 'attributed_to'],+ takes: ['id', 'page_id', 'row_num', 'weight', 'since_date', 'until_date', 'source', 'superseded_by', 'active', 'resolved_at', 'resolved_outcome',+ 'resolved_value', 'resolved_unit', 'resolved_source', 'resolved_by', 'created_at', 'resolved_quality'],+ timeline_entries: ['id', 'page_id', 'source', 'event_page_id', 'created_at'],+ };+ for (const table of ['facts', 'takes', 'timeline_entries'] as const) {+ const content = TRUST_CONTENT_COLUMNS[table];+ expect({ table, outside: content.filter(c => !WRITE_ATTRIBUTION_CONTENT_COLUMNS[table].includes(c)) }).toEqual({ table, outside: [] });+ expect({ table, rest: WRITE_ATTRIBUTION_CONTENT_COLUMNS[table].filter(c => !content.includes(c)).sort() })+ .toEqual({ table, rest: [...lifecycle[table]].sort() });+ }+ });++ test('pages use the pages_knowledge_revision tuple minus hash-ephemeral frontmatter keys', () => {+ const tuple = /IF \(NEW\.source_id,([^)]*)\)\s*IS DISTINCT FROM/.exec(PAGE_STATE_SCHEMA_SQL)?.[0] ?? '';+ const columns = [...tuple.matchAll(/NEW\.([a-z_]+)/g)].map(m => m[1]);+ expect(columns.length).toBeGreaterThan(5);+ expect([...TRUST_CONTENT_COLUMNS.pages]).toEqual(columns);+ expect([...TRUST_EPHEMERAL_FRONTMATTER_KEYS].sort()).toEqual([...HASH_EPHEMERAL_FRONTMATTER_KEYS, QUARANTINE_OVERRIDE_KEY].sort());+ expect(TRUST_EPHEMERAL_FRONTMATTER_KEYS).not.toContain('trust_tier');+ });+});++interface Backend { name: string; engine: BrainEngine; close: () => Promise<void> }+const backends: Backend[] = [];+beforeAll(async () => {+ for (const name of testBackends()) {+ if (name === 'pglite') {+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ backends.push({ name, engine, close: () => engine.disconnect() });+ } else {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ backends.push({ name, engine: pg.engine, close: pg.close });+ }+ }+}, 180_000);+afterAll(async () => { for (const b of backends) await b.close(); });++const trust = (tier: TrustTier, channel = 'test'): WriteTrust => ({ tier, origin: { channel } });+const attribution = (t?: WriteTrust): WriteAttribution => ({ requestId: null, principal: { kind: 'application', id: 'host:trust-test' }, ...(t ? { trust: t } : {}) });+async function page(engine: BrainEngine, slug: string): Promise<{ id: number; trust_tier: string; write_origin: unknown }> {+ const [row] = await engine.executeRaw<{ id: number; trust_tier: string; write_origin: unknown }>('SELECT id, trust_tier, write_origin FROM pages WHERE slug=$1', [slug]);+ return row!;+}+const tierOf = async (engine: BrainEngine, table: string, id: number) =>+ (await engine.executeRaw<{ t: string }>(`SELECT trust_tier AS t FROM ${table} WHERE id=$1`, [id]))[0]!.t;+async function newPage(engine: BrainEngine, t?: WriteTrust, frontmatter: Record<string, unknown> = {}): Promise<{ slug: string; id: number }> {+ const slug = `trust/${randomUUID().slice(0, 8)}`;+ const insert = (db: BrainEngine) => db.executeRaw(`INSERT INTO pages(slug,type,title,compiled_truth,source_id,frontmatter) VALUES($1,'note','T','body','default',$2::text::jsonb)`,+ [slug, JSON.stringify(frontmatter)]);+ if (t) await engine.transaction(tx => withWriteTrust(tx, t, () => insert(tx))); else await insert(engine);+ return { slug, id: (await page(engine, slug)).id };+}+const inTrust = (engine: BrainEngine, t: WriteTrust, fn: (tx: BrainEngine) => Promise<unknown>) => engine.transaction(tx => withWriteTrust(tx, t, () => fn(tx)));+const promote = (engine: BrainEngine, ceiling: TrustTier, sql: string, params: unknown[]) =>+ engine.transaction(tx => withTrustPromotion(tx, ceiling, () => tx.executeRaw(sql, params)));++for (const backendName of testBackends()) {+ const engineOf = () => backends.find(b => b.name === backendName)!.engine;++ describe(`trust tier trigger (${backendName})`, () => {+ test('fires last among BEFORE ROW triggers on every trust table', async () => {+ for (const table of TRUST_TABLES) {+ const names = (await engineOf().executeRaw<{ tgname: string }>(+ `SELECT tgname FROM pg_trigger WHERE tgrelid = $1::regclass AND NOT tgisinternal AND (tgtype & 3) = 3 ORDER BY tgname COLLATE "C"`, [table])).map(r => r.tgname);+ expect({ table, last: names.at(-1) }).toEqual({ table, last: TRUST_TIER_TRIGGER });+ for (const predecessor of TRUST_TIER_TRIGGER_PREDECESSORS[table]) expect({ table, predecessor, present: names.includes(predecessor) }).toEqual({ table, predecessor, present: true });+ }+ });++ test('INSERT cannot spoof a tier: no writer -> unknown, writer -> its tier (ENG-13)', async () => {+ const engine = engineOf();+ const slug = `trust/${randomUUID().slice(0, 8)}`;+ await engine.executeRaw(`INSERT INTO pages(slug,type,title,compiled_truth,source_id,trust_tier) VALUES($1,'note','T','b','default','user_confirmed')`, [slug]);+ expect((await page(engine, slug)).trust_tier).toBe('unknown');+ const slug2 = `trust/${randomUUID().slice(0, 8)}`;+ await inTrust(engine, trust('agent_written', 'mcp:put_page'), tx => tx.executeRaw(+ `INSERT INTO pages(slug,type,title,compiled_truth,source_id,trust_tier) VALUES($1,'note','T','b','default','operator_curated')`, [slug2]));+ expect(await page(engine, slug2)).toMatchObject({ trust_tier: 'agent_written', write_origin: { channel: 'mcp:put_page' } });+ });++ test('a writer tier above operator_curated needs a covering promotion', async () => {+ const engine = engineOf();+ await expect(newPage(engine, trust('user_confirmed'))).rejects.toThrow(/trust_raise_refused/);+ const slug = `trust/${randomUUID().slice(0, 8)}`;+ await engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed', () => withWriteTrust(tx, trust('user_confirmed', 'cli:remember --confirm'),+ () => tx.executeRaw(`INSERT INTO pages(slug,type,title,compiled_truth,source_id) VALUES($1,'note','T','b','default')`, [slug]))));+ expect((await page(engine, slug)).trust_tier).toBe('user_confirmed');+ });++ test('content rewrite: owner writer restamps, lower writers take min(prior, writer) (CEO-12)', async () => {+ const engine = engineOf();+ const legacy = await newPage(engine);+ await inTrust(engine, trust('operator_curated', 'sync'), tx => tx.executeRaw(`UPDATE pages SET compiled_truth='owner edit' WHERE id=$1`, [legacy.id]));+ expect(await page(engine, legacy.slug)).toMatchObject({ trust_tier: 'operator_curated', write_origin: { channel: 'sync' } });+ await inTrust(engine, trust('agent_written', 'mcp:put_page'), tx => tx.executeRaw(`UPDATE pages SET compiled_truth='agent edit' WHERE id=$1`, [legacy.id]));+ expect((await page(engine, legacy.slug)).trust_tier).toBe('agent_written');+ const external = await newPage(engine, trust('external_untrusted', 'connector:google'));+ await inTrust(engine, trust('agent_written'), tx => tx.executeRaw(`UPDATE pages SET compiled_truth='body ' WHERE id=$1`, [external.id]));+ expect((await page(engine, external.slug)).trust_tier).toBe('external_untrusted');+ const curated = await newPage(engine, trust('operator_curated'));+ await engine.executeRaw(`UPDATE pages SET title='edited by an undeclared writer' WHERE id=$1`, [curated.id]);+ expect((await page(engine, curated.slug)).trust_tier).toBe('unknown');+ });++ test('unchanged content keeps the tier without error; ephemeral frontmatter and tags are not content (CEO-16)', async () => {+ const engine = engineOf();+ const legacy = await newPage(engine, undefined, { captured_at: '2026-01-01' });+ await inTrust(engine, trust('operator_curated', 'sync'), async tx => {+ await tx.executeRaw(`UPDATE pages SET compiled_truth=compiled_truth WHERE id=$1`, [legacy.id]);+ await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter || '{"captured_at":"2026-02-02","quarantine":true}'::jsonb WHERE id=$1`, [legacy.id]);+ await tx.executeRaw(`UPDATE pages SET trust_tier='operator_curated' WHERE id=$1`, [legacy.id]);+ });+ expect((await page(engine, legacy.slug)).trust_tier).toBe('unknown');+ });++ test('a direct raise is refused on every trust table; promotion allows it; lowering is always allowed', async () => {+ const engine = engineOf();+ const p = await newPage(engine, trust('agent_written'));+ const refused = await engine.executeRaw(`UPDATE pages SET trust_tier='user_confirmed' WHERE id=$1`, [p.id]).then(() => null, (e: unknown) => e);+ expect(String((refused as Error)?.message)).toContain('trust_raise_refused');+ expect(databaseRefusal(refused)).toMatchObject({ code: 'trust_raise_refused', detail: { origin: 'database_trigger', table: 'pages' } });+ expect(trustRaiseRefusal(refused)?.code).toBe('trust_raise_refused');+ await promote(engine, 'operator_curated', `UPDATE pages SET trust_tier='operator_curated' WHERE id=$1`, [p.id]);+ expect((await page(engine, p.slug)).trust_tier).toBe('operator_curated');+ await expect(promote(engine, 'operator_curated', `UPDATE pages SET trust_tier='user_confirmed' WHERE id=$1`, [p.id])).rejects.toThrow(/trust_raise_refused/);+ await engine.executeRaw(`UPDATE pages SET trust_tier='external_untrusted' WHERE id=$1`, [p.id]);+ expect((await page(engine, p.slug)).trust_tier).toBe('external_untrusted');++ const [fact] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,entity_slug,fact,kind,source) VALUES('default','e','claim','fact','test') RETURNING id`);+ const [take] = await engine.executeRaw<{ id: number }>(`INSERT INTO takes(page_id,row_num,claim,kind,holder,weight) VALUES($1,1,'c','take','world',0.5) RETURNING id`, [p.id]);+ const [entry] = await engine.executeRaw<{ id: number }>(`INSERT INTO timeline_entries(page_id,date,summary,detail,source) VALUES($1,'2026-01-01','s','d','x') RETURNING id`, [p.id]);+ for (const [table, id] of [['facts', fact!.id], ['takes', take!.id], ['timeline_entries', entry!.id]] as const) {+ expect(await tierOf(engine, table, id)).toBe('unknown');+ await expect(engine.executeRaw(`UPDATE ${table} SET trust_tier='tool_observed' WHERE id=$1`, [id])).rejects.toThrow(/trust_raise_refused/);+ }+ });++ test('lifecycle and placement columns keep a confirmed tier; content columns do not (ENG-2)', async () => {+ const engine = engineOf();+ const [fact] = await engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed', () => withWriteTrust(tx, trust('user_confirmed'),+ () => tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,entity_slug,fact,kind,source) VALUES('default','e','confirmed claim','fact','test') RETURNING id`))));+ await inTrust(engine, trust('operator_curated', 'sync'), tx => tx.executeRaw(+ `UPDATE facts SET row_num=7, source_markdown_slug='e', visibility='private', confidence=0.5, notability='high', expired_at=now() WHERE id=$1`, [fact!.id]));+ expect(await tierOf(engine, 'facts', fact!.id)).toBe('user_confirmed');+ await inTrust(engine, trust('operator_curated', 'sync'), tx => tx.executeRaw(`UPDATE facts SET context='new context' WHERE id=$1`, [fact!.id]));+ expect(await tierOf(engine, 'facts', fact!.id)).toBe('operator_curated');+ });++ test('backfill moves only unknown rows and never to user_confirmed (CEO-10)', async () => {+ const engine = engineOf();+ const legacy = await newPage(engine);+ const backfill = (sql: string, params: unknown[]) => engine.transaction(tx => withTrustBackfill(tx, () => tx.executeRaw(sql, params)));+ await expect(backfill(`UPDATE pages SET trust_tier='user_confirmed' WHERE id=$1`, [legacy.id])).rejects.toThrow(/trust_raise_refused/);+ await backfill(`UPDATE pages SET trust_tier='tool_observed' WHERE id=$1`, [legacy.id]);+ expect((await page(engine, legacy.slug)).trust_tier).toBe('tool_observed');+ const agent = await newPage(engine, trust('agent_written'));+ await expect(backfill(`UPDATE pages SET trust_tier='operator_curated' WHERE id=$1`, [agent.id])).rejects.toThrow(/trust_raise_refused/);+ });++ test('page_versions snapshot the page tier and origin; a supplied value is ignored (ENG-10)', async () => {+ const engine = engineOf();+ const p = await newPage(engine, trust('operator_curated', 'sync'));+ const [v] = await engine.executeRaw<{ trust_tier: string; write_origin: unknown }>(+ `INSERT INTO page_versions(page_id,compiled_truth,frontmatter,trust_tier) VALUES($1,'body','{}'::jsonb,'user_confirmed') RETURNING trust_tier, write_origin`, [p.id]);+ expect(v).toEqual({ trust_tier: 'operator_curated', write_origin: { channel: 'sync' } });+ });+ });++ describe(`trust declarations through the attribution seam (${backendName})`, () => {+ test('nested declarations combine as min(outer, inner); undeclared scopes keep the outer one', async () => {+ const engine = engineOf();+ const seen = await engine.transaction(tx => withWriteTrust(tx, trust('operator_curated', 'sync'), async () => {+ const lowered = await withWriteTrust(tx, trust('agent_written', 'derived'), () => currentWriteTrust(tx));+ const notRaised = await withWriteAttribution(tx, attribution(trust('user_confirmed')), () => currentWriteTrust(tx)).catch(() => null);+ const kept = await withWriteAttribution(tx, attribution(), () => currentWriteTrust(tx));+ const restored = await currentWriteTrust(tx);+ return { lowered, notRaised, kept, restored };+ }));+ expect(seen.lowered).toEqual({ tier: 'agent_written', origin: { channel: 'derived' } });+ expect(seen.notRaised?.tier).toBe('operator_curated');+ expect(seen.kept).toEqual({ tier: 'operator_curated', origin: { channel: 'sync' } });+ expect(seen.restored).toEqual({ tier: 'operator_curated', origin: { channel: 'sync' } });+ expect(await engine.transaction(tx => currentWriteTrust(tx))).toBeNull();+ });++ test('withCoordinatedWrite nests min(outer, inner) and a group member resets to its own declaration', async () => {+ const engine = engineOf();+ const [a, b] = [`trust/${randomUUID().slice(0, 8)}`, `trust/${randomUUID().slice(0, 8)}`];+ const insert = (tx: BrainEngine, slug: string) => tx.executeRaw(`INSERT INTO pages(slug,type,title,compiled_truth,source_id) VALUES($1,'note','T','b','default')`, [slug]);+ const inner = await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {+ const nested = await withCoordinatedWrite(tx, ['default'], () => currentWriteTrust(tx), attribution(trust('operator_curated', 'inner')));+ await setMemberAttribution(tx, attribution(trust('external_untrusted', 'connector:github')));+ await insert(tx, a);+ await setMemberAttribution(tx, attribution());+ await insert(tx, b);+ return nested;+ }, attribution(trust('agent_written', 'outer'))));+ expect(inner).toEqual({ tier: 'agent_written', origin: { channel: 'inner' } });+ expect(await page(engine, a)).toMatchObject({ trust_tier: 'external_untrusted', write_origin: { channel: 'connector:github' } });+ expect(await page(engine, b)).toMatchObject({ trust_tier: 'unknown', write_origin: null });+ });++ test('the declared tier is the stored tier (ENG-18) and write_origin binds as a JSON object', async () => {+ const engine = engineOf();+ const declared = effectiveWriteTrust({ channel: 'agent_written', lowerTo: ['external_untrusted'], origin: { channel: 'mcp:remember', source_uri: 'https://example.com/a' } });+ const row = await inTrust(engine, declared, async tx => {+ const [f] = await tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,entity_slug,fact,kind,source) VALUES('default','e','f','fact','test') RETURNING id`);+ return { id: f!.id, scope: await currentWriteTrust(tx) };+ }) as { id: number; scope: WriteTrust };+ const [stored] = await engine.executeRaw<{ trust_tier: string; write_origin: unknown; kind: string }>(+ `SELECT trust_tier, write_origin, jsonb_typeof(write_origin) AS kind FROM facts WHERE id=$1`, [row.id]);+ expect(stored!.trust_tier).toBe(row.scope.tier);+ expect(stored!.kind).toBe('object');+ expect(stored!.write_origin).toEqual(declared.origin);+ });++ test('the managed-writer guard treats a page or fact tier change as guarded content', async () => {+ const engine = engineOf();+ const p = await newPage(engine, trust('agent_written'));+ const [f] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,entity_slug,fact,kind,source) VALUES('default','e','g','fact','test') RETURNING id`);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ await expect(engine.executeRaw(`UPDATE pages SET trust_tier='unknown' WHERE id=$1`, [p.id])).rejects.toThrow(/writer_coordinator_required/);+ await expect(engine.executeRaw(`UPDATE facts SET trust_tier='external_untrusted' WHERE id=$1`, [f!.id])).rejects.toThrow(/writer_coordinator_required/);+ await engine.executeRaw(`UPDATE facts SET write_origin='{"channel":"note"}'::jsonb WHERE id=$1`, [f!.id]);+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(`UPDATE pages SET trust_tier='unknown' WHERE id=$1`, [p.id]), attribution()));+ } finally {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ expect((await page(engine, p.slug)).trust_tier).toBe('unknown');+ });+ });++ describe(`get_write_attribution trust fields (${backendName})`, () => {+ test('a fact derived from an external page names that page and its tier; 40 inputs keep 32 (CEO-1)', async () => {+ const engine = engineOf();+ const source = await newPage(engine, trust('external_untrusted', 'connector:google'));+ const inputs: TaintInput[] = [{ table: 'pages', id: source.id, tier: 'external_untrusted' },+ ...Array.from({ length: 39 }, (_, i): TaintInput => ({ table: 'facts', id: 1000 + i, tier: 'operator_curated' }))];+ const declared = effectiveWriteTrust({ channel: 'agent_written', derived: true, inputs, origin: { channel: 'facts:extract' } });+ const [fact] = await inTrust(engine, declared, tx => tx.executeRaw<{ id: number }>(+ `INSERT INTO facts(source_id,entity_slug,fact,kind,source) VALUES('default',$1,'derived claim','fact','sync:import') RETURNING id`, [source.slug])) as Array<{ id: number }>;+ const ctx = { engine, remote: false, dryRun: false, config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ const out = await operationsByName.get_write_attribution!.handler(ctx, { slug: source.slug, fact: fact!.id }) as Record<string, any>;+ expect(out.trust_tier).toBe('external_untrusted');+ expect(out.write_origin.taint_inputs[0]).toEqual({ table: 'pages', id: source.id, tier: 'external_untrusted' });+ expect(out.write_origin).toMatchObject({ channel: 'facts:extract', taint_inputs_truncated: true, taint_input_count: 40 });+ expect(out.write_origin.taint_inputs).toHaveLength(32);+ expect(out.created.origin).toBeDefined();+ const pageView = await operationsByName.get_write_attribution!.handler(ctx, { slug: source.slug, versions: true }) as Record<string, any>;+ expect(pageView).toMatchObject({ trust_tier: 'external_untrusted', write_origin: { channel: 'connector:google' } });+ });+ });+}diff --git a/test/trust-tier.test.ts b/test/trust-tier.test.tsnew file mode 100644index 0000000000..e7a9c71b8c--- /dev/null+++ b/test/trust-tier.test.ts@@ -0,0 +1,111 @@+/**+ * Memory trust tiers (#5575): the one vocabulary every writer, reader and gate shares.+ *+ * Protects: the CEO-13 filter order (user_confirmed > operator_curated >+ * tool_observed > agent_written > unknown > external_untrusted), the fixed+ * user-facing labels (DX-8), min/max/admit helpers, the content_origin mapping+ * (DX-8), the per-token floor read-back (CEO-18) and the compute-once+ * effective tier with its bounded taint sample (ENG-18, CEO-1). Fails if the+ * order drifts (a `min_trust=agent_written` read would admit `unknown`), if a+ * derived write can exceed agent_written or its least trusted input, or if+ * the taint sample grows unbounded. Pure; no engine.+ */+import { describe, expect, test } from 'bun:test';+import {+ TAINT_INPUT_SAMPLE_LIMIT, TRUST_TIERS, TRUST_TIER_LABELS, admitsTrust, compareTrust, contentOriginTier, effectiveWriteTrust,+ maxTrust, minTrust, nestWriteTrust, parseTrustTier, storedMinTrust, storedTrustTier, tiersAtOrAbove, trustLabel, type TaintInput,+} from '../src/core/trust/tier.ts';+import { OperationError } from '../src/core/ops/contract.ts';++describe('trust tier vocabulary', () => {+ test('order is the CEO-13 filter order, highest first', () => {+ expect([...TRUST_TIERS]).toEqual(['user_confirmed', 'operator_curated', 'tool_observed', 'agent_written', 'unknown', 'external_untrusted']);+ for (let i = 1; i < TRUST_TIERS.length; i++) expect(compareTrust(TRUST_TIERS[i - 1]!, TRUST_TIERS[i]!)).toBeGreaterThan(0);+ });++ test('labels are the fixed DX-8 strings and unknown never reads as confirmed', () => {+ expect({ ...TRUST_TIER_LABELS }).toEqual({+ user_confirmed: 'confirmed by you', operator_curated: 'your notes', tool_observed: 'tool data',+ agent_written: 'written by an agent', unknown: 'unverified origin', external_untrusted: 'external, untrusted',+ });+ expect(trustLabel('unknown')).not.toContain('confirmed');+ });++ test('min_trust admits rows at or above the floor: agent_written excludes unknown and external', () => {+ expect(tiersAtOrAbove('agent_written')).toEqual(['user_confirmed', 'operator_curated', 'tool_observed', 'agent_written']);+ expect(admitsTrust('unknown', 'agent_written')).toBe(false);+ expect(admitsTrust('external_untrusted', 'unknown')).toBe(false);+ expect(admitsTrust('unknown', 'unknown')).toBe(true);+ expect(tiersAtOrAbove('external_untrusted')).toEqual([...TRUST_TIERS]);+ });++ test('min lowers, max raises (a token floor and a caller param combine as max)', () => {+ expect(minTrust('operator_curated', 'agent_written', 'tool_observed')).toBe('agent_written');+ expect(minTrust('agent_written', 'unknown')).toBe('unknown');+ expect(minTrust('unknown', 'external_untrusted')).toBe('external_untrusted');+ expect(maxTrust('unknown', 'tool_observed')).toBe('tool_observed');+ });++ test('parsing refuses anything but a tier with invalid_params naming the accepted values', () => {+ expect(parseTrustTier('tool_observed')).toBe('tool_observed');+ try { parseTrustTier('confirmed', 'min_trust'); throw new Error('accepted'); }+ catch (e) { expect(e).toBeInstanceOf(OperationError); expect((e as OperationError).code).toBe('invalid_params'); expect((e as Error).message).toContain('agent_written'); }+ });++ test('stored values: legacy NULL reads unknown; a damaged token floor fails closed to the strictest floor', () => {+ expect(storedTrustTier(null)).toBe('unknown');+ expect(storedTrustTier('bogus')).toBe('unknown');+ expect(storedMinTrust(null)).toBeUndefined();+ expect(storedMinTrust('agent_written')).toBe('agent_written');+ expect(storedMinTrust('bogus')).toBe('user_confirmed');+ });+});++describe('content_origin (DX-8)', () => {+ test('tool_output lowers to external_untrusted; user_said never confers owner authority', () => {+ expect(contentOriginTier('tool_output')).toBe('external_untrusted');+ expect(contentOriginTier('user_said')).toBe('agent_written');+ expect(contentOriginTier('inferred')).toBe('agent_written');+ });+ test('an unknown value is invalid_params listing the accepted values', () => {+ try { contentOriginTier('web'); throw new Error('accepted'); }+ catch (e) { expect((e as OperationError).code).toBe('invalid_params'); expect((e as Error).message).toContain('user_said, tool_output, inferred'); }+ });+});++describe('effective tier of one write (ENG-18, CEO-1)', () => {+ test('lowering signals only lower; a channel is never raised by them', () => {+ expect(effectiveWriteTrust({ channel: 'agent_written', lowerTo: ['external_untrusted'], origin: { channel: 'mcp:remember' } }).tier).toBe('external_untrusted');+ expect(effectiveWriteTrust({ channel: 'agent_written', lowerTo: ['operator_curated'], origin: { channel: 'mcp:remember' } }).tier).toBe('agent_written');+ });++ test('a derived write is capped at agent_written and at its least trusted input', () => {+ const owner = effectiveWriteTrust({ channel: 'operator_curated', derived: true, inputs: [{ table: 'pages', id: 1, tier: 'operator_curated' }], origin: { channel: 'dream' } });+ expect(owner.tier).toBe('agent_written');+ const external = effectiveWriteTrust({ channel: 'operator_curated', derived: true,+ inputs: [{ table: 'pages', id: 1, tier: 'operator_curated' }, { table: 'pages', id: 2, tier: 'external_untrusted' }], origin: { channel: 'dream' } });+ expect(external.tier).toBe('external_untrusted');+ expect(external.origin?.taint_inputs?.[0]).toEqual({ table: 'pages', id: 2, tier: 'external_untrusted' });+ });++ test('40 inputs keep the 32 least trusted with the truncation fields', () => {+ const inputs: TaintInput[] = Array.from({ length: 40 }, (_, i) => ({ table: 'facts', id: i + 1, tier: i === 37 ? 'external_untrusted' : 'operator_curated' }));+ const trust = effectiveWriteTrust({ channel: 'agent_written', derived: true, inputs, origin: { channel: 'consolidate' } });+ expect(trust.origin?.taint_inputs).toHaveLength(TAINT_INPUT_SAMPLE_LIMIT);+ expect(trust.origin?.taint_inputs?.[0]?.id).toBe(38);+ expect(trust.origin).toMatchObject({ taint_inputs_truncated: true, taint_input_count: 40, channel: 'consolidate' });+ expect(trust.tier).toBe('external_untrusted');+ });++ test('few inputs carry no truncation fields', () => {+ const trust = effectiveWriteTrust({ channel: 'agent_written', inputs: [{ table: 'pages', id: 1, tier: 'agent_written' }], origin: { channel: 'x' } });+ expect(trust.origin).toEqual({ channel: 'x', taint_inputs: [{ table: 'pages', id: 1, tier: 'agent_written' }] });+ });++ test('nesting combines as min(outer, inner): a nested write can lower, never raise', () => {+ const outer = { tier: 'agent_written' as const, origin: { channel: 'mcp:put_page' } };+ expect(nestWriteTrust(outer, { tier: 'operator_curated', origin: { channel: 'derived' } })).toEqual({ tier: 'agent_written', origin: { channel: 'derived' } });+ expect(nestWriteTrust(outer, { tier: 'external_untrusted', origin: null }).tier).toBe('external_untrusted');+ expect(nestWriteTrust(null, { tier: 'tool_observed', origin: null }).tier).toBe('tool_observed');+ });+});