Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

W1: the ledger's one history reader with the remote privacy rules; probe 14 on both engines

garrytanaa1a62d0a248
diff --git a/src/core/belief/history.ts b/src/core/belief/history.ts
new file mode 100644
index 0000000000..4f6d2a4adf
--- /dev/null
+++ b/src/core/belief/history.ts
@@ -0,0 +1,51 @@
+/**
+ * The one history reader of the belief ledger (docs/designs/BELIEF_LEDGER.md
+ * section 8, privacy). Every read of events goes through `readBeliefHistory`;
+ * remote callers never touch the table. A remote caller sees an event only when
+ * all hold, and the read fails closed when an owner cannot be resolved:
+ * - the event's own visibility was `world` when recorded;
+ * - the stream page's current lifetime is visible now (a page made private
+ * later hides its earlier events; an ended lifetime hides them too);
+ * - for links, every page-backed endpoint and the origin are visible now.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+
+export interface BeliefHistoryRow {
+ id: number; slug: string; page_lifetime: string | null; subject_kind: string; subject_key: string; event_type: string; origin: string;
+ trust_tier: string; writer_tier: string | null; tier_basis: string; visibility: string; recorded_at: string; source_time: string | null;
+ value: Record<string, unknown> | null; value_hash: string | null; prior_hash: string | null; state_hash: string; cause: Record<string, unknown>;
+ purged: boolean; redacted_fields: string[] | null;
+}
+
+export interface BeliefHistoryQuery { sourceId: string; slug?: string; subjectKey?: string; remote: boolean; afterId?: number; limit?: number }
+
+/** Lifetimes a link key names (`L:<uuid>` components), for the endpoint visibility rule. */
+function linkLifetimes(subjectKey: string): string[] {
+ const parts = JSON.parse(subjectKey) as unknown[];
+ const flat = parts[0] === 'lt' ? (parts[1] as unknown[]) : parts;
+ return flat.filter((p): p is string => typeof p === 'string' && p.startsWith('L:')).map(p => p.slice(2));
+}
+
+export async function readBeliefHistory(engine: BrainEngine, q: BeliefHistoryQuery): Promise<BeliefHistoryRow[]> {
+ const rows = await engine.executeRaw<BeliefHistoryRow & { stream_visible: boolean | null }>(`SELECT e.id, e.slug, e.page_lifetime::text AS page_lifetime,
+ e.subject_kind, e.subject_key, e.event_type, e.origin, e.trust_tier, e.writer_tier, e.tier_basis, e.visibility, e.recorded_at, e.source_time,
+ e.value, e.value_hash, e.prior_hash, e.state_hash, e.cause, e.purged, e.redacted_fields,
+ (SELECT ${privatePagesFilterFragment('p')} FROM belief_page_lifetimes l JOIN pages p ON p.source_id = l.source_id AND p.slug = l.slug
+ AND p.deleted_at IS NULL AND (l.page_id IS NULL OR p.id = l.page_id)
+ WHERE l.page_lifetime = e.page_lifetime AND l.ended_at IS NULL) AS stream_visible
+ FROM belief_events e
+ WHERE e.source_id = $1 AND ($2::text IS NULL OR e.slug = $2) AND ($3::text IS NULL OR e.subject_key = $3) AND e.id > $4
+ ORDER BY e.id LIMIT $5`, [q.sourceId, q.slug ?? null, q.subjectKey ?? null, q.afterId ?? 0, Math.min(Math.max(q.limit ?? 1000, 1), 10_000)]);
+ const json = (v: unknown) => typeof v === 'string' ? JSON.parse(v) : v;
+ const out = rows.map(r => ({ ...r, id: Number(r.id), value: json(r.value) as BeliefHistoryRow['value'], cause: json(r.cause) as BeliefHistoryRow['cause'] }));
+ if (!q.remote) return out.map(({ stream_visible: _, ...row }) => row);
+ const linkIds = [...new Set(out.filter(r => r.subject_kind === 'link' || r.subject_kind === 'link_transition').flatMap(r => linkLifetimes(r.subject_key)))];
+ const visibleLifetimes = new Set(linkIds.length ? (await engine.executeRaw<{ page_lifetime: string }>(`SELECT l.page_lifetime::text AS page_lifetime
+ FROM belief_page_lifetimes l JOIN pages p ON p.source_id = l.source_id AND p.slug = l.slug AND p.deleted_at IS NULL AND (l.page_id IS NULL OR p.id = l.page_id)
+ WHERE l.page_lifetime = ANY($1::uuid[]) AND l.ended_at IS NULL AND ${privatePagesFilterFragment('p')}`, [linkIds])).map(r => r.page_lifetime) : []);
+ return out.filter(r => r.visibility === 'world'
+ && (r.page_lifetime == null ? r.subject_kind === 'fact' : r.stream_visible === true)
+ && (r.subject_kind !== 'link' && r.subject_kind !== 'link_transition' || linkLifetimes(r.subject_key).every(id => visibleLifetimes.has(id))))
+ .map(({ stream_visible: _, ...row }) => row);
+}
diff --git a/test/belief-ledger-privacy.test.ts b/test/belief-ledger-privacy.test.ts
new file mode 100644
index 0000000000..c5547d7316
--- /dev/null
+++ b/test/belief-ledger-privacy.test.ts
@@ -0,0 +1,79 @@
+/**
+ * Belief ledger probe 14 (docs/designs/BELIEF_LEDGER.md sections 8 and 11):
+ * remote history reads leak nothing across private -> public, public ->
+ * private, a reused slug, a private fact on a public page, and a link with a
+ * private endpoint. PGLite and Postgres, each assertion with a forced probe.
+ */
+import { describe, expect, test } from 'bun:test';
+import { rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { readBeliefHistory } from '../src/core/belief/history.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts';
+
+const remote = (b: BeliefBrain, slug?: string) => readBeliefHistory(b.engine, { sourceId: b.sourceId, slug, remote: true });
+const local = (b: BeliefBrain, slug?: string) => readBeliefHistory(b.engine, { sourceId: b.sourceId, slug, remote: false });
+const priv = { visibility: 'private' };
+
+for (const engineCase of testBackends().map(beliefEngineCase)) {
+ describe(`belief ledger privacy (${engineCase.name})`, () => {
+ test('probe 14: private -> public shows only events recorded while world; public -> private hides the whole stream', async () => {
+ await beliefBrain(async b => {
+ await b.put('companies/acme-example', beliefPage({ frontmatter: priv, facts: ['Acme is secretly hiring'] }));
+ expect(await remote(b, 'companies/acme-example')).toEqual([]);
+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme is secretly hiring', 'Acme ships in May'] }));
+ const shown = await remote(b, 'companies/acme-example');
+ const all = await local(b, 'companies/acme-example');
+ expect(all.length).toBeGreaterThan(shown.length);
+ expect(shown.length).toBeGreaterThan(0);
+ expect(shown.every(e => e.visibility === 'world')).toBe(true);
+ expect(all.some(e => e.visibility === 'private' && e.event_type === 'page.published')).toBe(true);
+ await b.put('companies/acme-example', beliefPage({ frontmatter: priv, facts: ['Acme is secretly hiring', 'Acme ships in May'] }));
+ expect(await remote(b, 'companies/acme-example')).toEqual([]);
+ // Forced probe: a reader that checks only the recorded visibility would leak the earlier world events.
+ const recordedOnly = (await local(b, 'companies/acme-example')).filter(e => e.visibility === 'world');
+ expect(recordedOnly.length).toBeGreaterThan(0);
+ }, { managed: true, databaseUrl: engineCase.databaseUrl });
+ }, 120_000);
+
+ test('probe 14: a private fact on a public page and a reused slug stay hidden', async () => {
+ await beliefBrain(async b => {
+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme sells widgets'] }));
+ const mark = await b.lastId();
+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme sells widgets', { claim: 'Acme payroll is late', visibility: 'private' }] }));
+ const fact = (await local(b, 'companies/acme-example')).filter(e => e.id > mark && e.subject_kind === 'fact');
+ expect(fact.map(e => [e.event_type, e.visibility])).toEqual([['fact.asserted', 'private']]);
+ expect((await remote(b, 'companies/acme-example')).some(e => e.id > mark && e.subject_kind === 'fact')).toBe(false);
+ const oldLifetime = (await local(b, 'companies/acme-example'))[0]!.page_lifetime;
+ await b.engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug: 'companies/acme-example' }]);
+ await tx.executeRaw(`DELETE FROM pages WHERE source_id=$1 AND slug='companies/acme-example'`, [b.sourceId]);
+ });
+ rmSync(join(b.root, 'companies/acme-example.md'), { force: true });
+ await b.put('companies/acme-example', beliefPage({ title: 'Acme Reborn', facts: ['Acme is a new company'] }));
+ const reborn = await remote(b, 'companies/acme-example');
+ expect(reborn.length).toBeGreaterThan(0);
+ expect(reborn.every(e => e.page_lifetime !== oldLifetime)).toBe(true);
+ // Forced probe: a reader that resolves an ended lifetime by slug alone would show the old page's history.
+ const bySlug = (await local(b, 'companies/acme-example')).filter(e => e.page_lifetime === oldLifetime && e.visibility === 'world');
+ expect(bySlug.length).toBeGreaterThan(0);
+ }, { databaseUrl: engineCase.databaseUrl });
+ }, 120_000);
+
+ test('probe 14: a link with a private endpoint is hidden until the endpoint is public', async () => {
+ await beliefBrain(async b => {
+ await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example', frontmatter: priv }));
+ await b.put('companies/acme-example', beliefPage({ prose: 'No links.' }));
+ const mark = await b.lastId();
+ await b.put('companies/acme-example', beliefPage({ prose: 'Now linked.', links: ['people/alice-example'] }));
+ const linkEvents = (await local(b, 'companies/acme-example')).filter(e => e.id > mark && e.subject_kind === 'link');
+ expect(linkEvents.map(e => e.event_type)).toEqual(['link.asserted']);
+ expect((await remote(b, 'companies/acme-example')).filter(e => e.subject_kind === 'link')).toEqual([]);
+ await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));
+ expect((await remote(b, 'companies/acme-example')).filter(e => e.subject_kind === 'link').map(e => e.event_type)).toEqual(['link.asserted']);
+ // Forced probe: a reader that checks only the stream page would have shown the link while Alice was private.
+ expect(linkEvents[0]!.visibility).toBe('world');
+ }, { databaseUrl: engineCase.databaseUrl });
+ }, 120_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index c8e04c694b..a9073b3366 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -17,6 +17,7 @@ test/attribution-backfill-history.test.ts
test/backstop-same-page-shadow-managed-6333.test.ts
test/behavior-change-notice.test.ts
test/belief-ledger-lifecycle.test.ts
+test/belief-ledger-privacy.test.ts
test/capture-consent-admission.test.ts
test/capture-dispatch-provenance-6524.test.ts
test/chronicle-backfill-max-usd.test.ts