Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger: projections skip identical rewrites; post-read reuses untouched tables

garrytan08cea0f9e375
diff --git a/src/core/belief/state.ts b/src/core/belief/state.ts
index 9e7cc35ff2..618ba3a1b8 100644
--- a/src/core/belief/state.ts
+++ b/src/core/belief/state.ts
@@ -39,7 +39,9 @@ export interface RawTransition {
id: number; from: RawEndpoint; to: RawEndpoint; origin: RawEndpoint | null; link_type: string; kind: string;
occurred_on: string; date_precision: string; producer: string; line_hash: string;
}
-export interface RawState { pages: RawPage[]; facts: RawFact[]; takes: RawTake[]; links: RawLink[]; transitions: RawTransition[]; writerTier: string | null }
+/** `counts`: the transaction's write counters for facts, takes, links and link_transitions at the read (null: `track_counts` is off). */
+export interface RawState { pages: RawPage[]; facts: RawFact[]; takes: RawTake[]; links: RawLink[]; transitions: RawTransition[]; writerTier: string | null;
+ counts?: string[] | null }
const iso = (value: unknown): string | null => value == null ? null : new Date(value as string).toISOString();
const num = (value: unknown): number | null => value == null ? null : Number(value);
@@ -52,22 +54,41 @@ const ENDS = 'from_page_id, to_page_id, origin_page_id';
const OWNED_ROWS = (table: 'links' | 'link_transitions', ids: string, columns = '*') => `SELECT ${columns} FROM ${table} WHERE origin_page_id = ANY(${ids})
UNION ALL SELECT ${columns} FROM ${table} WHERE origin_page_id IS NULL AND from_page_id = ANY(${ids}) OFFSET 0`;
+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(' + '));
+
+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; }
+
/**
* One pipeline of five reads. `slugs` select the stream pages and the facts
* keyed to them; `pageIds` add pages by id (a renamed page is found at its new
- * slug); `factIds`/`takeIds` add rows a guard named that live in another stream.
+ * slug). With `known` (the batch's pre-read), a counted table this transaction
+ * has not written since `known` was read is not read again while the stream
+ * pages are the same pages at the same slugs: its rows are `known`'s, with fact
+ * entity pages and link endpoints read fresh. With `track_counts` off every part is read.
*/
export async function readBeliefState(tx: BrainEngine, sourceId: string, slugs: readonly string[], pageIds: readonly number[] = [], known?: RawState): 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
// 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.
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()]];
+ const params = [sourceId, [...slugs], [...pageIds], [...knownFp.keys()], 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[])))`;
+ const unwritten = (i: number) => `(SELECT ok FROM reuse) AND ($8::boolean OR (${WRITES[i]})::text = ($5::text[])[${i + 1}])`;
+ const part = (i: number, sql: string) => `CASE WHEN ${unwritten(i)} THEN NULL ELSE (SELECT COALESCE(json_agg(q), '[]'::json) FROM (
+${sql}) q) END`;
const [mode] = await tx.executeRaw<{ prev: string }>(`SELECT current_setting('plan_cache_mode') AS prev, set_config('plan_cache_mode', 'force_generic_plan', true)`);
- const [row] = await tx.executeRaw<Record<string, Record<string, unknown>[]>>(`SELECT
+ 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)
+ SELECT
(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,
p.content_hash, p.trust_tier, (${privatePagesFilterFragment('p')}) AS visible, s.incarnation::text AS incarnation,
@@ -75,51 +96,55 @@ SELECT p.id, p.slug, p.deleted_at IS NOT NULL AS deleted, p.knowledge_revision::
current_setting('gbrain.write_trust_tier', true) AS writer_tier
FROM pages p JOIN sources s ON s.id = p.source_id
WHERE p.source_id = $1 AND (p.slug = ANY($2::text[]) OR p.id = ANY($3::int[]))) q) AS pages,
- (SELECT COALESCE(json_agg(q), '[]'::json) FROM (
-SELECT f.id, f.entity_slug, f.source_markdown_slug AS sms, pe.id AS entity_page_id, f.fact,
+ 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,
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_tier
FROM (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
- LEFT JOIN pages pe ON pe.source_id = f.source_id AND pe.slug = f.entity_slug) q) AS facts,
- (SELECT COALESCE(json_agg(q), '[]'::json) FROM (
-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,
+ LEFT 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 p
+ WHERE 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,
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})) q) AS takes,
- (SELECT COALESCE(json_agg(q), '[]'::json) FROM (
-SELECT l.id, l.from_page_id AS f, l.to_page_id AS t, l.origin_page_id AS o,
+ FROM takes k 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_tense
- FROM (${OWNED_ROWS('links', PAGE_IDS)}) l) q) AS links,
- (SELECT COALESCE(json_agg(q), '[]'::json) FROM (
-SELECT x.id, x.from_page_id AS f, x.to_page_id AS t, x.origin_page_id AS o,
+ FROM (${OWNED_ROWS('links', PAGE_IDS)}) l`)} AS links,
+ ${part(3, `SELECT x.id, x.from_page_id AS f, x.to_page_id AS t, x.origin_page_id AS o,
x.link_type, x.kind, x.occurred_on::text AS occurred_on, x.date_precision, x.producer, x.line_hash
- FROM (${OWNED_ROWS('link_transitions', PAGE_IDS)}) x) q) AS transitions,
+ FROM (${OWNED_ROWS('link_transitions', PAGE_IDS)}) x`)} AS transitions,
(SELECT COALESCE(json_agg(q), '[]'::json) FROM (
SELECT p.id, p.slug, p.source_id, s.incarnation::text AS incarnation FROM pages p JOIN sources s ON s.id = p.source_id
WHERE p.id = ANY(ARRAY(SELECT unnest(ARRAY[e.from_page_id, e.to_page_id, e.origin_page_id])
FROM ((${OWNED_ROWS('links', PAGE_IDS, ENDS)}) UNION ALL (${OWNED_ROWS('link_transitions', PAGE_IDS, ENDS)})) e))) q) AS endpoints`, params);
await tx.executeRaw(`SELECT set_config('plan_cache_mode', $1, true)`, [mode!.prev]);
- const { pages: pageRows, facts, takes, links, transitions, endpoints } = row!;
- const byId = new Map(endpoints.map(r => [Number(r.id), { id: Number(r.id), slug: String(r.slug), source_id: String(r.source_id), incarnation: String(r.incarnation) }]));
+ const { pages: pageRows, counts, facts, entity_pages: entityPages, takes, links, transitions, endpoints } = row!;
+ const byId = new Map(endpoints!.map(r => [Number(r.id), { id: Number(r.id), slug: String(r.slug), source_id: String(r.source_id), incarnation: String(r.incarnation) }]));
const endpoint = (id: unknown): RawEndpoint | null => id == null ? null : byId.get(Number(id)) ?? null;
- const pages: RawPage[] = pageRows.map(r => ({ id: Number(r.id), slug: String(r.slug), deleted: r.deleted === true, revision: String(r.revision),
+ const pages: RawPage[] = pageRows!.map(r => ({ id: Number(r.id), slug: String(r.slug), deleted: r.deleted === true, revision: String(r.revision),
content_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)]));
return {
pages,
- facts: facts.map(r => toFact(r.fp == null ? { ...r, fp: knownFp.get(String(r.fact)) } : r)),
- takes: takes.map(r => toTake(r.claim_fp == null ? { ...r, claim_fp: knownFp.get(String(r.claim)) } : r)),
- 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),
+ facts: facts ? facts.map(r => toFact(r.fp == null ? { ...r, fp: knownFp.get(String(r.fact)) } : r))
+ : known!.facts.map(f => ({ ...f, entity_page_id: f.entity_slug == null ? null : entityPageOf.get(f.entity_slug) ?? null })),
+ takes: takes ? takes.map(r => toTake(r.claim_fp == null ? { ...r, claim_fp: knownFp.get(String(r.claim)) } : r)) : 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,
- assertion_tense: (r.assertion_tense as string | null) ?? null })),
- transitions: transitions.map(r => ({ id: Number(r.id), from: endpoint(r.f)!, to: endpoint(r.t)!, origin: endpoint(r.o),
+ assertion_tense: (r.assertion_tense as string | null) ?? null }))
+ : known!.links.map(l => ({ ...l, from: endpoint(l.from.id)!, to: endpoint(l.to.id)!, origin: endpoint(l.origin?.id) })),
+ transitions: transitions ? transitions.map(r => ({ id: Number(r.id), from: endpoint(r.f)!, to: endpoint(r.t)!, origin: endpoint(r.o),
link_type: String(r.link_type), kind: String(r.kind), occurred_on: String(r.occurred_on), date_precision: String(r.date_precision),
- producer: String(r.producer), line_hash: String(r.line_hash) })),
- writerTier: ((pageRows[0] ?? (await tx.executeRaw<Record<string, unknown>>(`SELECT current_setting('gbrain.write_trust_tier', true) AS writer_tier`))[0])
+ producer: String(r.producer), line_hash: String(r.line_hash) }))
+ : known!.transitions.map(x => ({ ...x, from: endpoint(x.from.id)!, to: endpoint(x.to.id)!, origin: endpoint(x.origin?.id) })),
+ writerTier: ((pageRows![0] ?? (await tx.executeRaw<Record<string, unknown>>(`SELECT current_setting('gbrain.write_trust_tier', true) AS writer_tier`))[0])
?.writer_tier as string | undefined) || null,
+ counts: counts as unknown as string[] | null,
};
}
diff --git a/src/core/engine-sql/takes.ts b/src/core/engine-sql/takes.ts
index c5db9bfb0b..ea7bd0df9f 100644
--- a/src/core/engine-sql/takes.ts
+++ b/src/core/engine-sql/takes.ts
@@ -61,11 +61,14 @@ async function _addTakesBatchOnce(exec: SqlExecutor, rowsIn: TakeBatchInput[]):
// Weight clamp/round + NUL-stripping live in buildTakeRows (shared w/ PGLite).
// NOTE: ON CONFLICT here is DO UPDATE (not DO NOTHING) — an intra-batch
// duplicate (page_id, row_num) errors, identical to the pre-#1861 unnest path.
+ // A stored row that already holds the values is left unwritten (no trigger,
+ // no updated_at bump) and still counts: every row is inserted, updated or
+ // already current, else the statement throws.
const { rows, weightClamped } = buildTakeRows(rowsIn);
if (weightClamped > 0) {
process.stderr.write(`[takes] TAKES_WEIGHT_CLAMPED: ${weightClamped} row(s) had weight outside [0,1]; clamped\n`);
}
- const result = await executeRawJsonb(
+ await executeRawJsonb(
exec,
`INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, superseded_by, active)
SELECT v.page_id, v.row_num, v.claim, v.kind, v.holder, v.weight,
@@ -89,11 +92,13 @@ async function _addTakesBatchOnce(exec: SqlExecutor, rowsIn: TakeBatchInput[]):
superseded_by = EXCLUDED.superseded_by,
active = EXCLUDED.active,
updated_at = now()
- RETURNING 1`,
+ WHERE (takes.claim, takes.kind, takes.holder, takes.weight, takes.since_date, takes.until_date, takes.source, takes.superseded_by, takes.active)
+ IS DISTINCT FROM (EXCLUDED.claim, EXCLUDED.kind, EXCLUDED.holder, EXCLUDED.weight, EXCLUDED.since_date, EXCLUDED.until_date,
+ EXCLUDED.source, EXCLUDED.superseded_by, EXCLUDED.active)`,
[],
[{ rows }],
);
- return result.length;
+ return rows.length;
}
/**
diff --git a/src/core/engine.ts b/src/core/engine.ts
index cc5ee40b2c..1a7438963f 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1913,8 +1913,8 @@ export interface BrainEngine {
* `jsonb_to_recordset(($1::jsonb)->'rows')` through `executeRawJsonb` (#1861;
* free-text-safe, replaced the prior `unnest(::text[])` path). Idempotency:
* ON CONFLICT (page_id, row_num) DO UPDATE — re-extract on a changed
- * claim/weight updates the row in place. Returns the number of rows inserted
- * OR updated. Row construction + weight clamp/round + NUL-strip live in
+ * claim/weight updates the row in place; an identical row stays unwritten. Returns
+ * the rows inserted, updated or already current. Row construction + weight clamp/round + NUL-strip live in
* `src/core/batch-rows.ts:buildTakeRows` (shared across both engines).
*
* Wrapped in `batchRetry` like the other batch primitives, so `opts` (auditSite,
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 14a25913fd..07f779435e 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -454,7 +454,11 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
claim_period=r.claim_period,attributed_to=r.attributed_to
FROM jsonb_to_recordset($3::text::jsonb) AS r(row_num integer,kind text,notability text,context text,valid_from text,valid_until text,
expired_at text,source text,confidence real,claim_metric text,claim_value double precision,claim_unit text,claim_period text,attributed_to text)
- WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num=r.row_num`, [sourceId, slug, fieldRows]) : Promise.resolve([]);
+ WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num=r.row_num
+ AND (f.kind,f.notability,f.context,f.valid_from,f.valid_until,f.expired_at,f.source,f.confidence,f.claim_metric,f.claim_value,f.claim_unit,
+ f.claim_period,f.attributed_to) IS DISTINCT FROM (r.kind,r.notability,r.context,COALESCE(r.valid_from::timestamptz,f.valid_from),
+ r.valid_until::timestamptz,r.expired_at::timestamptz,r.source,r.confidence,r.claim_metric,r.claim_value,r.claim_unit,r.claim_period,r.attributed_to)`,
+ [sourceId, slug, fieldRows]) : Promise.resolve([]);
const checkTakes = () => refuseCollisions(tx, id);
const dropTakes = () => tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])', [id, takeRowsGone.filter(n => !heldRowNums.has(n))]);
// A fence row's resolution cells are written as Markdown says, so a revert to a version that carries them restores
@@ -477,7 +481,9 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
resolved_by=r.resolved_by
FROM jsonb_to_recordset($2::text::jsonb) AS r(row_num integer,resolved_at text,resolved_quality text,resolved_outcome boolean,
resolved_source text,resolved_value real,resolved_unit text,resolved_by text)
- WHERE k.page_id=$1 AND k.row_num=r.row_num`, [id, resolutions]) : Promise.resolve([]);
+ WHERE k.page_id=$1 AND k.row_num=r.row_num AND (k.resolved_at,k.resolved_quality,k.resolved_outcome,k.resolved_source,k.resolved_value,k.resolved_unit,
+ k.resolved_by) IS DISTINCT FROM (r.resolved_at::timestamptz,r.resolved_quality,r.resolved_outcome,r.resolved_source,r.resolved_value,r.resolved_unit,
+ r.resolved_by)`, [id, resolutions]) : Promise.resolve([]);
// Event-page references have a different canonical origin and remain intact;
// new rows carry their Markdown detail on insert, pinned rows refresh only from their preimage.
const timelineRows = [
diff --git a/test/belief-ledger-touched.test.ts b/test/belief-ledger-touched.test.ts
new file mode 100644
index 0000000000..80dfbfeea8
--- /dev/null
+++ b/test/belief-ledger-touched.test.ts
@@ -0,0 +1,111 @@
+/**
+ * Belief ledger write-overhead probes (docs/designs/BELIEF_LEDGER.md section 9):
+ * a fence projection leaves rows that already hold their values unwritten, and
+ * the batch's post-read reuses the pre-read for every table the transaction did
+ * not write (its pg_stat_xact counter is unchanged). Each probe runs on PGLite
+ * and on Postgres when DATABASE_URL is set; the forced probe suppresses the
+ * touched signal and shows the drift check catches the event it loses.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { __suppressBeliefTouchedSignalForTests, readBeliefState } from '../src/core/belief/state.ts';
+import { beliefLedgerEntry } from '../src/commands/doctor/checks/belief-ledger.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { beliefBrain, beliefEngineCase, beliefPage, shape, type BeliefBrain } from './helpers/belief-ledger.ts';
+
+afterEach(() => { __suppressBeliefTouchedSignalForTests(false); });
+
+const SLUG = 'companies/acme-example';
+const page = (o: Parameters<typeof beliefPage>[0] = {}) => beliefPage({ facts: ['Acme raised a seed round', 'Acme has ten staff', 'Acme is in Austin'],
+ takes: ['Acme will win its market', 'Acme will hire fast'], links: ['people/alice-example'], ...o });
+
+/** Every fact and take row of the page with its row version (xmin moves on any rewrite, identical values included). */
+async function rowVersions(b: BeliefBrain): Promise<string[]> {
+ const rows = await b.engine.executeRaw<{ r: string }>(`SELECT 'fact:' || f.id || ':' || f.xmin::text AS r FROM facts f
+ WHERE f.source_id = $1 AND f.source_markdown_slug = $2
+ UNION ALL SELECT 'take:' || k.id || ':' || k.xmin::text FROM takes k JOIN pages p ON p.id = k.page_id WHERE p.source_id = $1 AND p.slug = $2
+ ORDER BY 1`, [b.sourceId, SLUG]);
+ return rows.map(r => r.r);
+}
+
+async function doctor(b: BeliefBrain): Promise<Check> {
+ const [check] = await beliefLedgerEntry.run({ engine: b.engine, tier: 'standard', doFix: false, dryRun: false, orphanRatioSourceId: b.sourceId } as DoctorContext) as Check[];
+ return check!;
+}
+
+for (const engineCase of testBackends().map(beliefEngineCase)) {
+ describe(`belief ledger write overhead (${engineCase.name})`, () => {
+ 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' }));
+ await b.put(SLUG, page());
+ };
+
+ test('a prose-only edit rewrites no fact or take row and records no belief event', async () => {
+ await brain(async b => {
+ await seeded(b);
+ const versions = await rowVersions(b);
+ expect(versions).toHaveLength(5);
+ const before = await b.lastId();
+ await b.put(SLUG, page({ prose: 'Rewritten prose only.' }));
+ expect(shape(await b.events(before))).toEqual(['page:page.published']);
+ expect(await rowVersions(b)).toEqual(versions);
+ });
+ }, 120_000);
+
+ test('a one-value change among identical rows rewrites that row alone and is recorded', async () => {
+ await brain(async b => {
+ await seeded(b);
+ const versions = await rowVersions(b);
+ const before = await b.lastId();
+ await b.put(SLUG, page({ facts: ['Acme raised a seed round', { claim: 'Acme has ten staff', confidence: '0.5' }, 'Acme is in Austin'] }));
+ const events = await b.events(before);
+ expect(shape(events)).toEqual(['page:page.published', 'fact:fact.revised']);
+ expect(events[1]!.value).toMatchObject({ confidence: 0.5 });
+ const changed = (await rowVersions(b)).filter(v => !versions.includes(v));
+ expect(changed).toHaveLength(1);
+ expect(changed[0]!.startsWith('fact:')).toBe(true);
+ const mark = await b.lastId();
+ await b.put(SLUG, page({ facts: ['Acme raised a seed round', { claim: 'Acme has ten staff', confidence: '0.5' }, 'Acme is in Austin'],
+ takes: [{ claim: 'Acme will win its market', weight: '0.9' }, 'Acme will hire fast'] }));
+ expect(shape(await b.events(mark))).toEqual(['page:page.published', 'take:take.revised']);
+ });
+ }, 120_000);
+
+ test('forced probe: with the touched signal suppressed the change goes unrecorded and the drift check names the slug', async () => {
+ await brain(async b => {
+ await seeded(b);
+ expect((await doctor(b)).status).toBe('ok');
+ const before = await b.lastId();
+ __suppressBeliefTouchedSignalForTests(true);
+ await b.put(SLUG, page({ facts: ['Acme raised a seed round', { claim: 'Acme has ten staff', confidence: '0.5' }, 'Acme is in Austin'] }));
+ __suppressBeliefTouchedSignalForTests(false);
+ expect(shape(await b.events(before))).toEqual(['page:page.published']);
+ const drifted = await doctor(b);
+ expect(drifted.status).toBe('warn');
+ expect(drifted.message).toContain(`${b.sourceId}: 1 drifted slug(s) (e.g. ${SLUG})`);
+ });
+ }, 120_000);
+
+ test('with track_counts off the post-read reads every table again', async () => {
+ await brain(async b => {
+ await seeded(b);
+ await b.engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL track_counts = off');
+ const pre = await readBeliefState(tx, b.sourceId, [SLUG]);
+ await tx.executeRaw(`UPDATE facts SET confidence = 0.25 WHERE source_id = $1 AND source_markdown_slug = $2 AND fact = 'Acme is in Austin'`, [b.sourceId, SLUG]);
+ const post = await readBeliefState(tx, b.sourceId, [SLUG], pre.pages.map(p => p.id), pre);
+ expect(post.facts.find(f => f.fact === 'Acme is in Austin')!.confidence).toBe(0.25);
+ await tx.executeRaw('SET LOCAL track_counts = on');
+ const counted = await readBeliefState(tx, b.sourceId, [SLUG]);
+ await tx.executeRaw(`UPDATE facts SET confidence = 0.75 WHERE source_id = $1 AND source_markdown_slug = $2 AND fact = 'Acme is in Austin'`, [b.sourceId, SLUG]);
+ const recounted = await readBeliefState(tx, b.sourceId, [SLUG], counted.pages.map(p => p.id), counted);
+ expect(recounted.facts.find(f => f.fact === 'Acme is in Austin')!.confidence).toBe(0.75);
+ expect(recounted.takes).toBe(counted.takes);
+ throw new Error('rollback');
+ }).catch(e => { if ((e as Error).message !== 'rollback') throw e; });
+ }, false);
+ }, 120_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 3f0696fc32..0e3300b961 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -24,6 +24,7 @@ test/belief-ledger-privacy.test.ts
test/belief-ledger-purge-review.test.ts
test/belief-ledger-purge.test.ts
test/belief-ledger-restore.test.ts
+test/belief-ledger-touched.test.ts
test/belief-ledger-trust.test.ts
test/capture-consent-admission.test.ts
test/capture-dispatch-provenance-6524.test.ts