Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(belief): review fixes for the weekly diff and W5 notes
garrytan50c52764fdf9
diff --git a/docs/designs/BELIEF_LEDGER.md b/docs/designs/BELIEF_LEDGER.mdindex 0d80d87fec..d823d2b3ce 100644--- a/docs/designs/BELIEF_LEDGER.md+++ b/docs/designs/BELIEF_LEDGER.md@@ -1611,6 +1611,11 @@ Garry accepted those answers. Questions 5, 6, 7 and 8 are decided.`before`, `after`, `cause` (the event type, the op, and any request,replacement, proposal or purge pointer the event recorded), `evidence`(event id, recorded time, slug, fence row) and the event's `trust_tier`.+ Subjects net on hashes (the first event's prior hash against the last+ one's value hash). Page events net per lifetime: a delete and its restore,+ or a rename and its revert, report nothing, and so does a page created and+ gone again inside the window; a purge, expiry, merge or hard delete is one+ `removed` page entry.3. **A subject with no earlier event.** Section 4 records a page's creationas one snapshot event, so a fact or take first edited inside the window mayhave no event before `since`. Its `before` is read from the page body as@@ -1619,7 +1624,8 @@ Garry accepted those answers. Questions 5, 6, 7 and 8 are decided.`before_known` is false: the value is disclosed as unknown, never guessed.A page created inside the window is one `added` page entry plus one`added` entry per fence fact and take of its creation body; links that- came with it are counted on the page entry.+ came with it are counted on the page entry (for local callers only: the+ counts include beliefs a remote caller may not read).4. **Upper bounds.** A relationship end that only the nightly check inferred(a transition whose producer is `dream`) is flagged `upper_bound: true` andrendered `end by <date>`: the relationship ended on or before that date@@ -1631,8 +1637,15 @@ Garry accepted those answers. Questions 5, 6, 7 and 8 are decided.source with no coverage at all returns `not_recorded: true`.6. **Remote callers.** `delta` passes `remote: !include_private`. The historyreader's rule applies (events world-visible when recorded, on a page- visible now, failing closed), and a body read for `before` is used only- where `remoteMayRead` passes that interval and only for world fence rows.+ visible now, failing closed; takes of the holders the caller may read), and+ a body read for `before` or a creation is used only where `remoteMayRead`+ passes that interval, only for world fence rows, and never for a claim made+ private later or a key a purge hid. A remote history page is filtered after+ its SQL `LIMIT`, so reads page on the rows each page scanned, never on the+ rows it returned. A take removal carries no value, so its holder is the+ key's newest earlier value's; a take that came with its page's creation and+ was removed later has no earlier event, so a remote caller does not see the+ removal.7. **Budget.** Under `budget_tokens`, belief lines pack into what pages,facts and threads leave; a dropped line sets `truncated`. Without abudget the list is capped at 200 entries, and a window with more thandiff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 773705ae40..4d07144db4 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -1046,9 +1046,15 @@ ledger starts after `since` (earlier changes are unknown, not absent), and`not_recorded` when the source has no ledger coverage. `entities` narrows thelist to changes on or about the named slugs. A caller without`include_private` (every remote caller) gets the world view: events that were-world-visible when recorded, on pages visible now. Under `budget_tokens` the-belief lines pack into what pages, facts and threads leave, and `truncated`-reports a cut; `text` gains a `## Belief changes since <since>` section. The+world-visible when recorded, on pages visible now, and takes of the holders+the caller may read (the takes surfaces' allow-list, `world` by default).+Under `budget_tokens` the belief lines pack into what pages, facts and threads+leave, and `truncated` reports a cut; `text` gains a+`## Belief changes since <since>` section. The diff is a read of the window,+not a cursor arm: it does not set `has_more` or hold a `session_id` cursor,+so lines a cut dropped are not delivered on the next wake; read them with an+explicit `since` (or `gbrain beliefs changes`). `min_trust` does not filter+it; each change carries its `trust_tier`. TheCLI twin is `gbrain beliefs changes [<entity>...] [--since 7d]`. Design:[BELIEF_LEDGER.md section 15](../designs/BELIEF_LEDGER.md#15-w4-as-built-the-weekly-change-diff).diff --git a/src/core/belief/changes.ts b/src/core/belief/changes.tsindex c6ceb974fd..495b141213 100644--- a/src/core/belief/changes.ts+++ b/src/core/belief/changes.ts@@ -22,7 +22,7 @@* upper bound: the relationship ended on or before that date (`upper_bound`).*/import type { BrainEngine } from '../engine.ts';-import { readBeliefHistory, type BeliefHistoryRow, type BeliefHistoryQuery } from './history.ts';+import { readBeliefHistoryPage, type BeliefHistoryRow, type BeliefHistoryQuery } from './history.ts';import { coverageAt } from './coverage-report.ts';import { readPageAtTime, remoteMayRead } from './page-at-time.ts';import { bodySubjects } from './backfill.ts';@@ -66,6 +66,7 @@ const SUBJECT_EVENTS = new Set(['fact.asserted', 'fact.revised', 'fact.retracted'link.asserted', 'link.revised', 'link.retracted', 'link.transferred', 'link.transition_added', 'link.transition_revised', 'link.transition_removed']);const REMOVALS = new Set(['fact.retracted', 'fact.withdrawn', 'fact.superseded', 'fact.purged', 'take.retracted', 'take.purged', 'link.retracted', 'link.transition_removed']);const ADDITIONS = new Set(['fact.asserted', 'fact.transferred', 'take.asserted', 'take.transferred', 'link.asserted', 'link.transferred', 'link.transition_added']);+const TERMINAL = new Set(['page.purged', 'page.expired', 'page.merged']);const PAGE_EVENTS: Record<string, BeliefChange['change']> = { 'page.deleted': 'deleted', 'page.restored': 'restored', 'page.renamed': 'renamed','page.purged': 'removed', 'page.expired': 'removed', 'page.merged': 'removed' };const CAUSE_FIELDS = ['request', 'replaces', 'replaced_by', 'proposal', 'guard', 'purge_request', 'from_key', 'hold'] as const;@@ -76,16 +77,44 @@ const DEFAULT_LIMIT = 200;const iso = (v: unknown) => new Date(v as string).toISOString();const isCreation = (e: BeliefHistoryRow) => e.event_type === 'page.published' && e.value != null && e.value.revision_before == null;-/** Every event matching `q`, paged by id; `truncated` when the cap stopped it. */+let pageSize = PAGE_SIZE;+/** Test seam: a small page size, so a cell can cross page boundaries without 10,000 events. */+export function __setBeliefChangesPageSizeForTests(n?: number): void { pageSize = n ?? PAGE_SIZE; }++/** Every event matching `q`, paged on what each page scanned (a remote page is filtered after its LIMIT); `truncated` when the cap stopped it. */async function readAll(engine: BrainEngine, q: BeliefHistoryQuery): Promise<{ rows: BeliefHistoryRow[]; truncated: boolean }> {const rows: BeliefHistoryRow[] = [];let afterId = 0;+ let scanned = 0;+ for (;;) {+ const page = await readBeliefHistoryPage(engine, { ...q, afterId, limit: pageSize });+ rows.push(...page.rows);+ scanned += page.scanned;+ if (page.lastScannedId == null || page.scanned < pageSize) return { rows, truncated: false };+ if (scanned >= MAX_EVENTS) return { rows, truncated: true };+ afterId = page.lastScannedId;+ }+}++/** Each wanted subject's newest event at or before `until`, read newest first and stopped once every subject has one. */+async function readPrior(engine: BrainEngine, q: BeliefChangesQuery, wanted: ReadonlyMap<string, string>, until: string): Promise<{ prior: Map<string, BeliefHistoryRow>; truncated: boolean }> {+ const prior = new Map<string, BeliefHistoryRow>();+ if (!wanted.size) return { prior, truncated: false };+ const subjectKeys = [...new Set(wanted.values())];+ let beforeId: number | undefined;+ let scanned = 0;for (;;) {- const page = await readBeliefHistory(engine, { ...q, afterId, limit: PAGE_SIZE });- rows.push(...page);- if (page.length < PAGE_SIZE) return { rows, truncated: false };- if (rows.length >= MAX_EVENTS) return { rows, truncated: true };- afterId = page.at(-1)!.id;+ const page = await readBeliefHistoryPage(engine, { sourceId: q.sourceId, remote: q.remote, takesHolders: q.takesHolders, subjectKeys, recordedUntil: until,+ beforeId, descending: true, limit: pageSize });+ for (const e of page.rows) {+ if (e.origin === 'backfill' || !SUBJECT_EVENTS.has(e.event_type) && e.event_type !== 'fact.adopted' && e.event_type !== 'link.adopted') continue;+ const id = `${e.subject_kind}\u0000${e.subject_key}`;+ if (wanted.has(id) && !prior.has(id)) prior.set(id, e);+ }+ scanned += page.scanned;+ if (page.lastScannedId == null || page.scanned < pageSize || prior.size === wanted.size) return { prior, truncated: false };+ if (scanned >= MAX_EVENTS) return { prior, truncated: true };+ beforeId = page.lastScannedId;}}@@ -111,6 +140,33 @@ function causeOf(e: BeliefHistoryRow): BeliefChange['cause'] {const evidenceOf = (e: BeliefHistoryRow): BeliefChange['evidence'] =>({ event_id: e.id, recorded_at: iso(e.recorded_at), slug: e.slug, ...(typeof e.cause.row === 'number' ? { row: e.cause.row } : {}) });+const pageEntry = (e: BeliefHistoryRow, change: BeliefChange['change'], before: Record<string, unknown> | null, after: Record<string, unknown> | null): BeliefChange =>+ ({ kind: 'page', slug: e.slug, change, subject: { slug: e.slug }, before, after, before_known: true, cause: causeOf(e), evidence: evidenceOf(e), trust_tier: e.trust_tier });++/**+ * One page lifetime's events in the window, netted: a delete and its restore, or a rename and its revert, report+ * nothing; a page created and gone again inside the window reports nothing. Returns the entries and the creation+ * event when the created page is still there at the end (its fence subjects are listed too).+ */+function netPage(evs: BeliefHistoryRow[], remote: boolean): { entries: BeliefChange[]; creation: BeliefHistoryRow | null } {+ const creation = evs.find(isCreation) ?? null;+ const terminal = [...evs].reverse().find(e => TERMINAL.has(e.event_type) || e.event_type === 'page.deleted' && e.value?.hard === true);+ if (terminal) return { entries: creation ? [] : [pageEntry(terminal, PAGE_EVENTS[terminal.event_type]!, null, null)], creation: null };+ const toggles = evs.filter(e => e.event_type === 'page.deleted' || e.event_type === 'page.restored');+ const renames = evs.filter(e => e.event_type === 'page.renamed' && e.value);+ const startDeleted = creation ? creation.value?.deleted === true : toggles[0]?.event_type === 'page.restored';+ const endDeleted = toggles.length ? toggles.at(-1)!.event_type === 'page.deleted' : startDeleted;+ if (creation) {+ if (endDeleted) return { entries: [], creation: null };+ return { entries: [pageEntry(creation, 'added', null, remote ? null : { counts: creation.value?.counts ?? null })], creation };+ }+ const entries: BeliefChange[] = [];+ if (startDeleted !== endDeleted) entries.push(pageEntry(toggles.at(-1)!, endDeleted ? 'deleted' : 'restored', null, null));+ const from = renames[0]?.value?.old_slug, to = renames.at(-1)?.value?.new_slug;+ if (renames.length && from !== to) entries.push(pageEntry(renames.at(-1)!, 'renamed', { slug: from }, { slug: to }));+ return { entries, creation: null };+}+export async function beliefChanges(engine: BrainEngine, q: BeliefChangesQuery): Promise<BeliefChanges> {const out: BeliefChanges = { source_id: q.sourceId, since: iso(q.since), until: iso(q.until), coverage_from: null, changes: [], truncated: false };const coverage = await coverageAt(engine, q.sourceId, q.until);@@ -120,39 +176,59 @@ export async function beliefChanges(engine: BrainEngine, q: BeliefChangesQuery):const read = await readAll(engine, { sourceId: q.sourceId, remote: q.remote, takesHolders: q.takesHolders, recordedAfter: out.since, recordedUntil: out.until });out.truncated = read.truncated;const events = read.rows.filter(e => e.origin !== 'backfill' && e.origin !== 'baseline');+ const wanted = q.entities?.length ? new Set(q.entities) : null;+ const touches = (slug: string, subject: Record<string, unknown>) => !wanted || wanted.has(slug)+ || [subject.subject_slug, subject.entity_slug, subject.from, subject.to].some(s => typeof s === 'string' && wanted.has(s));+ const limit = Math.max(1, q.limit ?? DEFAULT_LIMIT);- const created = new Map<string, BeliefHistoryRow>();- for (const e of events) if (e.subject_kind === 'page' && e.page_lifetime && isCreation(e)) created.set(e.page_lifetime, e);- const changes: BeliefChange[] = [];+ // Work items in evidence order; each yields its entries, and reading stops once more than `limit` are found.+ type Item = { id: number; run: () => Promise<BeliefChange[]> };+ const items: Item[] = [];+ const pageEvents = new Map<string, BeliefHistoryRow[]>();for (const e of events) {- if (e.subject_kind !== 'page') continue;- if (isCreation(e)) {- changes.push({ kind: 'page', slug: e.slug, change: 'added', subject: { slug: e.slug }, before: null, after: { counts: e.value?.counts ?? null },- before_known: true, cause: causeOf(e), evidence: evidenceOf(e), trust_tier: e.trust_tier });- continue;+ if (e.subject_kind !== 'page' || !e.page_lifetime || !isCreation(e) && !PAGE_EVENTS[e.event_type]) continue;+ let list = pageEvents.get(e.page_lifetime);+ if (!list) pageEvents.set(e.page_lifetime, list = []);+ list.push(e);+ }+ const created = new Set<string>();+ for (const [lifetime, evs] of pageEvents) {+ const net = netPage(evs, q.remote);+ if (evs.some(isCreation)) created.add(lifetime);+ for (const entry of net.entries.filter(c => touches(c.slug, c.subject))) items.push({ id: entry.evidence.event_id, run: async () => [entry] });+ const creation = net.creation;+ if (creation && touches(creation.slug, { subject_slug: creation.slug })) {+ items.push({ id: creation.id, run: async () => [...await readCreationSubjects(engine, q, creation, out.until) ?? []].flatMap(([id, value]) => {+ if (byKey.has(id)) return [];+ const kind = id.split('\u0000')[0] as 'fact' | 'take';+ return [{ kind, slug: creation.slug, change: 'added' as const, subject: subjectOf(kind, id.split('\u0000')[1]!, { subject_slug: creation.slug }, [value]),+ before: null, after: value, before_known: true, cause: causeOf(creation), evidence: evidenceOf(creation), trust_tier: creation.trust_tier }];+ }) });}- const change = PAGE_EVENTS[e.event_type];- if (!change) continue;- const renamed = change === 'renamed' && e.value ? e.value : null;- changes.push({ kind: 'page', slug: e.slug, change, subject: { slug: e.slug },- before: renamed ? { slug: renamed.old_slug } : null, after: renamed ? { slug: renamed.new_slug } : null,- before_known: true, cause: causeOf(e), evidence: evidenceOf(e), trust_tier: e.trust_tier });}const byKey = new Map<string, BeliefHistoryRow[]>();for (const e of events) {if (!SUBJECT_EVENTS.has(e.event_type)) continue;const id = `${e.subject_kind}\u0000${e.subject_key}`;- byKey.set(id, [...byKey.get(id) ?? [], e]);- }- const keys = [...new Set([...byKey.values()].map(rows => rows[0]!.subject_key))];- const prior = new Map<string, BeliefHistoryRow>();- if (keys.length) {- for (const e of (await readAll(engine, { sourceId: q.sourceId, remote: q.remote, takesHolders: q.takesHolders, subjectKeys: keys, recordedUntil: out.since })).rows) {- if (e.origin === 'backfill' || !SUBJECT_EVENTS.has(e.event_type) && e.event_type !== 'fact.adopted' && e.event_type !== 'link.adopted') continue;- prior.set(`${e.subject_kind}\u0000${e.subject_key}`, e);- }+ let list = byKey.get(id);+ if (!list) byKey.set(id, list = []);+ list.push(e);}+ const subjectFor = (id: string, rows: BeliefHistoryRow[]) => {+ const first = rows[0]!, last = rows.at(-1)!;+ return subjectOf(first.subject_kind as BeliefChangeKind, last.subject_key, (last.cause.label ?? first.cause.label ?? {}) as Record<string, unknown>,+ [...rows].reverse().map(r => r.value));+ };+ const keys = [...byKey].filter(([id, rows]) => {+ const first = rows[0]!, last = rows.at(-1)!;+ const finalHash = REMOVALS.has(last.event_type) ? null : last.value_hash;+ // Netted on hashes before anything is read: the window ends where it started.+ if (first.prior_hash != null && first.prior_hash === finalHash) return false;+ return touches(last.slug, subjectFor(id, rows));+ });+ const prior = await readPrior(engine, q, new Map(keys.map(([id, rows]) => [id, rows[0]!.subject_key])), out.since);+ out.truncated ||= prior.truncated;const bodies = new Map<string, Promise<Map<string, Record<string, unknown>> | null>>();const bodyAt = (slug: string, at: string) => {@@ -160,56 +236,66 @@ export async function beliefChanges(engine: BrainEngine, q: BeliefChangesQuery):if (!bodies.has(id)) bodies.set(id, readBodySubjects(engine, q, slug, at));return bodies.get(id)!;};-- for (const [id, rows] of byKey) {+ for (const [id, rows] of keys) {const first = rows[0]!;const last = rows.at(-1)!;- const kind = first.subject_kind as BeliefChangeKind;- const after = REMOVALS.has(last.event_type) ? null : last.value;- let before: Record<string, unknown> | null = null;- let beforeKnown = true;- const p = prior.get(id);- if (p) before = REMOVALS.has(p.event_type) ? null : p.value;- else if (ADDITIONS.has(first.event_type) || (first.page_lifetime && created.has(first.page_lifetime))) before = null;- else if (kind === 'fact' || kind === 'take') {- const subjects = await bodyAt(first.slug, out.since);- before = subjects?.get(`${kind}\u0000${first.subject_key}`) ?? null;- beforeKnown = before != null;- } else before = { present: true };- if (canonicalJson(before) === canonicalJson(after) && beforeKnown) continue;- const label = (last.cause.label ?? first.cause.label ?? {}) as Record<string, unknown>;- const subject = subjectOf(kind, last.subject_key, label, [after, before, ...rows.map(r => r.value)]);- changes.push({ kind, slug: last.slug, change: before == null && beforeKnown ? 'added' : after == null ? 'removed' : 'changed', subject, before, after,- before_known: beforeKnown, ...(kind === 'link_transition' && subject.transition === 'end' && subject.producer === 'dream' ? { upper_bound: true as const } : {}),- cause: causeOf(last), evidence: evidenceOf(last), trust_tier: last.trust_tier });+ items.push({ id: last.id, run: async () => {+ const kind = first.subject_kind as BeliefChangeKind;+ const after = REMOVALS.has(last.event_type) ? null : last.value;+ let before: Record<string, unknown> | null = null;+ let beforeKnown = true;+ const p = prior.prior.get(id);+ if (p) before = REMOVALS.has(p.event_type) ? null : p.value;+ else if (ADDITIONS.has(first.event_type) || (first.page_lifetime && created.has(first.page_lifetime))) before = null;+ else if (kind === 'fact' || kind === 'take') {+ const subjects = await bodyAt(first.slug, out.since);+ before = subjects?.get(id) ?? null;+ beforeKnown = before != null;+ } else {+ before = { present: true };+ beforeKnown = false;+ }+ if (canonicalJson(before) === canonicalJson(after) && beforeKnown) return [];+ const subject = subjectOf(kind, last.subject_key, (last.cause.label ?? first.cause.label ?? {}) as Record<string, unknown>, [after, before, ...rows.map(r => r.value)]);+ return [{ kind, slug: last.slug, change: before == null && beforeKnown ? 'added' : after == null ? 'removed' : 'changed', subject, before, after,+ before_known: beforeKnown, ...(kind === 'link_transition' && subject.transition === 'end' && subject.producer === 'dream' ? { upper_bound: true as const } : {}),+ cause: causeOf(last), evidence: evidenceOf(last), trust_tier: last.trust_tier }];+ } });}- for (const creation of created.values()) {- const subjects = await readCreationSubjects(engine, q, creation, out.until);- for (const [id, value] of subjects ?? []) {- if (byKey.has(id)) continue;- const kind = id.split('\u0000')[0] as 'fact' | 'take';- changes.push({ kind, slug: creation.slug, change: 'added', subject: subjectOf(kind, id.split('\u0000')[1]!, { subject_slug: creation.slug }, [value]),- before: null, after: value, before_known: true, cause: causeOf(creation), evidence: evidenceOf(creation), trust_tier: creation.trust_tier });- }+ const found: BeliefChange[] = [];+ for (const item of items.sort((a, b) => a.id - b.id)) {+ found.push(...await item.run());+ if (found.length > limit) break;}-- const wanted = q.entities?.length ? new Set(q.entities) : null;- const touches = (c: BeliefChange) => !wanted || wanted.has(c.slug) || [c.subject.subject_slug, c.subject.entity_slug, c.subject.from, c.subject.to].some(s => typeof s === 'string' && wanted.has(s));- const sorted = changes.filter(touches).sort((a, b) => a.evidence.event_id - b.evidence.event_id || a.kind.localeCompare(b.kind));- const limit = Math.max(1, q.limit ?? DEFAULT_LIMIT);- out.changes = sorted.slice(0, limit);- out.truncated ||= sorted.length > limit;+ out.changes = found.sort((a, b) => a.evidence.event_id - b.evidence.event_id || a.kind.localeCompare(b.kind)).slice(0, limit);+ out.truncated ||= found.length > limit;return out;}-/** Fence subjects of a page body, keyed `kind\u0000subject_key`; a remote caller gets them only where it may read the interval, and only world facts and takes of holders it may read. */+/**+ * Fence subjects of a page body, keyed `kind\u0000subject_key`, under the history reader's rules: a subject whose key a+ * purge hid is dropped for every caller; a remote caller gets them only where it may read the interval, and only+ * world rows (takes of holders it may read) whose claim was not made private after the interval's event.+ */async function subjectsOf(engine: BrainEngine, q: BeliefChangesQuery, at: Awaited<ReturnType<typeof readPageAtTime>>, interval: NonNullable<Awaited<ReturnType<typeof readPageAtTime>>['current']>) {if (!interval.page || interval.body === 'unavailable' || interval.body === 'segmented' || interval.page.compiled_truth == null) return null;if (q.remote && !await remoteMayRead(engine, at.page_id, interval)) return null;const { subjects } = await bodySubjects(engine, interval.lifetime, `${interval.page.compiled_truth}\n${interval.page.timeline ?? ''}`, interval.event.visibility);const holders = new Set(q.takesHolders ?? ['world']);- return new Map(subjects.filter(s => !q.remote || s.visibility === 'world' && (s.kind !== 'take' || holders.has(String(s.value.holder))))+ const readable = subjects.filter(s => !q.remote || s.visibility === 'world' && (s.kind !== 'take' || holders.has(String(s.value.holder))));+ if (!readable.length) return new Map<string, Record<string, unknown>>();+ const hidden = await engine.executeRaw<{ subject_kind: string; subject_key: string | null; claim_fp: string | null }>(+ `SELECT e.subject_kind, CASE WHEN e.event_type = 'derived.hidden' THEN e.subject_key END AS subject_key,+ CASE WHEN e.event_type <> 'derived.hidden' THEN e.claim_fp END AS claim_fp+ FROM belief_events e+ WHERE e.source_id = $1 AND e.source_incarnation = (SELECT s.incarnation FROM sources s WHERE s.id = $1)+ AND (e.event_type = 'derived.hidden' AND e.subject_key = ANY($2::text[])+ OR $4::boolean AND e.visibility = 'private' AND e.id > $3::bigint AND e.claim_fp = ANY($5::text[]))`,+ [q.sourceId, readable.map(s => s.key), interval.event.id, q.remote, readable.map(s => s.claimFp).filter((fp): fp is string => typeof fp === 'string')]);+ const hiddenKeys = new Set(hidden.filter(h => h.subject_key).map(h => `${h.subject_kind}\u0000${h.subject_key}`));+ const laterPrivate = new Set(hidden.filter(h => h.claim_fp).map(h => `${h.subject_kind}\u0000${h.claim_fp}`));+ return new Map(readable.filter(s => !hiddenKeys.has(`${s.kind}\u0000${s.key}`) && !laterPrivate.has(`${s.kind}\u0000${s.claimFp}`)).map(s => [`${s.kind}\u0000${s.key}`, s.value]));}@@ -219,7 +305,7 @@ async function readBodySubjects(engine: BrainEngine, q: BeliefChangesQuery, slugreturn read?.current ? subjectsOf(engine, q, read, read.current) : null;}-/** The fence subjects of the body a creation event published. */+/** The fence subjects of the body a creation event published (its interval, from the page's history up to `until`). */async function readCreationSubjects(engine: BrainEngine, q: BeliefChangesQuery, creation: BeliefHistoryRow, until: string) {const read = await readPageAtTime(engine, { sourceId: q.sourceId, slug: creation.slug, at: new Date(until), history: true, withBodies: true }).catch(() => null);const interval = read?.intervals.find(i => i.event.id === creation.id);diff --git a/src/core/belief/history.ts b/src/core/belief/history.tsindex 1f378cc704..af3b7f6042 100644--- a/src/core/belief/history.ts+++ b/src/core/belief/history.ts@@ -10,7 +10,8 @@* later hides its earlier events; an ended lifetime hides them too);* - for links, every page-backed endpoint and the origin are visible now;* - for takes, the take's holder is one the caller may read (`takesHolders`, default `['world']`, the takes- * surfaces' rule); a take event with no holder (purged or redacted) is hidden.+ * surfaces' rule). A removal carries no value, so its holder is the key's newest earlier value's (one key is one+ * holder); a take whose values were all purged has no holder and is hidden.* For every caller, a key with a `derived.hidden` (a purge hid the row it* describes, section 6.5) hides its events below that marker and its backfill* events at any id; the marker itself stays visible as the disclosure. Only@@ -31,8 +32,8 @@ export interface BeliefHistoryQuery {sourceId: string; slug?: string; subjectKey?: string; remote: boolean; afterId?: number; limit?: number;/** Recorded-time window (after, until]. */recordedAfter?: string; recordedUntil?: string;- /** Only these subject keys, below this event id (the history of keys before a window). */- subjectKeys?: readonly string[]; beforeId?: number;+ /** Only these subject keys, below this event id (the history of keys before a window, read newest first with `descending`). */+ subjectKeys?: readonly string[]; beforeId?: number; descending?: boolean;/** Remote callers: the take holders they may read (the takes surfaces' allow-list); `['world']` when absent. */takesHolders?: readonly string[];}@@ -45,33 +46,45 @@ function linkLifetimes(subjectKey: string): string[] {}export async function readBeliefHistory(engine: BrainEngine, q: BeliefHistoryQuery): Promise<BeliefHistoryRow[]> {- const rows = await engine.executeRaw<BeliefHistoryRow & { stream_visible: boolean | null; later_private: boolean }>(`SELECT e.id, e.slug, e.page_lifetime::text AS page_lifetime,+ return (await readBeliefHistoryPage(engine, q)).rows;+}++/**+ * One page of history and how far it read: `scanned` rows matched the query before the remote filter, the last of them+ * `lastScannedId`. A remote page can hold fewer rows than `limit` and still not be the last; page on these, never on+ * `rows.length`.+ */+export async function readBeliefHistoryPage(engine: BrainEngine, q: BeliefHistoryQuery): Promise<{ rows: BeliefHistoryRow[]; scanned: number; lastScannedId: number | null }> {+ const rows = await engine.executeRaw<BeliefHistoryRow & { stream_visible: boolean | null; later_private: boolean; take_holder: string | 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.slugAND 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,(e.claim_fp IS NOT NULL AND EXISTS (SELECT 1 FROM belief_events v WHERE v.source_id = e.source_id AND v.source_incarnation = e.source_incarnation- AND v.claim_fp = e.claim_fp AND v.subject_kind = e.subject_kind AND v.visibility = 'private' AND v.id > e.id)) AS later_private+ AND v.claim_fp = e.claim_fp AND v.subject_kind = e.subject_kind AND v.visibility = 'private' AND v.id > e.id)) AS later_private,+ CASE WHEN e.subject_kind = 'take' THEN COALESCE(e.value->>'holder', (SELECT t.value->>'holder' FROM belief_events t WHERE t.source_id = e.source_id+ AND t.source_incarnation = e.source_incarnation AND t.subject_kind = 'take' AND t.subject_key = e.subject_key AND t.id < e.id AND t.value IS NOT NULL+ ORDER BY t.id DESC LIMIT 1)) END AS take_holderFROM belief_events eWHERE e.source_id = $1 AND e.source_incarnation = (SELECT s.incarnation FROM sources s WHERE s.id = $1) AND ($2::text IS NULL OR e.slug = $2) AND ($3::text IS NULL OR e.subject_key = $3) AND e.id > $4AND ($6::timestamptz IS NULL OR e.recorded_at > $6::timestamptz) AND ($7::timestamptz IS NULL OR e.recorded_at <= $7::timestamptz)AND ($8::text[] IS NULL OR e.subject_key = ANY($8::text[])) AND ($9::bigint IS NULL OR e.id < $9::bigint)AND NOT EXISTS (SELECT 1 FROM belief_events h WHERE h.source_id = e.source_id AND h.subject_kind = e.subject_kind AND h.subject_key = e.subject_keyAND h.event_type = 'derived.hidden' AND h.id <> e.id AND (h.id > e.id OR e.origin = 'backfill'))- 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),+ ORDER BY e.id ${q.descending ? 'DESC' : 'ASC'} LIMIT $5`, [q.sourceId, q.slug ?? null, q.subjectKey ?? null, q.afterId ?? 0, Math.min(Math.max(q.limit ?? 1000, 1), 10_000),q.recordedAfter ?? null, q.recordedUntil ?? null, q.subjectKeys ? [...q.subjectKeys] : null, q.beforeId ?? null]);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: _, later_private: __, ...row }) => row);+ const page = (kept: typeof out) => ({ rows: kept.map(({ stream_visible: _, later_private: __, take_holder: ___, ...row }) => row), scanned: out.length, lastScannedId: out.at(-1)?.id ?? null });+ if (!q.remote) return page(out);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_lifetimeFROM 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) : []);const holders = new Set(q.takesHolders ?? ['world']);- return out.filter(r => r.visibility === 'world' && r.later_private !== true- && (r.subject_kind !== 'take' || typeof r.value?.holder === 'string' && holders.has(r.value.holder))+ return page(out.filter(r => r.visibility === 'world' && r.later_private !== true+ && (r.subject_kind !== 'take' || typeof r.take_holder === 'string' && holders.has(r.take_holder))&& (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: _, later_private: __, ...row }) => row);+ && (r.subject_kind !== 'link' && r.subject_kind !== 'link_transition' || linkLifetimes(r.subject_key).every(id => visibleLifetimes.has(id)))));}diff --git a/src/core/link-relationship-notes.ts b/src/core/link-relationship-notes.tsindex 896dae9c78..1af8e7e78c 100644--- a/src/core/link-relationship-notes.ts+++ b/src/core/link-relationship-notes.ts@@ -59,8 +59,12 @@ export async function loadRelationshipNotes(const notes = new Map<string, string>();if (subjects.length === 0) return notes;const privacy = opts.excludePrivate ? ` AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';- const endBy = (producer: string) => `EXISTS (SELECT 1 FROM link_transitions x WHERE x.from_page_id = l.from_page_id AND x.to_page_id = l.to_page_id- AND x.link_type = l.link_type AND x.kind = 'end' AND x.occurred_on = lr_t.last_end AND x.producer ${producer})`;+ // The evidence the relationship projection counts for this scope (link-relationships.ts): an origin that is gone or in+ // another source never counts, and a private origin does not count toward the world scope.+ const endBy = (producer: string) => `EXISTS (SELECT 1 FROM link_transitions x LEFT JOIN pages xo ON xo.id = x.origin_page_id+ WHERE x.from_page_id = l.from_page_id AND x.to_page_id = l.to_page_id AND x.link_type = l.link_type AND x.kind = 'end'+ AND x.occurred_on = lr_t.last_end AND x.producer ${producer}+ AND (x.origin_page_id IS NULL OR xo.deleted_at IS NULL AND xo.source_id = f.source_id${opts.excludePrivate ? ` AND ${privatePagesFilterFragment('xo')}` : ''}))`;const rows = await engine.executeRaw<{ from_slug: string; source_id: string; to_slug: string; to_title: string | null; link_type: string; last_end: string | null; end_upper_bound: boolean | null }>(`SELECT f.slug AS from_slug, f.source_id, t.slug AS to_slug, t.title AS to_title, l.link_type, lr_t.last_end::text AS last_end,(${endBy("= 'dream'")} AND NOT ${endBy("<> 'dream'")}) AS end_upper_bound${TEMPORAL_LINK_SELECT_SQL}diff --git a/src/core/link-validity.ts b/src/core/link-validity.tsindex ae13663620..891ae1af3d 100644--- a/src/core/link-validity.ts+++ b/src/core/link-validity.ts@@ -261,12 +261,19 @@ function dedupeEvents(transitions: readonly TransitionEvidence[]): StateEvent[]/*** Drops an inferred end when an explicit end closes the same stint: the explicit date is when it ended, the inferred- * one only bounds it. A stint runs from a start to the next start (an implicit stint before the first start).+ * one only bounds it. Stints are assigned in replay order (an end sorts before a start on the same day, so a same-day+ * end and rejoin end the old stint): an end belongs to the stint the last start before it opened, or to the implicit+ * stint before the first start.*/function withoutOverriddenInferredEnds(events: StateEvent[]): StateEvent[] {- const stintOf = (date: string) => events.filter(e => e.kind === 'start' && e.date <= date).at(-1)?.date ?? null;- const explicit = new Set(events.filter(e => e.kind === 'end' && !e.inferred).map(e => stintOf(e.date)));- return events.filter(e => !(e.kind === 'end' && e.inferred && explicit.has(stintOf(e.date))));+ const stintOf = new Map<StateEvent, number>();+ let stint = 0;+ for (const e of events) {+ if (e.kind === 'start') stint++;+ else stintOf.set(e, stint);+ }+ const explicit = new Set([...stintOf].filter(([e]) => !e.inferred).map(([, s]) => s));+ return events.filter(e => !(e.kind === 'end' && e.inferred && explicit.has(stintOf.get(e)!)));}/** Merge touching/overlapping stints and drop empty ones (until <= from). */diff --git a/test/belief-ledger-w5-time-model.test.ts b/test/belief-ledger-w5-time-model.test.tsindex d605467a7d..62558ffd1b 100644--- a/test/belief-ledger-w5-time-model.test.ts+++ b/test/belief-ledger-w5-time-model.test.ts@@ -5,6 +5,7 @@*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { loadRelationshipNotes, relationshipNoteKey } from '../src/core/link-relationship-notes.ts';+import { refreshRelationships } from '../src/core/link-relationships.ts';import { testBackends } from './helpers/test-backends.ts';import { beliefBrain, beliefEngineCase, type BeliefBrain } from './helpers/belief-ledger.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -49,6 +50,22 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {expect(await note(b)).toContain('ended: works_at acme-example (2025-06-01)');}), 120_000);+ test('a private page\'s explicit end does not turn the world-scope upper bound exact (remote notes)', () => brain(async b => {+ await b.put('companies/acme-example', '---\ntype: company\ntitle: Acme\n---\nA company.\n');+ await b.put('companies/widget-co', '---\ntype: company\ntitle: Widget\n---\nAnother company.\n');+ await b.put('people/alice-example', person([JOINED_ACME, JOINED_WIDGET, INFERRED]));+ await b.put('notes/hr-private', '---\ntype: note\ntitle: HR\nvisibility: private\n---\nPrivate HR note.\n');+ const ids = Object.fromEntries((await b.engine.executeRaw<{ slug: string; id: number }>(+ 'SELECT slug, id FROM pages WHERE source_id = $1', [b.sourceId])).map(r => [r.slug, r.id]));+ await b.engine.executeRaw(`INSERT INTO link_transitions (source_id, from_page_id, to_page_id, link_type, kind, occurred_on, producer, origin_page_id)+ VALUES ($1, $2, $3, 'works_at', 'end', '2025-03-01', 'explicit', $4)`, [b.sourceId, ids['people/alice-example'], ids['companies/acme-example'], ids['notes/hr-private']]);+ await refreshRelationships(b.engine, [{ from_page_id: ids['people/alice-example']!, to_page_id: ids['companies/acme-example']!, link_type: 'works_at' }]);+ const notes = async (excludePrivate: boolean) => (await loadRelationshipNotes(b.engine,+ [{ slug: 'people/alice-example', source_id: b.sourceId, summary: '' }], { excludePrivate })).get(relationshipNoteKey(b.sourceId, 'people/alice-example'));+ expect(await notes(true)).toContain('ended: works_at acme-example (by 2025-03-01)');+ expect(await notes(false)).toContain('ended: works_at acme-example (2025-03-01)');+ }), 120_000);+test('the legacy engine copier refuses a brain whose page versions it would discard, and names how many', async () => {const { engine } = bare;{diff --git a/test/belief-ledger-weekly-diff.test.ts b/test/belief-ledger-weekly-diff.test.tsindex 6b80a2bc4e..ee68973755 100644--- a/test/belief-ledger-weekly-diff.test.ts+++ b/test/belief-ledger-weekly-diff.test.ts@@ -7,7 +7,7 @@ import { describe, expect, spyOn, test } from 'bun:test';import { beliefsChangesArgs, runBeliefs } from '../src/commands/beliefs.ts';import { currentExitCode, setCliExitVerdict } from '../src/core/cli-force-exit.ts';import { operationsByName } from '../src/core/operations.ts';-import { beliefChanges, renderBeliefChange, type BeliefChange } from '../src/core/belief/changes.ts';+import { __setBeliefChangesPageSizeForTests, beliefChanges, renderBeliefChange, type BeliefChange } from '../src/core/belief/changes.ts';import { testBackends } from './helpers/test-backends.ts';import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts';@@ -122,6 +122,63 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {expect((await changes(b, old, early)).coverage_from).toEqual(expect.any(String));}), 120_000);+ test('remote reads page on what each history page scanned, and before is the newest value at since', () => brain(async b => {+ await b.put(slug, beliefPage({ facts: [{ claim: 'Acme has 40 staff', confidence: '0.1' }] }));+ for (const c of ['0.2', '0.3', '0.4']) await b.put(slug, beliefPage({ facts: [{ claim: 'Acme has 40 staff', confidence: c }] }));+ const t0 = await at(b);+ await b.put('people/secret-example', beliefPage({ title: 'Secret', type: 'person', facts: ['Secret one', 'Secret two', 'Secret three'], frontmatter: { visibility: 'private' } }));+ await b.put('people/secret-example', beliefPage({ title: 'Secret', type: 'person', facts: ['Secret four', 'Secret five'], frontmatter: { visibility: 'private' } }));+ await b.put(slug, beliefPage({ facts: [{ claim: 'Acme has 40 staff', confidence: '0.9' }, 'Acme opened an office in Berlin'] }));+ const t1 = await at(b);+ const full = await changes(b, t0, t1, { remote: true });+ expect(sorted(brief(full.changes))).toEqual(sorted([['fact', 'changed', 'Acme has 40 staff'], ['fact', 'added', 'Acme opened an office in Berlin']]));+ expect(full.changes.find(c => c.change === 'changed')!.before!.confidence).toBe(0.4);+ try {+ for (const size of [1, 2, 3]) {+ __setBeliefChangesPageSizeForTests(size);+ expect(await changes(b, t0, t1, { remote: true })).toEqual(full);+ expect(await changes(b, t0, t1)).toEqual(await (async () => { __setBeliefChangesPageSizeForTests(); const r = await changes(b, t0, t1); __setBeliefChangesPageSizeForTests(size); return r; })());+ }+ } finally { __setBeliefChangesPageSizeForTests(); }+ }), 120_000);++ test('remote callers: a creation body never shows a fact made private later, or counts of what it cannot read; a take retraction is shown', () => brain(async b => {+ await b.put(slug, beliefPage({ facts: ['Acme sells widgets'] }));+ await b.put(slug, beliefPage({ facts: ['Acme sells widgets'], takes: [{ claim: 'Acme will IPO', who: 'world', weight: '0.4' }] }));+ const t0 = await at(b);+ await b.put('companies/newco-example', beliefPage({ title: 'Newco', facts: ['Newco signed SECRET-CONTRACT', 'Newco is public'], takes: [{ claim: 'Newco is privately loved', who: 'garry-example' }] }));+ await b.put(slug, beliefPage({ facts: ['Acme sells widgets'] }));+ const t1 = await at(b);+ // Made private after the window: the window's events never mention the fact, so only the creation body could show it.+ await b.put('companies/newco-example', beliefPage({ title: 'Newco', facts: [{ claim: 'Newco signed SECRET-CONTRACT', visibility: 'private' }, 'Newco is public'],+ takes: [{ claim: 'Newco is privately loved', who: 'garry-example' }] }));+ const local = await changes(b, t0, t1);+ expect(JSON.stringify(local)).toContain('SECRET-CONTRACT');+ const remote = await changes(b, t0, t1, { remote: true });+ expect(JSON.stringify(remote)).not.toContain('SECRET-CONTRACT');+ expect(JSON.stringify(remote)).not.toContain('privately');+ expect(sorted(brief(remote.changes))).toEqual(sorted([['page', 'added', 'companies/newco-example'], ['fact', 'added', 'Newco is public'], ['take', 'removed', 'Acme will IPO']]));+ expect(remote.changes.find(c => c.kind === 'page')!.after).toBeNull();+ expect(local.changes.find(c => c.kind === 'page')!.after).toMatchObject({ counts: expect.any(Object) });+ }), 120_000);++ test('page lifecycle nets out: a delete and its restore report nothing, and a page created and deleted inside the window reports nothing', () => brain(async b => {+ const revision = async (s: string) => (await b.engine.executeRaw<{ r: string }>('SELECT knowledge_revision::text AS r FROM pages WHERE source_id=$1 AND slug=$2', [b.sourceId, s]))[0]!.r;+ const del = async (s: string) => b.op('delete_page', { slug: s, expected_revision: await revision(s) });+ await b.put(slug, beliefPage({ facts: ['Acme sells widgets'] }));+ const t0 = await at(b);+ await del(slug);+ await b.op('restore_page', { slug, expected_revision: await revision(slug) });+ await b.put('companies/gone-example', beliefPage({ title: 'Gone', facts: ['Gone was here'] }));+ await del('companies/gone-example');+ const t1 = await at(b);+ expect(brief((await changes(b, t0, t1)).changes)).toEqual([]);+ await del(slug);+ const t2 = await at(b);+ expect(brief((await changes(b, t1, t2)).changes)).toEqual([['page', 'deleted', slug]]);+ expect(sorted(brief((await changes(b, t0, t2)).changes))).toEqual([['page', 'deleted', slug]]);+ }), 120_000);+test('delta {beliefs: true} carries the diff and its text section; budget_tokens truncates it, and a remote caller gets the world view', () => brain(async b => {await b.put(slug, beliefPage({ facts: ['Acme sells widgets'] }));const t0 = await at(b);diff --git a/test/belief-ledger-weekly-probes.test.ts b/test/belief-ledger-weekly-probes.test.tsindex 97dd89e12f..5b67cdc313 100644--- a/test/belief-ledger-weekly-probes.test.ts+++ b/test/belief-ledger-weekly-probes.test.ts@@ -97,11 +97,12 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {}));const hit = [...got].filter(x => expected.set.has(x)).length;tp += hit; fp += got.size - hit; fn += expected.set.size - hit;- for (const c of diff.changes.filter(c => c.change === 'changed' && (c.kind === 'fact' || c.kind === 'take'))) {+ // Every gold re-score is reported as changed with its exact before and after, and nothing else is.+ const rescored = Object.fromEntries(diff.changes.filter(c => c.change === 'changed' && (c.kind === 'fact' || c.kind === 'take')).map(c => {const field = c.kind === 'fact' ? 'confidence' : 'weight';- const want = expected.values.get(`${c.kind}|${c.slug}|${c.subject.claim}`);- if (want) expect([Number(c.before![field]), Number(c.after![field])]).toEqual(want.map(Number));- }+ return [`${c.kind}|${c.slug}|${c.subject.claim}`, [Number(c.before![field]), Number(c.after![field])]];+ }));+ expect(rescored).toEqual(Object.fromEntries([...expected.values].map(([k, v]) => [k, v.map(Number)])));await new Promise(r => setTimeout(r, 2_200));const delta = await operationsByName.delta!.handler(b.ctx, { since: t0 }) as { pages: unknown[]; text: string };const beliefText = diff.changes.map(renderBeliefChange).join('\n');diff --git a/test/link-validity.test.ts b/test/link-validity.test.tsindex 46f0df7fc6..6132428cfd 100644--- a/test/link-validity.test.ts+++ b/test/link-validity.test.ts@@ -140,6 +140,11 @@ describe('buildRelationshipState — inferred closures are upper bounds (W5)', (expect(buildRelationshipState('state', [], [start('2019-02-01'), inferredEnd('2025-03-01'), end('2025-03-01')]).lastEndUpperBound).toBe(false);});+ test('a same-day explicit end and rejoin ends the old stint, so it does not override the new stint\'s inferred closure', () => {+ const s = buildRelationshipState('state', [], [start('2019-02-01'), end('2022-01-01'), start('2022-01-01'), inferredEnd('2025-03-01')]);+ expect(s).toMatchObject({ lastEnd: '2025-03-01', lastEndUpperBound: true });+ });+test('order invariance holds with inferred and explicit ends mixed', () => {const ev = [start('2019-02-01'), inferredEnd('2025-03-01'), end('2025-06-01', 2), start('2026-01-01')];const baseline = JSON.stringify(buildRelationshipState('state', [], ev));