Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(#7636): cover the remaining fail-closed branches; pre-landing review fixes
garrytanaf9cfeeec615
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 3634e9c0b7..0d6feaeb20 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -76,7 +76,7 @@ const RELATIONSHIP_TEXT: Record<string, string> = {old_source_outside: 'a row moved from a source this publication does not own',checkpoint_outside_owner: 'a source sync checkpoint outside owner publication',topology_outside_administration: 'a source topology change outside writer administration',- unreadable_state: 'writer state this database role cannot read (row-level security hides it)',+ unreadable_state: 'writer state this database role cannot read (row-level security hides it, or its row is missing)',};function guardDetail(raw: unknown): Pick<PublicationFailureDetail, 'op' | 'relationship' | 'sources'> {diff --git a/src/core/schema-migrations/v278-writer-fence-fail-closed.ts b/src/core/schema-migrations/v278-writer-fence-fail-closed.tsindex ff38de3f58..07a0bd6bed 100644--- a/src/core/schema-migrations/v278-writer-fence-fail-closed.ts+++ b/src/core/schema-migrations/v278-writer-fence-fail-closed.ts@@ -17,11 +17,12 @@ import {// (unreadable state), as does a page or source lookup row-level security// hides, the git-canonical recount under RLS on sources, and protocol// activation while RLS filters the tables it must see empty. An unmanaged-// brain, the owner and any role that can read the state behave as before.+// brain, the owner and any role that can read the state behave as before,+// except that activation and the recount refuse any caller RLS applies to,+// whatever its policies: a hidden row cannot be told from an absent one there.// Replaces only the five functions: their triggers already call them, and// re-creating the triggers would take ACCESS EXCLUSIVE locks on the largest// tables. No privilege changes, no SECURITY DEFINER, no row is read or written.-// Provisional number: renumbered at the merge slot.export const v278: Migration = {version: 278,name: 'writer_fence_fail_closed',diff --git a/test/writer-fence-fail-closed-7636.test.ts b/test/writer-fence-fail-closed-7636.test.tsindex 03a2637305..704689de33 100644--- a/test/writer-fence-fail-closed-7636.test.ts+++ b/test/writer-fence-fail-closed-7636.test.ts@@ -5,7 +5,9 @@* "G7a off", "floor unknown" or "quiesced" and let the write through.** Contract: such a lookup raises writer_coordinator_required (unreadable state). The owner, an unmanaged brain and a- * role that can read the state behave exactly as before, including the cascade a coordinated page delete runs.+ * role that can read the state behave exactly as before, including the cascade a coordinated page delete runs. The+ * exceptions are protocol activation and the git-canonical source recount: they refuse any caller row-level security+ * filters, whatever its policies, because a hidden row cannot be told from an absent one there.* The owner arm runs on PGLite and Postgres (PGLite has no roles: its behaviour is unchanged); the scoped-role arm* runs on Postgres through test/e2e/writer-fence-fail-closed-7636-postgres.test.ts.*/@@ -17,6 +19,7 @@ import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { databaseRefusal } from '../src/core/persistence/publication-failure.ts';import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';@@ -104,7 +107,7 @@ const ACTIVATE = 'UPDATE persistence_brain SET writer_protocol_floor=2 WHERE sindescribe('owner behaviour is unchanged', () => {test('an unmanaged brain takes writes without a coordinator; a managed one refuses them as before', async () => {for (const { name, engine } of engines) {- const { pageId, requestId, effectId } = seeded.get(engine)!;+ const { pageId } = seeded.get(engine)!;await singleton(engine, false, 1);expect(await attempt(engine, ...newPage('default')), name).toBe('ok');expect(await attempt(engine, 'DELETE FROM tags WHERE page_id=$1', [pageId]), name).toBe('ok');@@ -120,7 +123,7 @@ describe('owner behaviour is unchanged', () => {test('the protocol floor, activation and the git-canonical count behave as before', async () => {for (const { name, engine } of engines) {- const { pageId, requestId, effectId } = seeded.get(engine)!;+ const { requestId, effectId } = seeded.get(engine)!;await singleton(engine, true, 1);expect(await attempt(engine, ACTIVATE, [], { settings: QUIESCED }), name).toMatch(NOT_QUIESCED);await singleton(engine, true, 2);@@ -135,6 +138,32 @@ describe('owner behaviour is unchanged', () => {expect(await engine.executeRaw('SELECT strict_sources FROM git_canonical_brain'), name).toEqual([{ strict_sources: 1 }]);}});++ // gstack /ship Step 7 coverage audit (pass 1).+ // Value: protects=a missing persistence_brain singleton is refused as unreadable_state (never "unmanaged") and classified+ // as writer_coordinator_required with its own text; fails_when=the NOT FOUND raise reverts to a pass, or its CONSTRAINT or+ // DETAIL stop matching publication-failure.ts; why_new=that branch ran only under a Postgres scoped role, and no test fed a+ // real unreadable_state raise through databaseRefusal; seam=none; no_claim=how the consumer stores it on a receipt+ // (databaseRefusal called directly on the driver error)+ test('a missing persistence_brain singleton is refused, not read as unmanaged, and classified as unreadable state', async () => {+ for (const { name, engine } of engines) {+ await singleton(engine, false, 1);+ let caught: unknown;+ try {+ await engine.transaction(async tx => {+ await tx.executeRaw('DELETE FROM persistence_brain WHERE singleton = 1');+ await tx.executeRaw(...newPage('default'));+ throw new Error(ROLLBACK);+ });+ } catch (error) { caught = error; }+ expect((caught as Error).message, name).toMatch(UNREADABLE);+ const refusal = databaseRefusal(caught);+ expect(refusal, name).toMatchObject({ code: 'writer_coordinator_required',+ detail: { origin: 'database_guard', sqlstate: 'P0001', table: 'pages', op: 'INSERT', branch: 'unreadable_state', relationship: 'unreadable_state' } });+ expect(refusal!.message, name).toContain('row-level security hides it');+ expect(await engine.executeRaw('SELECT count(*)::int AS n FROM persistence_brain'), name).toEqual([{ n: 1 }]);+ }+ });});(backends.includes('postgres') ? describe : describe.skip)('a scoped role that cannot read the fence state (Postgres)', () => {@@ -216,6 +245,49 @@ describe('owner behaviour is unchanged', () => {expect(await attempt(engine, 'DELETE FROM tags WHERE page_id=$1', [pageId], as)).toMatch(UNREADABLE);});+ // gstack /ship Step 7 coverage audit (pass 1).+ // Value: protects=a page child moved off a page RLS hides is refused (the old-page lookup of an UPDATE); fails_when=the+ // NOT FOUND check after the old_source lookup is dropped, so old_source stays NULL and the allowlist passes; why_new=only+ // a DELETE (new-page lookup) was covered; seam=none; no_claim=timeline_entries and takes (same branch, tags stand in)+ test('gbrain_require_managed_writer: moving a page child off a page row-level security hides is refused', async () => {+ await singleton(engine, false, 1);+ const [target] = await engine.executeRaw<{ id: number }>(`INSERT INTO pages(source_id,slug,type,title,compiled_truth)+ VALUES('default',$1,'note','Target','body') RETURNING id`, [`notes/target-${randomUUID().slice(0, 8)}`]);+ try {+ await singleton(engine, true, 1);+ const move = ['UPDATE tags SET page_id=$1 WHERE page_id=$2', [target!.id, pageId]] as [string, unknown[]];+ await policies([]);+ expect(await attempt(engine, ...move, { ...as, settings: coordinator(['default']) })).toBe('ok');+ await policies([], { pages: `id <> ${Number(pageId)}` });+ expect(await attempt(engine, ...move, { ...as, settings: coordinator(['default']) })).toMatch(UNREADABLE);+ } finally {+ await singleton(engine, false, 1);+ await engine.executeRaw('DELETE FROM pages WHERE id=$1', [target!.id]);+ }+ });++ // gstack /ship Step 7 coverage audit (pass 1).+ // Value: protects=G7a counts both sources of a cross-source move, so a hidden git-canonical old source is refused;+ // fails_when=the expected count CASE collapses to 1, letting a page leave a hidden git-canonical source without the git+ // protocol; why_new=only single-source INSERTs were covered; seam=none; no_claim=the reverse move (same comparison)+ test('gbrain_require_managed_writer: moving a page out of a git-canonical source row-level security hides is refused', async () => {+ await singleton(engine, false, 1);+ const [moved] = await engine.executeRaw<{ id: number }>(`INSERT INTO pages(source_id,slug,type,title,compiled_truth)+ VALUES('git-src',$1,'note','Moved','body') RETURNING id`, [`notes/moved-${randomUUID().slice(0, 8)}`]);+ try {+ await singleton(engine, true, 1);+ const move = ['UPDATE pages SET source_id=$1 WHERE id=$2', ['default', moved!.id]] as [string, unknown[]];+ const settings = coordinator(['default', 'git-src']);+ await policies([]);+ expect(await attempt(engine, ...move, { ...as, settings })).toMatch(GIT_PROTOCOL);+ await policies([], { sources: `id <> 'git-src'` });+ expect(await attempt(engine, ...move, { ...as, settings })).toMatch(UNREADABLE);+ } finally {+ await singleton(engine, false, 1);+ await engine.executeRaw('DELETE FROM pages WHERE id=$1', [moved!.id]);+ }+ });+test('gbrain_guard_effect_protocol and gbrain_guard_request_protocol: a hidden floor no longer reads as no floor', async () => {await policies(['persistence_brain']);await singleton(engine, true, 2);@@ -229,6 +301,27 @@ describe('owner behaviour is unchanged', () => {expect(await attempt(engine, ACTIVATE, [], { ...as, settings: QUIESCED })).toMatch(UNREADABLE);});+ // gstack /ship Step 7 coverage audit (pass 1).+ // Value: protects=row-level security on any one of the five tables activation must see empty refuses it; fails_when=a+ // table drops out of the row_security_active list, so activation reads that table filtered; why_new=RLS was on all five+ // at once, so only the first operand was exercised; seam=none; no_claim=a policy that filters rows (RLS on, open policy)+ test('gbrain_guard_protocol_activation: row-level security on any one table it must see empty refuses activation', async () => {+ const watched = ['persistence_requests', 'persistence_effects', 'persistence_worktrees', 'persistence_source_bindings', 'sources'];+ await policies([]);+ await singleton(engine, true, 1);+ try {+ for (const table of watched) await engine.executeRaw(`ALTER TABLE ${table} DISABLE ROW LEVEL SECURITY`);+ // Every table readable: the seeded queued request blocks activation as it does for the owner.+ expect(await attempt(engine, ACTIVATE, [], { ...as, settings: QUIESCED })).toMatch(NOT_QUIESCED);+ for (const hidden of watched) {+ for (const table of watched) await engine.executeRaw(`ALTER TABLE ${table} ${table === hidden ? 'ENABLE' : 'DISABLE'} ROW LEVEL SECURITY`);+ expect(await attempt(engine, ACTIVATE, [], { ...as, settings: QUIESCED }), hidden).toMatch(UNREADABLE);+ }+ } finally {+ for (const table of watched) await engine.executeRaw(`ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY`);+ }+ });+test('gbrain_count_git_canonical_sources: a recount over the sources RLS lets the role see is refused', async () => {await policies([], { sources: `id = 'scoped-src'` });await singleton(engine, false, 1);