Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust-reads): write_gate_receipts bump the trust generation; ENG-14 drift tests
garrytan519799c0396d
diff --git a/src/core/eligibility/generation-schema.ts b/src/core/eligibility/generation-schema.tsindex 5229d7e8a1..16f8d31a0e 100644--- a/src/core/eligibility/generation-schema.ts+++ b/src/core/eligibility/generation-schema.ts@@ -58,6 +58,12 @@ export const TRUST_GENERATION_WHEN: Readonly<Record<string, Partial<Record<Generfact_purges: { insert: 'TRUE' },take_purges: { insert: 'TRUE' },page_purges: { insert: 'TRUE' },+ // A new or changed flag receipt changes what activation control withholds (CEO-20).+ write_gate_receipts: {+ insert: 'TRUE',+ update: '(OLD.verdict, OLD.reason_families, OLD.content_hash, OLD.target_table, OLD.target_id) IS DISTINCT FROM (NEW.verdict, NEW.reason_families, NEW.content_hash, NEW.target_table, NEW.target_id)',+ delete: 'TRUE',+ },needs_rederive: { insert: 'TRUE' },};@@ -80,21 +86,6 @@ export function trustGenerationTriggerSql(table: string, event: GenerationEvent,];}-/**- * The write gate's verdict receipts (write_gate_receipts, lane L2a) suppress- * a row from proactive surfaces, so a receipt insert or a verdict change must- * bump the generation too. Not part of the migration until that table exists- * on this branch: after L2a merges, append these statements to- * TRUST_GENERATION_SCHEMA_STATEMENTS (its migration runs before this one on- * fresh installs and upgrades alike).- */-export const WRITE_GATE_RECEIPTS_GENERATION_STATEMENTS: readonly string[] = [- ...trustGenerationTriggerSql('write_gate_receipts', 'insert', 'TRUE'),- ...trustGenerationTriggerSql('write_gate_receipts', 'update',- '(OLD.verdict, OLD.reason_families, OLD.content_hash, OLD.target_table, OLD.target_id) IS DISTINCT FROM (NEW.verdict, NEW.reason_families, NEW.content_hash, NEW.target_table, NEW.target_id)'),- ...trustGenerationTriggerSql('write_gate_receipts', 'delete', 'TRUE'),-];-export const TRUST_GENERATION_SCHEMA_STATEMENTS: readonly string[] = [`CREATE TABLE IF NOT EXISTS ${TRUST_POLICY_STATE_TABLE} (id SMALLINT PRIMARY KEY CHECK (id = 1),diff --git a/test/eligibility-registry.test.ts b/test/eligibility-registry.test.tsnew file mode 100644index 0000000000..d4258d341d--- /dev/null+++ b/test/eligibility-registry.test.ts@@ -0,0 +1,85 @@+/**+ * #5575 ENG-14 drift tests: every read-scope operation declares its trust+ * handling (filtered | labeled | text_free), every `filtered` op takes the+ * `min_trust` param, the dispatcher backstop refuses an unfiltered read for a+ * floored token, and every registered proactive surface calls+ * `proactiveEligibility` with its own id (no unregistered ids anywhere).+ * Fails when an op or surface is added without a declaration.+ */+import { describe, expect, test } from 'bun:test';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { operations } from '../src/core/operations.ts';+import { enforceReadTrustFloor, OP_READ_TRUST, PROACTIVE_SURFACES, readTrustHandling } from '../src/core/eligibility/registry.ts';+import { OperationError } from '../src/core/ops/contract.ts';++const readOps = operations.filter(o => (o.scope ?? 'read') === 'read');++describe('read trust registry (ENG-14)', () => {+ test('every read-scope operation is declared, and every declaration names a read-scope operation', () => {+ expect(readOps.filter(o => !(o.name in OP_READ_TRUST)).map(o => o.name)).toEqual([]);+ const names = new Set(readOps.map(o => o.name));+ expect(Object.keys(OP_READ_TRUST).filter(n => !names.has(n))).toEqual([]);+ });++ test('every filtered op takes min_trust; ops that take min_trust are filtered', () => {+ for (const op of readOps) {+ const filtered = readTrustHandling(op) === 'filtered';+ expect({ op: op.name, min_trust: 'min_trust' in op.params }).toEqual({ op: op.name, min_trust: filtered });+ }+ });++ test('the retrieval and memory read surfaces are filtered', () => {+ for (const name of ['search', 'query', 'get_page', 'fetch', 'recall', 'context_pack', 'delta', 'takes_list', 'takes_search', 'get_timeline', 'volunteer_context', 'assemble_evidence']) {+ expect({ name, handling: OP_READ_TRUST[name] }).toEqual({ name, handling: 'filtered' });+ }+ });++ test('an unlisted read op resolves to the strictest handling', () => {+ expect(readTrustHandling({ name: 'some_future_op' })).toBe('labeled');+ });+});++describe('dispatcher floor backstop (CEO-18)', () => {+ const op = (name: string) => operations.find(o => o.name === name)!;+ test('a floored connection is refused a labeled read and allowed filtered, text-free and write ops', () => {+ const floored = { minTrust: 'operator_curated' as const };+ expect(() => enforceReadTrustFloor(floored, op('list_pages'))).toThrow(OperationError);+ try { enforceReadTrustFloor(floored, op('list_pages')); } catch (e) { expect((e as OperationError).code).toBe('permission_denied'); }+ expect(() => enforceReadTrustFloor(floored, op('search'))).not.toThrow();+ expect(() => enforceReadTrustFloor(floored, op('whoami'))).not.toThrow();+ expect(() => enforceReadTrustFloor(floored, op('put_page'))).not.toThrow();+ });+ test('a connection without a floor reaches every read op', () => {+ for (const o of readOps) expect(() => enforceReadTrustFloor({}, o)).not.toThrow();+ expect(() => enforceReadTrustFloor(undefined, op('list_pages'))).not.toThrow();+ });+});++describe('proactive surface registry (CEO-20)', () => {+ const root = join(import.meta.dir, '..');+ function walk(dir: string, out: string[] = []): string[] {+ for (const name of readdirSync(dir)) {+ const p = join(dir, name);+ if (statSync(p).isDirectory()) walk(p, out); else if (p.endsWith('.ts')) out.push(p);+ }+ return out;+ }++ test('each registered surface module calls proactiveEligibility with its id', () => {+ for (const [id, file] of Object.entries(PROACTIVE_SURFACES)) {+ const text = readFileSync(join(root, file), 'utf8');+ expect({ id, file, calls: new RegExp(`proactiveEligibility\\([^)]*'${id.replace('.', '\\.')}'`).test(text) }).toEqual({ id, file, calls: true });+ }+ });++ test('no source calls proactiveEligibility with an unregistered surface id', () => {+ const ids = new Set(Object.keys(PROACTIVE_SURFACES));+ const unknown: string[] = [];+ for (const file of walk(join(root, 'src'))) {+ const text = readFileSync(file, 'utf8');+ for (const m of text.matchAll(/proactiveEligibility\([^)]*?'([a-z_.]+)'/g)) if (!ids.has(m[1])) unknown.push(`${file}: ${m[1]}`);+ }+ expect(unknown).toEqual([]);+ });+});diff --git a/test/trust-generation.test.ts b/test/trust-generation.test.tsindex df7db0484e..e7d12f2c21 100644--- a/test/trust-generation.test.ts+++ b/test/trust-generation.test.ts@@ -23,7 +23,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';import { readTrustGeneration, trustCacheIdentity } from '../src/core/eligibility/generation.ts';-import { TRUST_GENERATION_TRIGGERS, TRUST_GENERATION_WHEN, WRITE_GATE_RECEIPTS_GENERATION_STATEMENTS } from '../src/core/eligibility/generation-schema.ts';+import { TRUST_GENERATION_TRIGGERS, TRUST_GENERATION_WHEN } from '../src/core/eligibility/generation-schema.ts';import { withTrustPromotion, withWriteTrust } from '../src/core/persistence/context.ts';import { setMinTrust } from '../src/core/trust/min-trust.ts';@@ -68,10 +68,9 @@ const promote = (engine: BrainEngine, table: string, id: number) => engine.trans() => tx.executeRaw(`UPDATE ${table} SET trust_tier = 'user_confirmed' WHERE id = $1`, [id])));describe('trust generation schema', () => {- test('every trigger is a deferred AFTER row trigger, and the write-gate spot names write_gate_receipts', () => {+ test('every listed table carries a generation trigger, write_gate_receipts included', () => {expect(Object.keys(TRUST_GENERATION_WHEN).sort()).toEqual(- ['access_tokens', 'config', 'fact_purges', 'facts', 'needs_rederive', 'oauth_clients', 'page_purges', 'pages', 'take_purges', 'takes', 'timeline_entries']);- expect(WRITE_GATE_RECEIPTS_GENERATION_STATEMENTS.join('\n')).toContain('ON write_gate_receipts');+ ['access_tokens', 'config', 'fact_purges', 'facts', 'needs_rederive', 'oauth_clients', 'page_purges', 'pages', 'take_purges', 'takes', 'timeline_entries', 'write_gate_receipts']);});test('the identity changes with the generation, the floor and the activation mode', () => {@@ -164,6 +163,18 @@ for (const backendName of testBackends()) {expect(await bumps(engine, () => engine.executeRaw(`INSERT INTO needs_rederive(derived_table, derived_id, source_id, reason) VALUES('facts',$1,'default','test')`, [hash]))).toBe(1);});+ test('a write-gate receipt insert, verdict change and delete bump; a re-sighting does not', async () => {+ const engine = engineOf();+ const hash = randomUUID();+ const insert = () => engine.executeRaw(`INSERT INTO write_gate_receipts (target_table, target_id, source_id, content_hash, tier, detector_version, verdict, reason_families)+ VALUES ('facts', '999999', 'default', $1, 'agent_written', 1, 'flag', ARRAY['standing_instruction'])+ ON CONFLICT (target_table, target_id, content_hash, detector_version) DO UPDATE SET last_seen_at = now()`, [hash]);+ expect(await bumps(engine, insert)).toBe(1);+ expect(await bumps(engine, insert)).toBe(0);+ expect(await bumps(engine, () => engine.executeRaw(`UPDATE write_gate_receipts SET verdict = 'quarantine' WHERE content_hash = $1`, [hash]))).toBe(1);+ expect(await bumps(engine, () => engine.executeRaw('DELETE FROM write_gate_receipts WHERE content_hash = $1', [hash]))).toBe(1);+ });+test('a transaction bumps once however many transitions it commits; a rollback bumps nothing', async () => {const engine = engineOf();const ids = [await newFact(engine), await newFact(engine), await newFact(engine)];