Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test: cover the federation exposure warning and the purge feedback scrub edges
garrytanf204cd1661f8
diff --git a/test/federation-exposure-warn.test.ts b/test/federation-exposure-warn.test.tsnew file mode 100644index 0000000000..2d721616f1--- /dev/null+++ b/test/federation-exposure-warn.test.ts@@ -0,0 +1,54 @@+/**+ * Added by /ship coverage audit.+ * Value: protects=a failed exposure read prints a warning and reads as null, and no read runs when the change does not federate;+ * fails_when=the .catch is dropped (federate throws after its config commit) or the federating guard is removed; why_new=sources-federate-member-pages+ * never fails the read; seam=none; no_claim=the real SQL read (a rejecting executeRaw stands in for a broken database)+ * Value: protects=the operator lines name how many pages beyond the five examples exist, and add no such line when every page is listed;+ * fails_when=the "... and N more" line is dropped or miscounted; why_new=the CLI cases expose at most two pages; seam=none; no_claim=none beyond protects+ */+import { describe, expect, spyOn, test } from 'bun:test';+import { pagesExposedLines, remotePagesFederationExposesOrWarn, type PagesExposed } from '../src/core/access/federation-exposure.ts';+import type { SqlEngine } from '../src/core/persistence/model.ts';++function engineWith(executeRaw: () => Promise<never>): { engine: SqlEngine; calls: () => number } {+ let n = 0;+ return { engine: { executeRaw: async () => { n++; return executeRaw(); } } as unknown as SqlEngine, calls: () => n };+}++describe('#8982 federation exposure read never changes the federation', () => {+ test('a failed read warns on stderr and reads as null', async () => {+ const { engine, calls } = engineWith(async () => { throw new Error('relation "page_versions" does not exist'); });+ const err: string[] = [];+ const spy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); });+ try {+ expect(await remotePagesFederationExposesOrWarn(engine, 'source-a', true)).toBeNull();+ } finally { spy.mockRestore(); }+ expect(calls()).toBe(1);+ expect(err.join('\n')).toContain('Warning: could not check source-a for remote-written pages without readers: relation "page_versions" does not exist');+ });++ test('a change that does not federate reads nothing', async () => {+ const { engine, calls } = engineWith(async () => { throw new Error('must not read'); });+ expect(await remotePagesFederationExposesOrWarn(engine, 'source-a', false)).toBeNull();+ expect(calls()).toBe(0);+ });+});++describe('#8982 pagesExposedLines', () => {+ const exposed = (count: number, n: number): PagesExposed => ({+ count, examples: Array.from({ length: n }, (_, i) => ({ slug: `notes/page-${i}`, member: i === 0 ? 'alice-example' : null })),+ check: 'gbrain access who-can-read notes/page-0 --source source-a', restrict: 'gbrain access rule add --prefix notes/ --readers alice-example --source source-a',+ });++ test('more pages than examples name the rest as a count', () => {+ const lines = pagesExposedLines('source-a', exposed(7, 5));+ expect(lines[0]).toContain('Warning: 7 page(s) in source-a');+ expect(lines).toContain(' notes/page-0 (member alice-example)');+ expect(lines).toContain(' notes/page-1 (credential bound to no member now)');+ expect(lines).toContain(' ... and 2 more');+ });++ test('every page listed adds no count line', () => {+ expect(pagesExposedLines('source-a', exposed(3, 3)).some(l => l.includes('more'))).toBe(false);+ });+});diff --git a/test/purge-retrieval-feedback-8821.test.ts b/test/purge-retrieval-feedback-8821.test.tsindex c7405e3d4e..77ff8b1a5e 100644--- a/test/purge-retrieval-feedback-8821.test.ts+++ b/test/purge-retrieval-feedback-8821.test.ts@@ -23,7 +23,7 @@ import { importFromContent } from '../src/core/import-file.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';-import { applyRatings, insertRetrievalEvents } from '../src/core/feedback/store.ts';+import { applyRatings, insertRetrievalEvents, scrubPurgedSlugs } from '../src/core/feedback/store.ts';import { withEnv } from './helpers/with-env.ts';import { beliefBrain, beliefPage, openFileBeliefBrain, withFileBeliefBrain } from './helpers/belief-ledger.ts';import { createPgliteBackup, restorePgliteBackup } from '../src/core/backup/snapshot.ts';@@ -133,6 +133,37 @@ describe('#8821 a page purge removes the slug from the retrieval logs and eval cconst stores = new Map((result.receipt.stores as Array<{ store: string; status: string }>).map(s => [s.store, s.status]));expect(stores.get('eval_candidates.retrieved_slugs')).toBe('deleted');}, 60_000);++ // Added by /ship coverage audit.+ // Value: protects=purging the page at the to end of a from|type|to edge removes that edge's link rating, weight and event row;+ // fails_when=the edge match keeps only the starts_with arm and drops the right-end arm; why_new=every case above purges the from end;+ // seam=none; no_claim=Postgres parity (PGLite only)+ test('purging the page at the to end of an edge scrubs the edge\'s link rows too', async () => {+ const snapshot = await engine.readPageSnapshot(OTHER, { sourceId: 'default' });+ const result = await withEnv({ GBRAIN_HOME: home }, () => operations.find(o => o.name === 'delete_page')!.handler(context(),+ { slug: OTHER, purge: true, request_id: randomUUID(), expected_revision: snapshot!.revision })) as Record<string, any>;+ expect(result.status).toBe('purged');+ for (const table of ['retrieval_feedback', 'retrieval_weights']) {+ expect({ table, rows: await engine.executeRaw(`SELECT source_id FROM ${table} WHERE element_kind = 'link' AND element_key = $1 ORDER BY 1`, [EDGE]) })+ .toEqual({ table, rows: [] });+ }+ expect(await engine.executeRaw(`SELECT source_id FROM retrieval_event_links WHERE edge_key = $1 ORDER BY 1`, [EDGE])).toEqual([{ source_id: 'source-b' }]);+ expect(await engine.executeRaw(`SELECT 1 FROM retrieval_weights WHERE source_id = 'default' AND element_kind = 'page' AND element_key = $1`, [SLUG])).toHaveLength(1);+ }, 60_000);++ // Added by /ship coverage audit.+ // Value: protects=a slug that is a prefix of another page's slug scrubs none of that page's rows or edges;+ // fails_when=the edge match drops its '|' delimiter (a LIKE/prefix match) or the page match loosens; why_new=no case purges a prefix slug;+ // seam=none; no_claim=the purge transaction around the scrub (called directly)+ test('a slug that prefixes another page\'s slug scrubs none of its rows', async () => {+ expect(await scrubPurgedSlugs(engine, 'default', ['people/alice', 'companies/acme', 'works_at'])).toEqual({+ retrieval_event_pages: 0, retrieval_event_links: 0, retrieval_feedback: 0, retrieval_weights: 0, 'eval_candidates.retrieved_slugs': 0 });+ expect(await residue()).toEqual({ ...ONLY_SOURCE_B,+ retrieval_event_pages: [{ source_id: 'default' }, { source_id: 'source-b' }], retrieval_event_links: [{ source_id: 'default' }, { source_id: 'source-b' }],+ retrieval_feedback: [{ source_id: 'default' }, { source_id: 'default' }, { source_id: 'source-b' }],+ retrieval_weights: [{ source_id: 'default' }, { source_id: 'default' }, { source_id: 'source-b' }],+ eval_candidates: [{ source_ids: ['default'] }, { source_ids: ['source-b'] }] });+ }, 60_000);});test('#8821 a recorded tombstone the belief ledger expires scrubs the same rows', () => beliefBrain(async b => {diff --git a/test/sources-federate-member-pages.test.ts b/test/sources-federate-member-pages.test.tsindex a889a6c755..2955cd5a52 100644--- a/test/sources-federate-member-pages.test.ts+++ b/test/sources-federate-member-pages.test.ts@@ -134,6 +134,18 @@ describe('sources federate previews member-written pages it exposes (#8982, pgli}}, 240_000);+ // Added by /ship coverage audit.+ // Value: protects=federate on a source that is already federated adds nothing to the no-grant floor, so it names no pages;+ // fails_when=the !wasFederated guard is dropped and every repeat federate warns; why_new=each case above flips false to true;+ // seam=none; no_claim=restore's own federated check (covered above)+ test('federating a source that is already federated names no pages', async () => {+ expect(await federated()).toBe(true);+ const out = await sources(['federate', SRC, '--json']);+ expect(JSON.parse(out.stdout)).toEqual({ id: SRC, federated: true });+ expect(out.stderr).not.toContain('Warning');+ expect(await federated()).toBe(true);+ }, 240_000);+const archive = () => engine.executeRaw(`UPDATE sources SET archived = true, archived_at = now(), archive_expires_at = now() + interval '72 hours',config = config || '{"federated": false}'::jsonb WHERE id = $1`, [SRC]);