Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W1: probes 6 and 12 on both engines; a group's commit marks share one observation time
garrytan7771b9a05dc0
diff --git a/src/core/belief/append.ts b/src/core/belief/append.tsindex a04b4bb30d..1abf00d7b6 100644--- a/src/core/belief/append.ts+++ b/src/core/belief/append.ts@@ -165,9 +165,10 @@ export async function appendBeliefEvents(tx: BrainEngine, input: BeliefEventDraf*/export async function markBeliefCommits(engine: Pick<BrainEngine, 'executeRaw'>, publicationIds: readonly string[]): Promise<void> {if (!publicationIds.length) return;- await engine.executeRaw(`INSERT INTO belief_commit_marks (publication_id, observed_at)- SELECT e.publication_id, clock_timestamp() FROM belief_events e+ await engine.executeRaw(`WITH t AS MATERIALIZED (SELECT clock_timestamp() AS at)+ INSERT INTO belief_commit_marks (publication_id, observed_at)+ SELECT e.publication_id, t.at FROM t, belief_events eWHERE e.publication_id = ANY($1::uuid[])- GROUP BY e.publication_id HAVING max(e.recorded_at) <= clock_timestamp()+ GROUP BY e.publication_id, t.at HAVING max(e.recorded_at) <= t.atON CONFLICT (publication_id) DO NOTHING`, [[...publicationIds]]);}diff --git a/test/belief-ledger-group.test.ts b/test/belief-ledger-group.test.tsnew file mode 100644index 0000000000..72a59ff74c--- /dev/null+++ b/test/belief-ledger-group.test.ts@@ -0,0 +1,105 @@+/**+ * Belief ledger probes 6 and 12 (docs/designs/BELIEF_LEDGER.md section 11):+ * concurrent relationship refreshes on one key, and the exact-value+ * assertions through a grouped managed-sync publication (put_pages+ * members publish one transaction each). Each runs on PGLite+ * and on Postgres when DATABASE_URL is set, with a forced probe that must+ * make it fail.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { __setBeliefEmitterFaultForTests, type BeliefEventDraft } from '../src/core/belief/append.ts';+import { withBeliefBatch } from '../src/core/belief/ledger.ts';+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { performSync } from '../src/commands/sync/perform.ts';+import { testBackends } from './helpers/test-backends.ts';+import { beliefBrain, beliefEngineCase, beliefPage, shape, type BeliefBrain } from './helpers/belief-ledger.ts';++afterEach(() => { __setBeliefEmitterFaultForTests(null); });++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });++const company = (slug: string, facts: string[]) => ({ slug, content: beliefPage({ title: slug, facts, takes: ['It will grow'] }) });+const lifetimeFree = (value: Record<string, unknown> | null) => value && 'entity' in value ? { ...value, entity: 'L' } : value;++for (const engineCase of testBackends().map(beliefEngineCase)) {+ describe(`belief ledger grouped and concurrent publication (${engineCase.name})`, () => {+ test('probe 6: two concurrent relationship refreshes on one key append the evidence once and no relationship-state event', async () => {+ await beliefBrain(async b => {+ await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));+ await b.put('companies/acme-example', beliefPage({ prose: 'No links yet.' }));+ const refresh = () => b.engine.transaction(async tx => {+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug: 'companies/acme-example' }]);+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: ['companies/acme-example'], op: 'probe_relationship' }, () => tx.addLinksBatch(+ [{ from_slug: 'companies/acme-example', to_slug: 'people/alice-example', from_source_id: b.sourceId, to_source_id: b.sourceId,+ link_type: 'works_at', context: 'Alice works at Acme', link_source: 'manual' }], { auditSite: 'addLinksBatch' }));+ });+ const relationships = async () => Number((await b.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM link_relationships r+ JOIN pages f ON f.id = r.from_page_id WHERE f.source_id = $1 AND f.slug = 'companies/acme-example' AND r.link_type = 'works_at'`, [b.sourceId]))[0]!.n);+ const mark = await b.lastId();+ await Promise.all([refresh(), refresh()]);+ const events = await b.events(mark);+ expect(shape(events)).toEqual(['link:link.asserted']);+ expect(events[0]!.subject_key).toContain('works_at');+ expect(events[0]!.value).toMatchObject({ context: 'Alice works at Acme' });+ expect(await relationships()).toBeGreaterThan(0);+ // Forced probe: an emitter that re-appends the evidence on every refresh is caught.+ let seen: BeliefEventDraft | null = null;+ __setBeliefEmitterFaultForTests(drafts => {+ const link = drafts.find(d => d.subjectKind === 'link') ?? seen;+ seen = link;+ return link && !drafts.includes(link) ? [...drafts, link] : drafts;+ });+ await b.engine.executeRaw(`DELETE FROM links WHERE from_page_id = (SELECT id FROM pages WHERE source_id = $1 AND slug = 'companies/acme-example')`, [b.sourceId]);+ const forced = await b.lastId();+ await Promise.all([refresh(), refresh()]);+ expect((await b.events(forced)).filter(e => e.subject_kind === 'link').length).toBe(2);+ }, { databaseUrl: engineCase.databaseUrl });+ }, 120_000);++ test('probe 12: a grouped managed-sync publication records the same exact values as single writes, one publication per member', async () => {+ await beliefBrain(async b => {+ const files = Array.from({ length: 6 }, (_, i) => `companies/grouped-${i}`);+ const singles = Array.from({ length: 6 }, (_, i) => `companies/single-${i}`);+ git(b.root, 'init', '-q');+ mkdirSync(join(b.root, 'companies'), { recursive: true });+ const sync = async (facts: string[]) => {+ for (const slug of files) writeFileSync(join(b.root, `${slug}.md`), company(slug, facts).content);+ git(b.root, 'add', '-A'); git(b.root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'edit');+ await performSync(b.engine, { sourceId: b.sourceId, noPull: true, noEmbed: true, noExtract: true, drain: true } as never);+ };+ const comparable = (events: Awaited<ReturnType<BeliefBrain['events']>>, prefix: string) => events+ .map(e => ({ slug: e.slug.replace(prefix, 'x'), kind: e.subject_kind, type: e.event_type, value: e.subject_kind === 'page' ? Object.keys(e.value ?? {}).sort() : lifetimeFree(e.value) }))+ .sort((x, y) => JSON.stringify(x).localeCompare(JSON.stringify(y)));+ const facts = ['Seed round closed', 'Ten staff', 'Sells widgets'];+ const edited = ['Seed round closed', 'Twelve staff', 'Sells widgets'];+ for (const slug of singles) await b.put(slug, company(slug, facts).content);+ const singleMark = await b.lastId();+ for (const slug of singles) await b.put(slug, company(slug, edited).content);+ const single = comparable(await b.events(singleMark), 'single');+ await sync(facts);+ const groupMark = await b.lastId();+ await sync(edited);+ const groupedEvents = await b.events(groupMark);+ expect(comparable(groupedEvents, 'grouped')).toEqual(single);+ expect(groupedEvents.filter(e => e.subject_kind === 'fact').map(e => e.event_type).sort())+ .toEqual([...Array(6).fill('fact.asserted'), ...Array(6).fill('fact.retracted')]);+ const publications = [...new Set(groupedEvents.map(e => e.publication_id))];+ expect(publications.length).toBe(6);+ const marks = await b.engine.executeRaw<{ observed_at: string; n: number }>(`SELECT observed_at::text AS observed_at, count(*)::int AS n FROM belief_commit_marks+ WHERE publication_id = ANY($1::uuid[]) GROUP BY observed_at`, [publications]);+ expect(marks.reduce((n, m) => n + Number(m.n), 0)).toBe(6);+ // Grouped on Postgres (PGLite publishes one member per transaction): a transaction that carried several+ // members gives them one post-commit observation (section 5.3).+ if (engineCase.name === 'postgres') expect(Math.max(...marks.map(m => Number(m.n)))).toBeGreaterThan(1);+ // Forced probe: grouped members whose fact values are corrupted no longer match the single-write path.+ __setBeliefEmitterFaultForTests(drafts => drafts.map(d => d.subjectKind === 'fact' && d.value ? { ...d, value: { ...d.value, fact: 'corrupted' } } : d));+ const forcedMark = await b.lastId();+ await sync(facts);+ await sync(edited);+ expect(comparable((await b.events(forcedMark)).slice(-groupedEvents.length), 'grouped')).not.toEqual(single);+ }, { managed: true, databaseUrl: engineCase.databaseUrl });+ }, 240_000);+ });+}diff --git a/test/belief-ledger-lifecycle.test.ts b/test/belief-ledger-lifecycle.test.tsindex ed81a096ac..40b0ba85d9 100644--- a/test/belief-ledger-lifecycle.test.ts+++ b/test/belief-ledger-lifecycle.test.ts@@ -1,6 +1,6 @@/*** Belief ledger lifecycle probes (docs/designs/BELIEF_LEDGER.md section 11:- * 1, 2, 3, 5, 7, 12, 18, 21, 39). Each asserts exact event types, keys and+ * 1, 2, 3, 5, 7, 18, 21, 39; probe 12 is in belief-ledger-group.test.ts). Each asserts exact event types, keys and* values on PGLite and on Postgres when DATABASE_URL is set, and each has a* forced probe: a deliberately broken emitter that must make it fail.*/diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex c79840a185..09d8140f7a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -17,6 +17,7 @@ test/attribution-backfill-history.test.tstest/backstop-same-page-shadow-managed-6333.test.tstest/behavior-change-notice.test.tstest/belief-ledger-coverage.test.ts+test/belief-ledger-group.test.tstest/belief-ledger-identity.test.tstest/belief-ledger-lifecycle.test.tstest/belief-ledger-privacy.test.ts