Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
belief ledger: process-local fingerprint cache; record the overhead pass
garrytanef0b6e76bd8e
diff --git a/docs/architecture/key-files/belief-ledger.md b/docs/architecture/key-files/belief-ledger.mdindex 726f3c669b..446156f600 100644--- a/docs/architecture/key-files/belief-ledger.md+++ b/docs/architecture/key-files/belief-ledger.md@@ -7,7 +7,7 @@ Design: [BELIEF_LEDGER.md](../../designs/BELIEF_LEDGER.md). Operator surface: `g- `src/core/belief/schema.ts` — the ledger DDL (`belief_events`, `belief_page_lifetimes`, `belief_commit_marks`, `belief_redactions`, `belief_retier_manifest`) shared by migration v249 and both schema blobs; `sources.purge_epoch` is migration-only. Edit here, then `bun run build:schema`.- `src/core/belief/keys.ts` — subject keys and hashes. A key never holds a row id: page slugs serialize as the lifetime (`L:<uuid>`), a slug with no page as `S:<incarnation>:<slug>`. Append, replay, lookup and `state_hash` share this one serialization.- `src/core/belief/lifetimes.ts` — page lifetimes, the ledger's page identity: minted at first need, kept across a rename, ended by a hard delete or a recreate; `page_id` is a hint only.-- `src/core/belief/state.ts` / `subjects.ts` — raw stream state (a page, its fence and DB-only facts, takes, and links whose origin, else from, page it is) and its keyed subjects; row ids are payload, never keys.+- `src/core/belief/state.ts` / `subjects.ts` — raw stream state (a page, its fence and DB-only facts, takes, and links whose origin, else from, page it is) and its keyed subjects; row ids are payload, never keys. The post read reuses the pre read's rows for tables the transaction did not write (`pg_stat_xact` counters; a full read with `track_counts` off). The process-local fingerprint cache maps claim-text SHA-256 to `gbrain_fact_fingerprint` only (no text, bounded); `__fingerprintCacheForTests` and `__suppressBeliefTouchedSignalForTests` are the test seams.- `src/core/belief/ledger.ts` — the finalization contract. `withBeliefBatch` reads the state of the held page keys before and after the transaction's projections and appends the canonical diff (origin `live` on a managed brain, `unmanaged` otherwise, or the caller's override). `beliefBatchCovers` and `insideBeliefBatch` let a nested writer skip its own batch. Managed mode comes from `readManagedMode`, never a direct `persistence_brain` read.- `src/core/belief/append.ts` — the one insert (`appendBeliefEvents`): tombstones and the redaction register first, then deterministic `event_key`s. `markBeliefCommits` writes the post-commit observation (`observed_at >= recorded_at`); `__setBeliefEmitterFaultForTests` is the forced-probe seam.- `src/core/belief/coverage.ts` — `enableBeliefLedger` (`coverage.started`, a resumable per-page baseline, `coverage.complete` whose recorded_at is the watermark; certified only on a managed brain) and `disableBeliefLedger` (`coverage.stopped`). Start, complete and stop are decided under the source row FOR UPDATE: a second enable resumes the open run, a disable mid-walk ends it with no `complete`, and the completion re-checks the pending set (a page renamed behind the cursor). A slug no page key can name is skipped and listed (`unkeyable_slugs`). The coverage state is the newest event other than `coverage.restored`, so a restore never restarts a stopped ledger.diff --git a/docs/designs/BELIEF_LEDGER.md b/docs/designs/BELIEF_LEDGER.mdindex 7f627df083..69c3892086 100644--- a/docs/designs/BELIEF_LEDGER.md+++ b/docs/designs/BELIEF_LEDGER.md@@ -1105,10 +1105,39 @@ machine, median of 2 runs, after section 13 item 16:| `beliefs enable` baseline | 1.2 s (1.2 ms/page) | 1.8 s (1.8 ms/page) || `beliefs backfill`, 2 prior versions per page | 9.7 s (25,040 events) | 7.3 s |-Cheaper options, none in W1: skip the post-read of tables a publication did-not write (projections would report what they touched), keep each stream's-subject snapshot on its lifetime row so the pre read is a key lookup, or-force generic plans for the state read on Postgres (about 0.8 ms).+**After the write-overhead pass** (section 13, items 17 to 20). Measured on+the 4-core bench machine with the same `submitPageMutation` bench, master+(v0.60.265.0) against the branch, interleaved, 3 rounds of 15 runs per cell+(median of the round medians):++| Cell | `put_page` ms | Ledger ms in the transaction | Ledger share |+|---|---|---|---|+| PGLite typical edit | 62 → 57 | 3.8–3.9 → 3.7–3.8 | 6.1% → 6.4–6.6% |+| PGLite large edit | 380–385 → 206–210 | 14.6 → 14.0 | 3.8% → 6.7–6.8% |+| Postgres typical edit | 47.5 → 44.4 | 4.5–4.6 → 3.8–3.9 | 9.7% → 8.6–8.7% |+| Postgres large edit | 229–231 → 208–223 | 25.5–28.2 → 23.4–23.6 | 12.2–12.3% → 10.4–11.3% |++The large PGLite share rose because `put_page` lost 45% of its time (the+projections no longer rewrite 225 identical rows), not because the ledger+grew. A typical Postgres edit now spends about 1.25 ms on the pre read,+0.9 ms on the post read, 0.35 ms on lifetimes, 0.3 ms keying, 0.2 ms+diffing, 0.4 ms on the append and 0.4 ms on the commit mark. Large-edit+Postgres medians move by ±3 ms between identical rounds.++Managed sync, create, 1000 typical pages plus 20 people, 5 interleaved reps+per arm on Postgres: off 17.18 s median (16.66–18.99), on 19.37 s median+(18.47–21.76), +12.7%, 7.2 ms per page in the transaction. On PGLite, 2 reps+per arm: 39.4 → 43.6 s, +10.8%. Creates gain nothing from items 17 and 19: a+create writes every table and reads every claim for the first time. The+earlier +24% (lane 32) and +35% (one noisy rep of two) came from too few+reps to quote.++**Targets for turning recording on by default:** typical edit ≤5%, large+edit ≤10% and managed-sync create ≤10% of the write's time, ledger on+against off. After this pass W1 meets none of them on Postgres (typical+8.6–8.7%, large 10.4–11.3%, create +12.7%) and only the large-edit one on+PGLite (typical 6.4–6.6%, large 6.7–6.8%, create +10.8%), so recording stays+opt-in per source (`gbrain beliefs enable`).**Storage** (section 12, question 7, decided). A second free bench insertedthe creation events of 2,000 typical pages into a PGLite table with the full@@ -1502,3 +1531,39 @@ Garry accepted those answers. Questions 5, 6, 7 and 8 are decided.and 2000 pages on PGLite). The read now sets `force_generic_plan` forthat one statement, transaction-local, and restores the previous value;the cost stays about 0.6 ms per page at every size.+17. **Projections skip identical rewrites; the post read reuses untouched+ tables.** The fence fact-field update, the take upsert and the take+ resolution update write only rows whose values change, so a prose edit+ rewrites no fact or take row and `takes.updated_at` moves only when the+ take changes. Nothing reads a rewrite that changes no value: write+ attribution and the trust tier already move only on a value change, and+ every `updated_at` cursor and freshness reader is on `pages`. The post+ read compares the transaction's `pg_stat_get_xact_tuples_*` counters for+ facts, takes, links and link transitions with the pre read's and reuses+ the pre read's rows for every table the transaction did not write, while+ the stream pages are the same pages at the same slugs (fact entity pages+ and link endpoints are read fresh). With `track_counts` off it reads+ everything. A missed write would surface as drift in doctor+ `belief_ledger_coverage`, which a forced probe shows.+18. **Fewer statements per batch.** The source read that opens a batch also+ reads the managed mode and switches to generic plans for the pre read;+ each state read restores the plan mode inside its own statement. When+ the post read reused a table's rows, the post side reuses the pre side's+ fact and take subjects (take visibility from the post side) instead of+ keying them again.+19. **Process-local fingerprint cache.** Each stream read hashes claim texts+ (SHA-256, in SQL) and fingerprints only those whose hash the process has+ not fingerprinted before; `gbrain_fact_fingerprint` costs about 27 µs per+ claim on Postgres, the SHA-256 under 1 µs. The cache maps text hash to+ fingerprint only, never claim text, and is bounded (20,000 fingerprints,+ 2,000 streams, oldest out first). A forced probe compares cached and SQL+ fingerprints for random claims with case, Unicode, punctuation and+ whitespace edge cases on both engines, because a divergence would break+ purge matching. One-shot CLI processes start cold and pay the full read.+20. **Declined: a subject snapshot cache on the lifetime row** (the "cheaper+ option" section 9 listed). After items 17 to 19 a typical Postgres edit+ costs about 3.8 ms of a 44–50 ms write. Removing the pre read entirely+ would leave about 2.6–2.8 ms (5.5–6%); a real cache also needs a+ validity check and a write per batch, so about 6–7%, still above the 5%+ target, for a migration plus invalidation on purge, redaction and+ unmanaged writers. Not built.diff --git a/src/core/belief/state.ts b/src/core/belief/state.tsindex 3ef3f7152f..cea9146786 100644--- a/src/core/belief/state.ts+++ b/src/core/belief/state.ts@@ -19,13 +19,15 @@ export interface RawPage {}export interface RawFact {id: number; entity_slug: string | null; sms: string | null; entity_page_id: number | null; fact: string; fp: string;+ /** SHA-256 of `fact` (the fingerprint cache key); set by the stream reads. */+ th?: string;kind: string; visibility: string; notability: string; context: string | null; confidence: number;valid_from: string | null; valid_until: string | null; claim_metric: string | null; claim_value: number | null;claim_unit: string | null; claim_period: string | null; event_type: string | null; dimension: string | null;value: string | null; value_hash: string | null; row_num: number | null; tier: string;}export interface RawTake {- id: number; page_id: number; row_num: number; claim: string; claim_fp: string; kind: string; holder: string; weight: number;+ id: number; page_id: number; row_num: number; claim: string; claim_fp: string; th?: string; kind: string; holder: string; weight: number;since_date: string | null; until_date: string | null; source: string | null; active: boolean;resolved_at: string | null; resolved_outcome: boolean | null; resolved_value: number | null; resolved_unit: string | null;resolved_source: string | null; resolved_by: string | null; resolved_quality: string | null; tier: string;@@ -58,6 +60,26 @@ const COUNTED = ['facts', 'takes', 'links', 'link_transitions'] as const;/** Rows this transaction has inserted, updated or deleted in each counted table so far (the backend's pending statistics, which only grow within a transaction). */const WRITES = COUNTED.map(table => ['inserted', 'updated', 'deleted'].map(op => `pg_stat_get_xact_tuples_${op}('${table}'::regclass)`).join(' + '));+/** SHA-256 of a claim text, the fingerprint cache's key (`textHash` in JS). */+const TEXT_HASH = (column: string) => `encode(sha256(convert_to(${column}, 'UTF8')), 'hex')`;+export const FINGERPRINT_CACHE_MAX = 20_000;+export const FINGERPRINT_STREAMS_MAX = 2_000;+/**+ * Process-local fingerprint cache: claim-text SHA-256 to its `gbrain_fact_fingerprint`, the stream reads' costliest+ * column (a regexp normalization per row). It holds hashes only, never claim text, and is bounded: the oldest entries+ * go first. `streamHashes` names the text hashes each stream's last read saw, so a read passes the database the+ * hashes whose fingerprints it already has and the database fingerprints only the rest.+ */+const fingerprints = new Map<string, string>();+const streamHashes = new Map<string, string[]>();+const remember = <V>(map: Map<string, V>, key: string, value: V, max: number) => {+ map.delete(key);+ map.set(key, value);+ while (map.size > max) map.delete(map.keys().next().value!);+};+/** Test-only: the cache's contents, to poison an entry or clear it. */+export function __fingerprintCacheForTests(): { fingerprints: Map<string, string>; streams: Map<string, string[]> } { return { fingerprints, streams: streamHashes }; }+let touchedSignalSuppressed = false;/** Test-only: report every counted table as unwritten, so a re-read reuses the earlier rows whatever the transaction wrote. */export function __suppressBeliefTouchedSignalForTests(suppressed: boolean): void { touchedSignalSuppressed = suppressed; }@@ -73,14 +95,19 @@ export function __suppressBeliefTouchedSignalForTests(suppressed: boolean): voidexport async function readBeliefState(tx: BrainEngine, sourceId: string, slugs: readonly string[], pageIds: readonly number[] = [], known?: RawState,planModePrev?: string): Promise<RawState> {// One statement: each part selects the batch's pages itself ($1 source, $2 slugs, $3 page ids) and returns its rows as JSON.- // Fingerprints of claim texts `known` (the batch's pre-read) already has are not recomputed: the SQL fingerprint- // is most of a large page's read. The statement runs with a generic plan (restored after): under the default+ // Fingerprints of claim texts whose hash `known` (the batch's pre-read) or the cache already has are not recomputed+ // ($4 those hashes and fingerprints, a JSON object): the SQL fingerprint is most of a large page's read. The statement runs with a generic plan (restored after): under the default// plan_cache_mode a bulk import re-plans it for every page as the tables grow (about 3 ms each, rising with size).// $5 `known`'s counters, $6 its stream pages (id:slug), $7 its facts' entity slugs, $8 the test suppression,// $9 the plan_cache_mode to restore (the statement is planned before it runs, so it restores the mode itself);// `planModePrev`: the caller already switched to generic plans (readLedgerSource's `batch`) and this is the mode it replaced.- const knownFp = new Map<string, string>([...(known?.facts ?? []).map(f => [f.fact, f.fp] as const), ...(known?.takes ?? []).map(k => [k.claim, k.claim_fp] as const)]);- const params = [sourceId, [...slugs], [...pageIds], [...knownFp.keys()], known?.counts ?? null, (known?.pages ?? []).map(p => `${p.id}:${p.slug}`),+ const streamKey = (slug: string) => `${sourceId}\u0000${slug}`;+ const knownFp = new Map<string, string>([...(known?.facts ?? []).map(f => [f.th, f.fp] as const), ...(known?.takes ?? []).map(k => [k.th, k.claim_fp] as const)]+ .flatMap(([th, fp]) => th === undefined ? [] : [[th, fp] as [string, string]]));+ for (const slug of new Set([...slugs, ...(known?.pages ?? []).map(p => p.slug)])) {+ for (const hash of streamHashes.get(streamKey(slug)) ?? []) { const fp = fingerprints.get(hash); if (fp !== undefined) knownFp.set(hash, fp); }+ }+ const params = [sourceId, [...slugs], [...pageIds], JSON.stringify(Object.fromEntries(knownFp)), known?.counts ?? null, (known?.pages ?? []).map(p => `${p.id}:${p.slug}`),[...new Set((known?.facts ?? []).flatMap(f => f.entity_slug == null ? [] : [f.entity_slug]))], touchedSignalSuppressed];const STREAM_SLUGS = `$2::text[] || ARRAY(SELECT p.slug FROM pages p WHERE p.source_id = $1 AND p.id = ANY($3::int[]))`;const PAGE_IDS = `ARRAY(SELECT p.id FROM pages p WHERE p.source_id = $1 AND (p.slug = ANY($2::text[]) OR p.id = ANY($3::int[])))`;@@ -91,7 +118,8 @@ ${sql}) q) END`;set_config('plan_cache_mode', 'force_generic_plan', true)`))[0]!.prev);const [row] = await tx.executeRaw<Record<string, Record<string, unknown>[] | null>>(`WITH reuse AS (SELECT ($8::boolean OR current_setting('track_counts') = 'on')AND $5::text[] IS NOT NULL AND ARRAY(SELECT p.id || ':' || p.slug FROM pages p- WHERE p.source_id = $1 AND (p.slug = ANY($2::text[]) OR p.id = ANY($3::int[])) ORDER BY 1) = ARRAY(SELECT unnest($6::text[]) ORDER BY 1) AS ok)+ WHERE p.source_id = $1 AND (p.slug = ANY($2::text[]) OR p.id = ANY($3::int[])) ORDER BY 1) = ARRAY(SELECT unnest($6::text[]) ORDER BY 1) AS ok),+ known_fp AS (SELECT $4::text::jsonb AS m)SELECT set_config('plan_cache_mode', $9, true) AS restored,(SELECT COALESCE(json_agg(q), '[]'::json) FROM (SELECT p.id, p.slug, p.deleted_at IS NOT NULL AS deleted, p.knowledge_revision::text AS revision,@@ -101,19 +129,20 @@ SELECT p.id, p.slug, p.deleted_at IS NOT NULL AS deleted, p.knowledge_revision::FROM pages p JOIN sources s ON s.id = p.source_idWHERE p.source_id = $1 AND (p.slug = ANY($2::text[]) OR p.id = ANY($3::int[]))) q) AS pages,CASE WHEN current_setting('track_counts') = 'on' THEN json_build_array(${WRITES.map(w => `(${w})::text`).join(', ')}) END AS counts,- ${part(0, `SELECT f.id, f.entity_slug, f.source_markdown_slug AS sms, pe.id AS entity_page_id, f.fact,- CASE WHEN f.fact = ANY($4::text[]) THEN NULL ELSE gbrain_fact_fingerprint(f.fact) END AS fp, f.kind, f.visibility, f.notability, f.context, f.confidence::text AS confidence,+ ${part(0, `SELECT f.id, f.entity_slug, f.source_markdown_slug AS sms, pe.id AS entity_page_id, f.fact, h.th,+ COALESCE((SELECT m FROM known_fp) ->> h.th, gbrain_fact_fingerprint(f.fact)) AS fp, f.kind, f.visibility, f.notability, f.context, f.confidence::text AS confidence,f.valid_from, f.valid_until, f.claim_metric, f.claim_value::text AS claim_value, f.claim_unit, f.claim_period, f.event_type,f.dimension, f.value, f.value_hash, f.row_num, f.trust_tierFROM (SELECT * FROM facts WHERE source_id = $1 AND expired_at IS NULL AND source_markdown_slug = ANY(${STREAM_SLUGS})UNION ALL SELECT * FROM facts WHERE source_id = $1 AND expired_at IS NULL AND source_markdown_slug IS NULL AND entity_slug = ANY(${STREAM_SLUGS})) f+ CROSS JOIN LATERAL (SELECT ${TEXT_HASH('f.fact')} AS th) hLEFT JOIN pages pe ON pe.source_id = f.source_id AND pe.slug = f.entity_slug`)} AS facts,CASE WHEN ${unwritten(0)} THEN (SELECT COALESCE(json_agg(json_build_array(p.slug, p.id)), '[]'::json) FROM pages pWHERE p.source_id = $1 AND p.slug = ANY($7::text[])) END AS entity_pages,- ${part(1, `SELECT k.id, k.page_id, k.row_num, k.claim, CASE WHEN k.claim = ANY($4::text[]) THEN NULL ELSE gbrain_fact_fingerprint(k.claim) END AS claim_fp,+ ${part(1, `SELECT k.id, k.page_id, k.row_num, k.claim, h.th, COALESCE((SELECT m FROM known_fp) ->> h.th, gbrain_fact_fingerprint(k.claim)) AS claim_fp,k.kind, k.holder, k.weight::text AS weight, k.since_date, k.until_date, k.source, k.active, k.resolved_at, k.resolved_outcome,k.resolved_value::text AS resolved_value, k.resolved_unit, k.resolved_source, k.resolved_by, k.resolved_quality, k.trust_tier- FROM takes k WHERE k.page_id = ANY(${PAGE_IDS})`)} AS takes,+ FROM takes k CROSS JOIN LATERAL (SELECT ${TEXT_HASH('k.claim')} AS th) h WHERE k.page_id = ANY(${PAGE_IDS})`)} AS takes,${part(2, `SELECT l.id, l.from_page_id AS f, l.to_page_id AS t, l.origin_page_id AS o,l.link_type, l.link_source, l.context, l.origin_field, l.link_kind, l.resolution_type, l.assertion_tenseFROM (${OWNED_ROWS('links', PAGE_IDS)}) l`)} AS links,@@ -131,12 +160,23 @@ SELECT p.id, p.slug, p.source_id, s.incarnation::text AS incarnation FROM pagescontent_hash: (r.content_hash as string | null) ?? null, tier: String(r.trust_tier), visible: r.visible === true, large: r.large === true,incarnation: String(r.incarnation) }));const entityPageOf = new Map(((entityPages ?? []) as unknown as Array<[string, number]>).map(([slug, id]) => [slug, Number(id)]));+ const factRows = facts ? facts.map(toFact) : null;+ const takeRows = takes ? takes.map(toTake) : null;+ const slugOfPage = new Map(pages.map(p => [p.id, p.slug]));+ const seen = new Map<string, string[]>();+ for (const [slug, th, fp] of [...(factRows ?? known!.facts).map(f => [f.sms ?? f.entity_slug ?? '', f.th, f.fp] as const),+ ...(takeRows ?? known!.takes).map(k => [slugOfPage.get(k.page_id) ?? '', k.th, k.claim_fp] as const)]) {+ if (th === undefined) continue;+ remember(fingerprints, th, fp, FINGERPRINT_CACHE_MAX);+ const hashes = seen.get(slug);+ if (hashes) hashes.push(th); else seen.set(slug, [th]);+ }+ for (const [slug, hashes] of seen) remember(streamHashes, streamKey(slug), hashes, FINGERPRINT_STREAMS_MAX);return {pages,- facts: facts ? facts.map(r => toFact(r.fp == null ? { ...r, fp: knownFp.get(String(r.fact)) } : r))- : known!.facts.some(f => f.entity_page_id !== (f.entity_slug == null ? null : entityPageOf.get(f.entity_slug) ?? null))- ? known!.facts.map(f => ({ ...f, entity_page_id: f.entity_slug == null ? null : entityPageOf.get(f.entity_slug) ?? null })) : known!.facts,- takes: takes ? takes.map(r => toTake(r.claim_fp == null ? { ...r, claim_fp: knownFp.get(String(r.claim)) } : r)) : known!.takes,+ facts: factRows ?? (known!.facts.some(f => f.entity_page_id !== (f.entity_slug == null ? null : entityPageOf.get(f.entity_slug) ?? null))+ ? known!.facts.map(f => ({ ...f, entity_page_id: f.entity_slug == null ? null : entityPageOf.get(f.entity_slug) ?? null })) : known!.facts),+ takes: takeRows ?? known!.takes,links: links ? links.map(r => ({ id: Number(r.id), from: endpoint(r.f)!, to: endpoint(r.t)!, origin: endpoint(r.o), link_type: String(r.link_type),link_source: (r.link_source as string | null) ?? null, context: String(r.context ?? ''), origin_field: (r.origin_field as string | null) ?? null,link_kind: (r.link_kind as string | null) ?? null, resolution_type: (r.resolution_type as string | null) ?? null,@@ -156,7 +196,7 @@ SELECT p.id, p.slug, p.source_id, s.incarnation::text AS incarnation FROM pagesexport async function readFactsById(tx: BrainEngine, ids: readonly number[]): Promise<RawFact[]> {if (!ids.length) return [];const rows = await tx.executeRaw<Record<string, unknown>>(`SELECT f.id, f.entity_slug, f.source_markdown_slug AS sms, pe.id AS entity_page_id, f.fact,- gbrain_fact_fingerprint(f.fact) AS fp, f.kind, f.visibility, f.notability, f.context, f.confidence::text AS confidence,+ gbrain_fact_fingerprint(f.fact) AS fp, ${TEXT_HASH('f.fact')} AS th, f.kind, f.visibility, f.notability, f.context, f.confidence::text AS confidence,f.valid_from, f.valid_until, f.claim_metric, f.claim_value::text AS claim_value, f.claim_unit, f.claim_period, f.event_type,f.dimension, f.value, f.value_hash, f.row_num, f.trust_tierFROM facts f LEFT JOIN pages pe ON pe.source_id = f.source_id AND pe.slug = f.entity_slug WHERE f.id = ANY($1::bigint[])`, [[...ids]]);@@ -165,7 +205,7 @@ export async function readFactsById(tx: BrainEngine, ids: readonly number[]): Prfunction toFact(r: Record<string, unknown>): RawFact {return { id: Number(r.id), entity_slug: (r.entity_slug as string | null) ?? null, sms: (r.sms as string | null) ?? null,- entity_page_id: num(r.entity_page_id), fact: String(r.fact), fp: String(r.fp), kind: String(r.kind), visibility: String(r.visibility),+ entity_page_id: num(r.entity_page_id), fact: String(r.fact), fp: String(r.fp), th: String(r.th), kind: String(r.kind), visibility: String(r.visibility),notability: String(r.notability), context: (r.context as string | null) ?? null, confidence: Number(r.confidence),valid_from: iso(r.valid_from), valid_until: iso(r.valid_until), claim_metric: (r.claim_metric as string | null) ?? null,claim_value: num(r.claim_value), claim_unit: (r.claim_unit as string | null) ?? null, claim_period: (r.claim_period as string | null) ?? null,@@ -174,7 +214,7 @@ function toFact(r: Record<string, unknown>): RawFact {}function toTake(r: Record<string, unknown>): RawTake {- return { id: Number(r.id), page_id: Number(r.page_id), row_num: Number(r.row_num), claim: String(r.claim), claim_fp: String(r.claim_fp),+ return { id: Number(r.id), page_id: Number(r.page_id), row_num: Number(r.row_num), claim: String(r.claim), claim_fp: String(r.claim_fp), th: String(r.th),kind: String(r.kind), holder: String(r.holder), weight: Number(r.weight), since_date: (r.since_date as string | null) ?? null,until_date: (r.until_date as string | null) ?? null, source: (r.source as string | null) ?? null, active: r.active === true,resolved_at: iso(r.resolved_at), resolved_outcome: (r.resolved_outcome as boolean | null) ?? null, resolved_value: num(r.resolved_value),diff --git a/test/belief-ledger-touched.test.ts b/test/belief-ledger-touched.test.tsindex 66653ee27d..57f7b34c9e 100644--- a/test/belief-ledger-touched.test.ts+++ b/test/belief-ledger-touched.test.ts@@ -7,7 +7,8 @@* touched signal and shows the drift check catches the event it loses.*/import { afterEach, describe, expect, test } from 'bun:test';-import { __suppressBeliefTouchedSignalForTests, readBeliefState, type RawState } from '../src/core/belief/state.ts';+import { createHash } from 'node:crypto';+import { FINGERPRINT_CACHE_MAX, __fingerprintCacheForTests, __suppressBeliefTouchedSignalForTests, readBeliefState, type RawState } from '../src/core/belief/state.ts';import { withBeliefBatch } from '../src/core/belief/ledger.ts';import { keyedSubjects } from '../src/core/belief/subjects.ts';import { beliefLedgerEntry } from '../src/commands/doctor/checks/belief-ledger.ts';@@ -36,8 +37,68 @@ async function doctor(b: BeliefBrain): Promise<Check> {return check!;}+/** Claims that stress the fingerprint's normalization: case, Unicode, punctuation, dots and every kind of whitespace. */+const EDGE_PIECES = ['Acme', 'ACME', 'acme', 'İstanbul', 'ß', 'Straße', 'é', 'e\u0301', 'naïve', '日本語', '😀', '\u00a0', '\u2003', '\t', '\n', ' ', ' ',+ '.', '...', '…', '. .', 'U.S.', 'v2.0', ',', '!', '"', "'", '‘’', '“”', '«»', '–', '—', '·', '•', '¡', '¿', '(x)', '[y]', '{z}', '|', '\\', '/', '$5', '%', '&', '@', '#1', '_', '~', '^'];+function edgeClaims(count: number): string[] {+ let seed = 0x5eed;+ const next = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;+ const out = ['Acme raised a seed round', ' acme raised a seed round. ', 'ACME RAISED\tA SEED\nROUND...', 'Acme raised a seed round…', '\u00a0Acme\u2003raised a seed round'];+ while (out.length < count) out.push(Array.from({ length: 2 + Math.floor(next() * 8) }, () => EDGE_PIECES[Math.floor(next() * EDGE_PIECES.length)]).join(next() < 0.5 ? ' ' : ''));+ return [...new Set(out.filter(c => c.trim().length))];+}+for (const engineCase of testBackends().map(beliefEngineCase)) {describe(`belief ledger write overhead (${engineCase.name})`, () => {+ test('the fingerprint cache returns exactly gbrain_fact_fingerprint for edge-case claims (forced probe: a poisoned entry is caught)', async () => {+ await beliefBrain(async b => {+ await b.put(SLUG, beliefPage({ prose: 'Edge cases.' }));+ const [{ id: pageId }] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2', [b.sourceId, SLUG]);+ const claims = edgeClaims(160);+ await b.engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, source, visibility, confidence)+ SELECT $1, $2, c, 'fact', 'probe', 'world', 1 FROM unnest($3::text[]) AS c`, [b.sourceId, SLUG, claims]);+ await b.engine.executeRaw(`INSERT INTO takes (page_id, row_num, claim, kind, holder, weight)+ SELECT $1, n::int, c, 'take', 'brain', 0.5 FROM unnest($2::text[]) WITH ORDINALITY AS t(c, n)`, [pageId, claims.slice(0, 60)]);+ const truth = new Map((await b.engine.executeRaw<{ fact: string; fp: string; th: string }>(`SELECT c AS fact, gbrain_fact_fingerprint(c) AS fp,+ encode(sha256(convert_to(c, 'UTF8')), 'hex') AS th FROM unnest($1::text[]) AS c`, [claims])).map(r => [r.fact, r]));+ for (const claim of claims) expect(truth.get(claim)!.th).toBe(createHash('sha256').update(claim, 'utf8').digest('hex'));+ const mismatches = (state: RawState) => [...state.facts.map(f => [f.fact, f.fp] as const), ...state.takes.map(k => [k.claim, k.claim_fp] as const)]+ .filter(([text, fp]) => truth.get(text)!.fp !== fp).map(([text]) => text);+ const cache = __fingerprintCacheForTests();+ cache.fingerprints.clear(); cache.streams.clear();+ const cold = await readBeliefState(b.engine, b.sourceId, [SLUG]);+ expect(cold.facts).toHaveLength(claims.length);+ expect(cold.takes).toHaveLength(60);+ expect(mismatches(cold)).toEqual([]);+ for (const claim of claims) expect(cache.fingerprints.get(truth.get(claim)!.th)).toBe(truth.get(claim)!.fp);+ const warm = await readBeliefState(b.engine, b.sourceId, [SLUG]);+ expect(mismatches(warm)).toEqual([]);+ const victim = claims[1]!;+ cache.fingerprints.set(truth.get(victim)!.th, 'poisoned');+ expect(mismatches(await readBeliefState(b.engine, b.sourceId, [SLUG]))).toEqual([victim, ...(claims.slice(0, 60).includes(victim) ? [victim] : [])]);+ cache.fingerprints.clear(); cache.streams.clear();+ }, { managed: false, enable: false, databaseUrl: engineCase.databaseUrl });+ }, 120_000);++ test('the fingerprint cache stays within its bounds and holds no claim text', async () => {+ const cache = __fingerprintCacheForTests();+ await beliefBrain(async b => {+ await b.put(SLUG, beliefPage({ facts: ['Acme raised a seed round', 'Acme has ten staff'], takes: ['Acme will win its market'] }));+ await readBeliefState(b.engine, b.sourceId, [SLUG]);+ const texts = ['Acme raised a seed round', 'Acme has ten staff', 'Acme will win its market'];+ for (const [key, value] of cache.fingerprints) expect([key, value].some(v => texts.some(t => v.includes(t)))).toBe(false);+ for (const [key, hashes] of cache.streams) expect([key, ...hashes].some(v => texts.some(t => v.includes(t.toLowerCase()) || v.includes(t)))).toBe(false);+ }, { managed: false, enable: false, databaseUrl: engineCase.databaseUrl });+ for (let i = 0; i < FINGERPRINT_CACHE_MAX + 50; i++) cache.fingerprints.set(`h${i}`, 'f');+ await beliefBrain(async b => {+ await b.put(SLUG, beliefPage({ facts: ['Acme raised a seed round'] }));+ await readBeliefState(b.engine, b.sourceId, [SLUG]);+ expect(cache.fingerprints.size).toBe(FINGERPRINT_CACHE_MAX);+ expect(cache.fingerprints.has('h0')).toBe(false);+ }, { managed: false, enable: false, databaseUrl: engineCase.databaseUrl });+ cache.fingerprints.clear(); cache.streams.clear();+ }, 120_000);+const brain = (run: (b: BeliefBrain) => Promise<void>, managed = true) => beliefBrain(run, { managed, databaseUrl: engineCase.databaseUrl });const seeded = async (b: BeliefBrain) => {await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));