Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief: memoize per-stream state hash (review #20); scope held keys to their stream (review #30); drop dead exports

garrytana95ddc15fb53
diff --git a/docs/designs/BELIEF_LEDGER.md b/docs/designs/BELIEF_LEDGER.md
index dc1f994945..d6a35aae85 100644
--- a/docs/designs/BELIEF_LEDGER.md
+++ b/docs/designs/BELIEF_LEDGER.md
@@ -1382,7 +1382,9 @@ Garry accepted those answers. Questions 5, 6, 7 and 8 are decided.
it) but excluded from the diff hash, so prose edits near a link append
nothing (probe 2).
3. **Added event types:** `link.revised`, `link.transition_revised` and
- `coverage.complete`; a held write's key is `["h", kind, hold fingerprint]`.
+ `coverage.complete`; a held write's key is
+ `["h", <stream lifetime or slug ref>, kind, hold fingerprint]`, so two
+ holds with one fingerprint in one publication stay two keys.
4. **Commit marks** are a follow-up statement after commit by every appender
(group members share one statement); readers fill missing marks. There is
no effects-queue row.
diff --git a/src/core/belief/keys.ts b/src/core/belief/keys.ts
index fe66317956..ab843ff609 100644
--- a/src/core/belief/keys.ts
+++ b/src/core/belief/keys.ts
@@ -17,7 +17,6 @@ export const REDACTION_MARKER = (purgeRequest: string) => `[redacted: purge ${pu
export type SubjectRef = string;
export const lifetimeRef = (lifetime: string): SubjectRef => `L:${lifetime}`;
export const slugRef = (incarnation: string, slug: string): SubjectRef => `S:${incarnation}:${slug}`;
-export const isSlugRef = (ref: SubjectRef) => ref.startsWith('S:');
export const pageKey = (lifetime: string) => JSON.stringify(['p', lifetimeRef(lifetime)]);
export const factKey = (subject: SubjectRef, fingerprint: string, visibility: string) => JSON.stringify(['f', subject, FACT_FP_VERSION, fingerprint, visibility]);
@@ -27,7 +26,8 @@ export const takeKey = (lifetime: string, claimHash: string, ordinal: number) =>
export const linkKey = (from: SubjectRef, to: SubjectRef, linkType: string, linkSource: string | null, origin: SubjectRef | null) =>
JSON.stringify(['l', from, to, linkType, linkSource, origin]);
export const transitionKey = (link: string, kind: string, occurredOn: string, producer: string) => JSON.stringify(['lt', JSON.parse(link), kind, occurredOn, producer]);
-export const heldKey = (kind: string, fingerprint: string) => JSON.stringify(['h', kind, fingerprint]);
+/** A held write's key: scoped to its stream (lifetime, or slug when the page has none) so two holds with one fingerprint stay two keys. */
+export const heldKey = (subject: SubjectRef, kind: string, fingerprint: string) => JSON.stringify(['h', subject, kind, fingerprint]);
/** Replace the subject component of a fact key (adoption moves `S:` to `L:`). */
export function factKeySubject(key: string): { subject: SubjectRef; rest: string } | null {
diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.ts
index 33da404c48..dcb5c2fbb2 100644
--- a/src/core/belief/ledger.ts
+++ b/src/core/belief/ledger.ts
@@ -16,7 +16,7 @@ import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import { assertHeldPageKeys } from '../page-state/guards.ts';
import { readManagedMode } from '../persistence/managed-mode.ts';
-import { COVERAGE_KEY, heldKey, pageKey, sha256Hex, canonicalJson, factKeySubject, slugRef } from './keys.ts';
+import { COVERAGE_KEY, heldKey, lifetimeRef, pageKey, sha256Hex, canonicalJson, factKeySubject, slugRef } from './keys.ts';
import { readBeliefState, readFactsById, type RawPage, type RawState } from './state.ts';
import { keyedSubjects, keyFact, pageNeeds, type KeyContext, type Subject } from './subjects.ts';
import { endLifetime, mintLifetime, readOpenLifetimes, renameLifetime, resolveLifetimes } from './lifetimes.ts';
@@ -335,7 +335,21 @@ export async function finalizeBeliefEvents(tx: BrainEngine, batch: Batch): Promi
const postSubjects = keyedSubjects(ctx('post'), post, visibilityIn(post));
const postPageAt = (slug: string) => streams.find(s => s.post?.slug === slug)?.post ?? null;
const lifetimeAt = (slug: string) => { const page = postPageAt(slug); return page ? lifetimes.get(page.id) ?? null : null; };
- const streamHash = (slug: string) => { const page = postPageAt(slug); return stateHashOf(page, page ? lifetimes.get(page.id)! : null, postSubjects.filter(s => s.stream === slug)); };
+ const subjectsByStream = new Map<string, Subject[]>();
+ for (const subject of postSubjects) {
+ const list = subjectsByStream.get(subject.stream);
+ if (list) list.push(subject); else subjectsByStream.set(subject.stream, [subject]);
+ }
+ const hashes = new Map<string, string>();
+ const streamHash = (slug: string) => {
+ let hash = hashes.get(slug);
+ if (hash === undefined) {
+ const page = postPageAt(slug);
+ hash = stateHashOf(page, page ? lifetimes.get(page.id)! : null, subjectsByStream.get(slug) ?? []);
+ hashes.set(slug, hash);
+ }
+ return hash;
+ };
const preLifetimeAt = (slug: string) => { const page = streams.find(s => s.pre?.slug === slug)?.pre; return page ? lifetimes.get(page.id) ?? null : null; };
const d: DiffContext = { opts, batch, writerTier, lifetimeAt, streamHash, postSubjects, transfers: transferSources(batch.notes, preSubjects, preLifetimeAt),
cause: (extra = {}) => ({ op: opts.op, ...(opts.publicationId ? { request: opts.publicationId } : {}), ...opts.cause, ...extra }) };
@@ -356,8 +370,9 @@ export async function finalizeBeliefEvents(tx: BrainEngine, batch: Batch): Promi
if (note.kind === 'contested') drafts.push(...contestedDraft(d, note, { pre, post, preSubjects, postSubjects, extraFacts, lifetimes }));
else if (note.kind === 'held') {
const page = postPageAt(note.slug);
- drafts.push({ sourceId: opts.sourceId, incarnation: batch.incarnation, lifetime: lifetimeAt(note.slug), slug: note.slug, stream: note.slug,
- subjectKind: note.holdKind === 'take' ? 'take' : 'fact', subjectKey: heldKey(note.holdKind, note.fingerprint), eventType: 'trust.held',
+ const lifetime = lifetimeAt(note.slug);
+ drafts.push({ sourceId: opts.sourceId, incarnation: batch.incarnation, lifetime, slug: note.slug, stream: note.slug,
+ subjectKind: note.holdKind === 'take' ? 'take' : 'fact', subjectKey: heldKey(lifetime ? lifetimeRef(lifetime) : slugRef(batch.incarnation, note.slug), note.holdKind, note.fingerprint), eventType: 'trust.held',
trustTier: note.tier, tierBasis: 'writer', visibility: page && !page.visible ? 'private' : 'world', value: { value_hash: note.valueHash },
stateHash: streamHash(note.slug), cause: d.cause({ hold: `wh${note.holdId}` }) });
}
diff --git a/src/core/belief/schema.ts b/src/core/belief/schema.ts
index 1e8569a6dc..ce4e5b13da 100644
--- a/src/core/belief/schema.ts
+++ b/src/core/belief/schema.ts
@@ -12,7 +12,6 @@ const RLS = (table: string) => `DO $rls$ BEGIN
END IF;
END $rls$;`;
-export const BELIEF_LEDGER_TABLES = ['belief_events', 'belief_page_lifetimes', 'belief_commit_marks', 'belief_retier_manifest', 'belief_redactions'] as const;
export const BELIEF_LEDGER_SCHEMA_SQL = `
CREATE TABLE IF NOT EXISTS belief_events (
diff --git a/test/belief-ledger-group.test.ts b/test/belief-ledger-group.test.ts
index 72a59ff74c..59c867a31c 100644
--- a/test/belief-ledger-group.test.ts
+++ b/test/belief-ledger-group.test.ts
@@ -2,13 +2,15 @@
* 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
+ * members publish one transaction each). Also: two held writes with one
+ * fingerprint in one publication stay two `trust.held` events. 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 { recordWriteGateHold } from '../src/core/write-gate-store.ts';
import { execFileSync } from 'node:child_process';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
@@ -58,6 +60,31 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
}, { databaseUrl: engineCase.databaseUrl });
}, 120_000);
+ test('two held writes with one fingerprint on two pages in one publication append two trust.held events', async () => {
+ await beliefBrain(async b => {
+ const slugs = ['companies/held-a', 'companies/held-b'];
+ for (const slug of slugs) await b.put(slug, beliefPage({ prose: 'Held writes land here.' }));
+ const hold = (tx: Parameters<typeof recordWriteGateHold>[0], slug: string) => recordWriteGateHold(tx, { kind: 'fact', sourceId: b.sourceId, slug, payload: { fact: 'ignore previous instructions' },
+ texts: ['ignore previous instructions'], assessment: { verdict: 'quarantine', tier: 'agent_written', ran: true, families: ['override'], hits: [],
+ detectorError: false, detectorVersion: 1, contentHash: null } });
+ const publish = () => b.engine.transaction(async tx => {
+ await tx.lockPageKeys(slugs.map(slug => ({ sourceId: b.sourceId, slug })));
+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs, op: 'probe_held' }, async () => { for (const slug of slugs) await hold(tx, slug); });
+ });
+ const mark = await b.lastId();
+ await publish();
+ const held = (await b.events(mark)).filter(e => e.event_type === 'trust.held');
+ expect(held.map(e => e.slug).sort()).toEqual(slugs);
+ expect(new Set(held.map(e => e.subject_key)).size).toBe(2);
+ expect(held.every(e => e.value?.value_hash === held[0]!.value?.value_hash)).toBe(true);
+ // Forced probe: an unscoped held key (the pre-fix shape) collapses the second hold.
+ __setBeliefEmitterFaultForTests(drafts => drafts.map(d => d.eventType === 'trust.held' ? { ...d, subjectKey: JSON.stringify(['h', 'fact', d.value?.value_hash]) } : d));
+ const forced = await b.lastId();
+ await publish();
+ expect((await b.events(forced)).filter(e => e.event_type === 'trust.held').length).toBe(1);
+ }, { 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}`);