Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(trust): release refusal, fallback and identity-race coverage for trust_release (gstack /ship Step 7, GBRA-60 lane C)

garrytan145fc688b937
diff --git a/test/trust-release-fence.test.ts b/test/trust-release-fence.test.ts
index 8abc86ebd5..320d761ebf 100644
--- a/test/trust-release-fence.test.ts
+++ b/test/trust-release-fence.test.ts
@@ -15,7 +15,8 @@
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
-import { readFileSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
@@ -25,10 +26,14 @@ import { enableBeliefLedger } from '../src/core/belief/coverage.ts';
import { parseFactsFence, renderFactsTable } from '../src/core/facts-fence.ts';
import { operationsByName } from '../src/core/operations.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { applyOwnerAction, currentHoldStore, previewOwnerAction } from '../src/core/trust/owner-actions.ts';
import { durableGitRepo, git } from './helpers/git-publication.ts';
import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { managedPersistenceEnabled } from '../src/core/persistence/ownership.ts';
import { enableTrustProtections } from './helpers/trust-protections.ts';
const slug = 'people/alice-example';
@@ -166,5 +171,222 @@ for (const backend of testBackends()) {
await settleManagedGitEffects(engine);
expect(readFileSync(file(root), 'utf8')).toBe(before);
}, { setup, databaseUrl }), 180_000);
+
+ // Generated by gstack /ship Step 7 coverage audit (#7511).
+ // Value: protects=a release into a deleted or private entity page refuses page_not_found, the fact stays held and nothing is admitted or written;
+ // fails_when=the deleted_at or excludePrivate guard in submitTrustRelease is dropped or inverted; why_new=no test released into a deleted or private page;
+ // seam=none; no_claim=the IPC owner path (local CLI confirmation only)
+ test('a release into a deleted or private entity page refuses page_not_found: the fact stays held and nothing is admitted', async () => {
+ for (const shape of ['deleted', 'private'] as const) {
+ await managedBrain(async ({ engine, ctx, root }) => {
+ await seedPage(engine, ctx);
+ const ref = await holdRemember(engine, ctx);
+ const live = await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ if (shape === 'deleted') {
+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug, expected_revision: live!.revision, request_id: randomUUID() } });
+ } else {
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), expected_revision: live!.revision,
+ content: '---\ntype: person\ntitle: Alice Example\nvisibility: private\n---\n\n# Alice Example\n\nBody.\n' } });
+ }
+ await settleManagedGitEffects(engine);
+ const before = shape === 'private' ? readFileSync(file(root), 'utf8') : null;
+ const error = await release(engine, ref).then(() => null, (e: { code?: string; message?: string }) => e);
+ expect({ shape, code: error?.code }).toEqual({ shape, code: 'page_not_found' });
+ expect(error?.message).toContain(shape);
+ expect(await holdStatus(engine, ref)).toBe('held');
+ expect(await factRows(engine)).toEqual([]);
+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE operation='trust_release'")).toEqual([]);
+ if (before !== null) { await settleManagedGitEffects(engine); expect(readFileSync(file(root), 'utf8')).toBe(before); }
+ }, { setup, databaseUrl });
+ }
+ }, 300_000);
+
+ // Generated by gstack /ship Step 7 coverage audit (#7511).
+ // Value: protects=on a managed brain a held fact whose entity page does not exist still releases database-only (no trust_release request, no fence index);
+ // fails_when=submitTrustRelease stops returning null for a missing page (throws or admits a door write); why_new=the managed release tests all seed the page first;
+ // seam=none; no_claim=the later page creation adopting the row (GBRA-190 G4 owns it)
+ test('a held fact whose entity page is missing releases database-only as before: no door request, no fence row index', () => managedBrain(async ({ engine, ctx }) => {
+ const ref = await holdRemember(engine, ctx);
+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true })).toBeNull();
+ expect(await release(engine, ref)).toMatchObject({ status: 'released', tier: 'user_confirmed' });
+ expect(await holdStatus(engine, ref)).toBe('released');
+ expect(await factRows(engine)).toEqual([expect.objectContaining({ trust_tier: 'user_confirmed', entity_slug: slug, row_num: null, source_markdown_slug: null, expired_at: null })]);
+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE operation='trust_release'")).toEqual([]);
+ }, { setup, databaseUrl }), 180_000);
+
+ // Generated by gstack /ship Step 7 coverage audit (#7511).
+ // Value: protects=a page deleted after the release request was admitted ends the request in conflict (page_not_found, legacy page_identity_changed); the hold stays held, no fact row;
+ // fails_when=prepareTrustReleaseMutation drops its deleted/recreated page identity check; why_new=only a hold decided meanwhile was raced, never the page;
+ // seam=none; no_claim=a page recreated under the slug (same check, other branch); the deletion is a raw SQL stand-in for a concurrent delete_page
+ test('an entity page deleted while the release is in flight ends the request in conflict (page_not_found): the fact stays held', () => managedBrain(async ({ engine, ctx }) => {
+ await seedPage(engine, ctx);
+ const ref = await holdRemember(engine, ctx);
+ // A concurrent delete_page committed between admission and preparation: the writer guard is lifted for this one
+ // statement and restored, the way the coordinator scopes its own page writes.
+ await engine.executeRaw(`CREATE FUNCTION test_delete_page() RETURNS trigger LANGUAGE plpgsql AS $$
+ DECLARE ws text := current_setting('gbrain.write_sources', true); gp text := current_setting('gbrain.git_protocol', true); BEGIN
+ PERFORM set_config('gbrain.write_sources', '["default"]', true); PERFORM set_config('gbrain.git_protocol', '1', true);
+ UPDATE pages SET deleted_at=now() WHERE source_id='default' AND slug=NEW.slug;
+ PERFORM set_config('gbrain.write_sources', COALESCE(ws, ''), true); PERFORM set_config('gbrain.git_protocol', COALESCE(gp, ''), true);
+ RETURN NEW; END $$`);
+ await engine.executeRaw(`CREATE TRIGGER test_delete_page AFTER INSERT ON persistence_requests FOR EACH ROW
+ WHEN (NEW.operation = 'trust_release') EXECUTE FUNCTION test_delete_page()`);
+ const error = await release(engine, ref).then(() => null, (e: { code?: string }) => e);
+ expect(JSON.parse(JSON.stringify(error))).toMatchObject({ code: 'page_not_found', error: 'page_identity_changed', message: 'The accepted page no longer exists.' });
+ expect(await holdStatus(engine, ref)).toBe('held');
+ expect(await factRows(engine)).toEqual([]);
+ const [receipt] = await engine.executeRaw<{ state: string; error_code: string }>("SELECT state, error_code FROM persistence_requests WHERE operation='trust_release'");
+ expect(receipt).toMatchObject({ state: 'conflict', error_code: 'page_identity_changed' });
+ }, { setup, databaseUrl }), 180_000);
+
+ // Generated by gstack /ship Step 7 coverage audit (#7511).
+ // Value: protects=on an unmanaged brain a held fact whose entity page exists still releases database-only: no trust_release request, no fence row;
+ // fails_when=submitTrustRelease's managed-mode check is dropped and every release goes through the door; why_new=no test releases a real hold unmanaged;
+ // seam=none; no_claim=the unmanaged page body (only that no fence row and no request appear)
+ test('on an unmanaged brain a held fact releases database-only even when its entity page exists', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-release-unmanaged-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ expect(await managedPersistenceEnabled(engine)).toBe(false);
+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: 'default', remote: false, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } } as OperationContext;
+ await operationsByName.put_page.handler(ctx, { slug, request_id: randomUUID(), content: '---\ntype: person\ntitle: Alice Example\n---\n\n# Alice Example\n\nBody.\n' });
+ const ref = await holdRemember(engine, ctx);
+ expect(await release(engine, ref)).toMatchObject({ status: 'released', tier: 'user_confirmed' });
+ expect(await holdStatus(engine, ref)).toBe('released');
+ expect(await factRows(engine)).toEqual([expect.objectContaining({ trust_tier: 'user_confirmed', entity_slug: slug, row_num: null, source_markdown_slug: null })]);
+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE operation='trust_release'")).toEqual([]);
+ const [page] = await engine.executeRaw<{ compiled_truth: string }>("SELECT compiled_truth FROM pages WHERE source_id='default' AND slug=$1", [slug]);
+ expect(fenceCells(page!.compiled_truth)).toEqual([]);
+ } finally { await disposePersistenceConsumer(engine); await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 180_000);
+
+ // Generated by gstack /ship Step 7 coverage audit (#7511).
+ // Value: protects=a hold dropped before its release, with no request of that approval, publishes nothing: publish returns false, the approval refuses preview_changed;
+ // fails_when=submitTrustRelease's hold.status check is dropped and a decided hold admits a door write; why_new=only a drop after admission (in flight) was tested;
+ // seam=none; no_claim=apply's publish-false branch itself (the stale preview binding refuses first); the hold is dropped through the owner drop action
+ test('a hold dropped before the release publishes nothing: publish returns false, no request is admitted and the stale approval refuses preview_changed', () => managedBrain(async ({ engine, ctx, root }) => {
+ await seedPage(engine, ctx);
+ const ref = await holdRemember(engine, ctx);
+ const approved = await previewOwnerAction(engine, { action: 'release', ref });
+ const drop = await previewOwnerAction(engine, { action: 'drop', ref });
+ await applyOwnerAction(engine, { action: 'drop', ref }, { binding: drop.binding, confirmation: { via: 'tty' }, by: owner });
+ expect(await holdStatus(engine, ref)).toBe('dropped');
+ const before = readFileSync(file(root), 'utf8');
+ expect(await currentHoldStore().publish!(engine, Number(ref.slice(1)), 'owner-example')).toBe(false);
+ const error = await applyOwnerAction(engine, { action: 'release', ref }, { binding: approved.binding, confirmation: { via: 'tty' }, by: owner })
+ .then(() => null, (e: { code?: string }) => e);
+ expect(error?.code).toBe('preview_changed');
+ expect(await holdStatus(engine, ref)).toBe('dropped');
+ expect(await factRows(engine)).toEqual([]);
+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE operation='trust_release'")).toEqual([]);
+ await settleManagedGitEffects(engine);
+ expect(readFileSync(file(root), 'utf8')).toBe(before);
+ }, { setup, databaseUrl }), 180_000);
+
+ // Generated by gstack /ship Step 7 coverage audit (#7511).
+ // Value: protects=a release into a page of an archived source refuses source_changed before admission: the fact stays held, no request, the file is unchanged;
+ // fails_when=the sources.archived check in submitTrustRelease is dropped or inverted; why_new=no test released with the source archived;
+ // seam=none; no_claim=gbrain sources archive itself (it refuses the default source; a raw UPDATE of sources.archived under gbrain.topology_change stands in)
+ test('a release into a page of an archived source refuses source_changed: the fact stays held and nothing is admitted', () => managedBrain(async ({ engine, ctx, root }) => {
+ await seedPage(engine, ctx);
+ const ref = await holdRemember(engine, ctx);
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change', 'on', true)");
+ await tx.executeRaw("UPDATE sources SET archived=true, archived_at=now() WHERE id='default'");
+ });
+ const before = readFileSync(file(root), 'utf8');
+ const error = await release(engine, ref).then(() => null, (e: { code?: string }) => e);
+ expect(error?.code).toBe('source_changed');
+ expect(await holdStatus(engine, ref)).toBe('held');
+ expect(await factRows(engine)).toEqual([]);
+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE operation='trust_release'")).toEqual([]);
+ expect(readFileSync(file(root), 'utf8')).toBe(before);
+ }, { setup, databaseUrl }), 180_000);
+
+ // Generated by gstack /ship Step 7 coverage audit (#7511).
+ // Value: protects=a page recreated under the slug (new page id) after the release was admitted ends the request in conflict page_identity_changed, hold held and no fact;
+ // fails_when=prepareTrustReleaseMutation stops comparing the page id with the admitted one; why_new=pass 1 raced a deleted page only, never a replaced one;
+ // seam=none; no_claim=a real purge-and-recreate (a raw SQL trigger renames the page away and inserts a copy with a new id between admission and preparation)
+ test('an entity page recreated under the same slug while the release is in flight refuses page_identity_changed: the fact stays held', () => managedBrain(async ({ engine, ctx }) => {
+ await seedPage(engine, ctx);
+ const ref = await holdRemember(engine, ctx);
+ const [admitted] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]);
+ await engine.executeRaw(`CREATE FUNCTION test_recreate_page() RETURNS trigger LANGUAGE plpgsql AS $$
+ DECLARE ws text := current_setting('gbrain.write_sources', true); gp text := current_setting('gbrain.git_protocol', true); prior jsonb; BEGIN
+ PERFORM set_config('gbrain.write_sources', '["default"]', true); PERFORM set_config('gbrain.git_protocol', '1', true);
+ SELECT to_jsonb(p) INTO prior FROM pages p WHERE source_id='default' AND slug=NEW.slug;
+ UPDATE pages SET slug=slug || '-replaced', deleted_at=now() WHERE source_id='default' AND slug=NEW.slug;
+ INSERT INTO pages SELECT * FROM jsonb_populate_record(NULL::pages, (prior - 'id' - 'knowledge_revision') || jsonb_build_object('id', nextval('pages_id_seq'), 'knowledge_revision', gen_random_uuid()));
+ PERFORM set_config('gbrain.write_sources', COALESCE(ws, ''), true); PERFORM set_config('gbrain.git_protocol', COALESCE(gp, ''), true);
+ RETURN NEW; END $$`);
+ await engine.executeRaw(`CREATE TRIGGER test_recreate_page AFTER INSERT ON persistence_requests FOR EACH ROW
+ WHEN (NEW.operation = 'trust_release') EXECUTE FUNCTION test_recreate_page()`);
+ const error = await release(engine, ref).then(() => null, (e: { code?: string }) => e);
+ expect(error?.code).toBe('page_identity_changed');
+ const [live] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1 AND deleted_at IS NULL", [slug]);
+ expect(Number(live!.id)).not.toBe(Number(admitted!.id));
+ expect(await holdStatus(engine, ref)).toBe('held');
+ expect(await factRows(engine)).toEqual([]);
+ const [receipt] = await engine.executeRaw<{ state: string; error_code: string }>("SELECT state, error_code FROM persistence_requests WHERE operation='trust_release'");
+ expect(receipt).toMatchObject({ state: 'conflict', error_code: 'page_identity_changed' });
+ }, { setup, databaseUrl }), 180_000);
+
+ // Generated by gstack /ship Step 7 coverage audit (#7511).
+ // Value: protects=a release into an agent_written page keeps the page's tier (stored tier and frontmatter marker) while its fact row is user_confirmed;
+ // fails_when=trust_release leaves FENCE_EDIT_OPERATIONS and the page is stamped with the release's user_confirmed tier; why_new=no test read the page tier after a release;
+ // seam=none; no_claim=pages at other tiers (put_page from the local CLI context seeds agent_written)
+ test('a release keeps its entity page at the page\'s own tier while the released fact row is user_confirmed', () => managedBrain(async ({ engine, ctx }) => {
+ await seedPage(engine, ctx);
+ const pageTier = async () => (await engine.executeRaw<{ trust_tier: string; marker: string | null }>(
+ "SELECT trust_tier, frontmatter->>'trust_tier' AS marker FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0];
+ const before = await pageTier();
+ expect(before).toEqual({ trust_tier: 'agent_written', marker: 'agent_written' });
+ const ref = await holdRemember(engine, ctx);
+ expect(await release(engine, ref)).toMatchObject({ status: 'released', tier: 'user_confirmed' });
+ expect(await factRows(engine)).toEqual([expect.objectContaining({ trust_tier: 'user_confirmed', channel: 'trust_release', source_markdown_slug: slug })]);
+ expect(await pageTier()).toEqual(before);
+ }, { setup, databaseUrl }), 180_000);
+
+ // Generated by gstack /ship Step 7 coverage audit (#7511).
+ // Value: protects=a held take on a managed brain skips the door (publish returns null) and its release refuses unavailable: hold held, no take, no request;
+ // fails_when=submitTrustRelease publishes non-fact holds (kind check dropped or the target falls back to the hold's slug); why_new=no release test used a take hold;
+ // seam=none; no_claim=releasing takes (unsupported today; this pins the refusal, not a future take release)
+ test('a held take on a managed brain does not go through the door: publish returns null and the release refuses unavailable', () => managedBrain(async ({ engine, ctx }) => {
+ await seedPage(engine, ctx);
+ await enableTrustProtections(engine);
+ let ref = '';
+ try { await operationsByName.takes_add.handler(ctx, { slug, claim: CLAIM, kind: 'take', holder: 'world', weight: 0.6, content_origin: 'tool_output', request_id: randomUUID() }); }
+ catch (e) { ref = JSON.parse((e as { detail: string }).detail).hold_ref; }
+ expect(ref).toMatch(/^h\d+$/);
+ expect((await engine.executeRaw<{ kind: string }>('SELECT kind FROM write_gate_holds WHERE id=$1', [Number(ref.slice(1))]))[0]!.kind).toBe('take');
+ expect(await currentHoldStore().publish!(engine, Number(ref.slice(1)), 'owner-example')).toBeNull();
+ const error = await release(engine, ref).then(() => null, (e: { code?: string }) => e);
+ expect(error?.code).toBe('unavailable');
+ expect(await holdStatus(engine, ref)).toBe('held');
+ expect(await engine.executeRaw('SELECT id FROM takes WHERE claim=$1', [CLAIM])).toEqual([]);
+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE operation='trust_release'")).toEqual([]);
+ }, { setup, databaseUrl }), 180_000);
});
}
+
+// Generated by gstack /ship Step 7 coverage audit (#7511).
+// Value: protects=the trust_release preparer refuses confirmation_required for a remote-authority or malformed request before reading any state;
+// fails_when=the authority.remote or intent-shape guard in prepareTrustReleaseMutation is dropped; why_new=no test reaches the preparer with a remote row;
+// seam=none; no_claim=how a remote row could be journaled (no remote op admits trust_release; the row is hand-built and the engine is a stub)
+describe('the trust_release preparer refuses a request the owner did not confirm', () => {
+ test('a remote or malformed trust_release request refuses confirmation_required and touches no engine', async () => {
+ const { prepareTrustReleaseMutation } = await import('../src/core/trust/release-publish.ts');
+ const engine = new Proxy({}, { get: (_t, key) => { throw new Error(`engine.${String(key)} read`); } }) as BrainEngine;
+ const intent = { hold_id: 1, last_seen_at: '2026-01-01T00:00:00Z', by: 'owner:owner-example', mode: 'append' };
+ const row = (over: Record<string, unknown>) => ({ operation: 'trust_release', source_id: 'default', slug, page_id: 1, intent, authority: { remote: false }, ...over }) as never;
+ for (const bad of [{ authority: { remote: true } }, { intent: null }, { intent: { ...intent, mode: 'rewrite' } }, { intent: { ...intent, hold_id: 'h1' } }, { operation: 'remember' }]) {
+ const error = await prepareTrustReleaseMutation(engine, row(bad), { engine: 'pglite' } as never).then(() => null, (e: { code?: string }) => e);
+ expect({ bad, code: error?.code }).toEqual({ bad, code: 'confirmation_required' });
+ }
+ });
+});