Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W4: gbrain beliefs changes (thin client routes through delta), delta belief packing in changes.ts, design sections 15-16, protocol and user docs, BEHAVIOR_CHANGES rows for W5
garrytan41e2900f9171
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex b402fa6145..c2c080859d 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -360,6 +360,8 @@ The legacy copier handles every other direction: `gbrain migrate --to pglite`, P| A Postgres brain moving to PGLite | `report` | The brain stays on Postgres; moving down would drop its history. || A target that already holds persistence history | `tell_user_to_run` | Rerun with an empty database the user provides (`--path` for a PGLite target). |+A brain with page versions but no write history gets the same refusal with `reason: page_history` and the number of versions in the message: the legacy copier re-creates pages without their versions, so the copy would discard them. Graduation (PGLite to Postgres) carries them.+On Windows, a PGLite brain with history gets `graduation_unsupported_platform` instead: it stays on PGLite and is shared with `gbrain mcp expose`.<a id="graduation-writer-held"></a>**Graduation refused: the brain is held (`graduation_source_writer_held`).** Graduation needs the PGLite kernel lock. A live stdio `gbrain serve` hands the brain over through the intent marker `<path>.gbrain-graduation.json` and exits; autopilot pauses. When another holder (an HTTP serve, a daemon, another command) does not release the brain within 30 seconds, the run refuses and names it with its pid and transport (`fix.next: tell_user_to_run`). The user stops that process, then the agent reruns the same `gbrain migrate` command. Verify with the read-only `gbrain migrate --status --json`. Nothing has changed in either datastore.diff --git a/docs/architecture/key-files/belief-ledger.md b/docs/architecture/key-files/belief-ledger.mdindex 8ff570a2c3..38680695b2 100644--- a/docs/architecture/key-files/belief-ledger.md+++ b/docs/architecture/key-files/belief-ledger.md@@ -17,8 +17,9 @@ Design: [BELIEF_LEDGER.md](../../designs/BELIEF_LEDGER.md). Operator surface: `g- `src/core/belief/history.ts` — the one history reader (`readBeliefHistory`); remote callers see only events that were world-visible when recorded on a page visible now, failing closed.- `src/core/belief/page-at-time.ts` — W2 page-at-time (BELIEF_LEDGER.md section 10): `readPageAtTime` replays a slug's page events of every lifetime into validity intervals under the section 5.3 visibility rule (a straddling write refuses `known_as_of_unproven`), refuses `coverage_from` / `coverage_gap` from `coverageAt`, and pairs each closed interval with the preimage version the next transition wrote (by revision, in order); the open head reads the live page. A body no version holds is disclosed (`body_reason`), never borrowed. Purge-redacted events carry no revision, so a purged lifetime splits only on slug and deleted state. `remoteMayRead` applies history.ts's remote rule per interval.- `src/core/belief/preimages.ts` — the preimage invariant (BELIEF_LEDGER.md section 14 item 8): a revision-moving publication leaves a version of its `revision_before`. `missingPreimages` is the in-batch check `finalizeBeliefEvents` runs under `NODE_ENV=test` (off with `GBRAIN_BELIEF_PREIMAGE_CHECK=0`); `preimageGaps` is doctor's production scan (large and segmented pages exempt).+- `src/core/belief/changes.ts` — W4 weekly change diff (BELIEF_LEDGER.md section 15): `beliefChanges` reads the window through `readBeliefHistory` (`recordedAfter`/`recordedUntil`, then `subjectKeys` up to `since` for each subject's value before), nets each subject end to end, reads a subject with no earlier event from the page body at `since` (`before_known: false` when no body answers), lists a page created in the window with its creation body's fence rows, flags a `dream`-inferred link end `upper_bound`, and skips backfill and baseline events. Remote callers get world fence rows only where `remoteMayRead` passes. Served by `delta {beliefs: true}` and `gbrain beliefs changes`.- `src/core/ops/known-as-of.ts` — the op surface: `get_page {known_as_of}` and `get_versions {known_as_of, diff, source_id}` (full surface only). One target source (explicit, ambient, or the only granted source whose ledger names the slug); remote callers get only readable intervals of a page visible now at their trust floor, with sanitized bodies. `parseKnownAsOf` refuses a bare date `clock_mismatch`.- `src/core/engine-sql/pages.ts` `updateSlug` — versions the page before the move (the move advances the revision), so page-at-time has the body from before a rename.-- `src/commands/beliefs.ts` — `gbrain beliefs enable|disable|status|reconcile|backfill` (local only; `--json`); an unknown source is `invalid_params`.+- `src/commands/beliefs.ts` — `gbrain beliefs enable|disable|status|changes|reconcile|backfill|replay-purges` (`--json`); an unknown source is `invalid_params`. Only `changes` routes on a thin client: `thin-client-routing.ts` calls the host's `delta {beliefs: true}` (so it lists the remote world view) and refuses `--source`; every other subcommand is host-only.- `src/commands/doctor/checks/belief-ledger.ts` — doctor `belief_ledger_coverage`: intervals and certification, baseline progress, drift (sampled; complete under `--tier deep`), orphan lifetimes, unmarked publications, and a restore whose purge replay was partial, unavailable or unverified (`ask_user`). `--fix` reconciles and fills marks; a brain without coverage is information with an `ask_user` enable.- Retention purge (BELIEF_LEDGER.md 6.5): on a managed brain `purge-deleted.ts` passes the internal `retention: true` (`purge-params.ts` accepts it only from a local caller with `purge: true`): it writes no content tombstone, redacts no history, appends no purge-mirror line and records `page.expired`. On an unmanaged brain each expired tombstone of a source with belief coverage is first deleted under its page key in a belief batch that appends `page.expired`; the bulk delete takes the rest.diff --git a/docs/designs/BELIEF_LEDGER.md b/docs/designs/BELIEF_LEDGER.mdindex 8a18b16a83..0d80d87fec 100644--- a/docs/designs/BELIEF_LEDGER.md+++ b/docs/designs/BELIEF_LEDGER.md@@ -1589,3 +1589,84 @@ Garry accepted those answers. Questions 5, 6, 7 and 8 are decided.its version redaction pass then redacts that version like every otherone, so the interval before a purge reads the body as it stood, minus thepurged claim.++## 15. W4 as built: the weekly change diff++1. **Surface.** One reader, two doors. `delta {beliefs: true}` (full surface+ only, so the served starter schema is unchanged) adds `beliefs` for the+ same window as the rest of the wake, and `gbrain beliefs changes+ [<entity>...] [--since 7d]` prints it from the CLI. Both call+ `beliefChanges` (`src/core/belief/changes.ts`). On a thin client the CLI+ calls the host's `delta`, so it lists what a remote caller may see.+ `entities` (the CLI's positionals) keeps changes whose stream page, fact+ subject or entity, or link end is one of the named slugs.+2. **One entry per belief that ended the window different.** Events are read+ from `readBeliefHistory` between `since` (exclusive) and `until`+ (inclusive), grouped by subject key, and compared end to end: `before` is+ the subject's newest event at or before `since`, `after` its newest event+ in the window. An edit and its revert, or an assert and its retraction,+ report nothing. Each entry carries `kind` (`page`, `fact`, `take`,+ `link`, `link_transition`), `change` (`added`, `removed`, `changed`;+ page events add `deleted`, `restored`, `renamed`), a readable `subject`,+ `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`.+3. **A subject with no earlier event.** Section 4 records a page's creation+ as one snapshot event, so a fact or take first edited inside the window may+ have no event before `since`. Its `before` is read from the page body as+ recorded at `since` (page-at-time, section 14). When no body answers (a+ pruned, purged or segmented body, or no version), `before` is null and+ `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.+4. **Upper bounds.** A relationship end that only the nightly check inferred+ (a transition whose producer is `dream`) is flagged `upper_bound: true` and+ rendered `end by <date>`: the relationship ended on or before that date+ (section 16).+5. **What is never a change.** Backfill and baseline events are skipped:+ backfill carries source times, and a baseline is the state a coverage run+ found. A window that starts before the source's coverage sets+ `coverage_from`, because earlier changes are unknown rather than absent; a+ source with no coverage at all returns `not_recorded: true`.+6. **Remote callers.** `delta` passes `remote: !include_private`. The history+ reader'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.+7. **Budget.** Under `budget_tokens`, belief lines pack into what pages,+ facts and threads leave; a dropped line sets `truncated`. Without a+ budget the list is capped at 200 entries, and a window with more than+ 50,000 events stops reading and sets `truncated`.+8. **Measured at $0.** Four seeded synthetic weeks (37 gold changes) give+ set-F1 1.0 with exact before and after values on PGLite and Postgres+ (`test/belief-ledger-weekly-probes.test.ts`). The cited diff costs 258,+ 233, 215 and 273 tokens against 227, 182, 307 and 281 for the plain list+ of changed pages, so the cited answer costs about the same as the list it+ replaces while naming each claim, its old value and its evidence.++## 16. W5 as built: the time-model fixes++1. **Inferred ends are upper bounds.** `RelationshipState.lastEndUpperBound`+ (`link-validity.ts`) is true when every transition behind the last end has+ producer `dream`: the nightly contradiction check closed the stint on the+ day it noticed, so the true end is on or before that date. The relationship+ note renders `ended: works_at acme-example (by 2025-03-01)`.+2. **An explicit end replaces the inferred one.** An explicit end of the same+ stint, earlier or later than the inferred closure, replaces it+ (`withoutOverriddenInferredEnds`), so a late correction from the page is+ the end the reader sees.+3. **Correction to the plan: page versions are not copied between engines.**+ `gbrain migrate --to <engine>` on a source brain that holds page versions and+ no journal tables refuses `writer_coordinator_required` (reason+ `page_history`, "Engine migration would discard N page versions.")+ instead of copying them. The legacy copier re-creates pages with new ids,+ so carrying versions would mean re-keying every version to its new page;+ graduation to a managed brain already carries them+ (`persistence/graduation-copy.ts`), so the plan's copy step is replaced by+ the refusal, which names how many versions the copy would have discarded.+4. **Dropped from the plan.** The `since_supplied` probe passes on master, so+ no fix shipped for it; the probe stays as a regression pin+ (`test/belief-ledger-w5-time-model.test.ts`).+5. **E2 moves to a custodian.** The rerun of the P1 E2 late-closure eval runs+ on held-out text in owner custody, preregistered in gbrain-evals before any+ run; nothing in this repository reads the held-out set.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 25803e4121..20b463712a 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2326,6 +2326,19 @@ guess. The refusal is `retryable`: ask about an instant before the write'srecorded time, or after its commit was observed (the message names the write).A stalled transaction stays unproven until it commits and is marked.+### What changed in a window++`gbrain beliefs changes [<entity>...] [--since 7d]` (and `delta {beliefs: true}`+for agents) lists each fact, take, link and page that ended the window+different from how it started: before, after, the event that caused it and+its event id. An edit and its revert report nothing. `earlier value unknown`+means no recorded body answers for the start of the window, not that the+belief was absent; `end by <date>` is a relationship end the nightly check+inferred, so it ended on or before that date. A window that starts before the+ledger was enabled says where coverage starts. On a thin client the command+runs through the host and lists only world beliefs on pages visible now+([design, section 15](../designs/BELIEF_LEDGER.md#15-w4-as-built-the-weekly-change-diff)).+## Repair refusal codesEach heading below is the `docs` anchor a refusal carries.diff --git a/docs/guides/temporal-edges.md b/docs/guides/temporal-edges.mdindex 6583336313..ea9173431f 100644--- a/docs/guides/temporal-edges.md+++ b/docs/guides/temporal-edges.md@@ -218,8 +218,11 @@ its closures are applied as timeline lines, each undoable. SetThe closure date is the newer relationship's start. When someone left one job andstarted the next later, and only the "joined" lines are written, the earlier job closes-on the later start date: late, not wrong. An explicit end line-(`Ended works_at [[companies/x]]`) or a "left" line dates it exactly.+on the later start date: late, not wrong. So a closure only the check dated is shown as+an upper bound, `ended: works_at acme-example (by 2025-03-01)`, and `gbrain beliefs+changes` marks it `end by 2025-03-01`. An explicit end line+(`Ended works_at [[companies/x]]`) or a "left" line dates it exactly and replaces the+inferred end, whether its date is earlier or later.| Setting | Default ||---|---|diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 4e0271d62b..773705ae40 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -960,7 +960,7 @@ timeline entry's event page) follows the same page rule, and facts and takesfence rows never count as an edit. The same assembler servesthe off-by-default hook push ([push context](../guides/push-context.md)).-### delta(since?, since_slug?, cursor?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM+### delta(since?, since_slug?, cursor?, entities?, budget_tokens?, session_id?, include_private?, beliefs?) — read, zero LLM"What changed since T" for heartbeats — pages updated afterthe cursor (oldest first) + facts recorded after the cursor + open-thread@@ -1032,6 +1032,26 @@ real rendered size, which then exceeds the budget. `since` is alwaysnormalized ISO (never the raw input string). Replay recipe:[ambient recall guide](../guides/ambient-recall.md#replay-after-a-degraded-wake).+**Belief changes (`beliefs: true`, full surface only).** Adds `beliefs`: each+belief that ended the window different from how it started, read from the+belief ledger for the same window as the wake (`since` to the wake's horizon).+`{ source_id, since, until, coverage_from, changes[], truncated, not_recorded? }`;+each change is `{ kind, slug, change, subject, before, after, before_known,+upper_bound?, cause, evidence: { event_id, recorded_at, slug, row? }, trust_tier }`.+An edit and its revert in the window report nothing. `before_known: false`+means the earlier value is unknown (no body answers at `since`), never that+it was empty; `upper_bound: true` marks a relationship end the nightly check+inferred, so it ended on or before that date. `coverage_from` is set when the+ledger starts after `since` (earlier changes are unknown, not absent), and+`not_recorded` when the source has no ledger coverage. `entities` narrows the+list 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+CLI 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).+## Latency classes (per verb)Published so harness authors place calls by cost, not by learning at timeout:diff --git a/llms-full.txt b/llms-full.txtindex 9142b18918..317d0addbb 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5641,6 +5641,8 @@ The legacy copier handles every other direction: `gbrain migrate --to pglite`, P| A Postgres brain moving to PGLite | `report` | The brain stays on Postgres; moving down would drop its history. || A target that already holds persistence history | `tell_user_to_run` | Rerun with an empty database the user provides (`--path` for a PGLite target). |+A brain with page versions but no write history gets the same refusal with `reason: page_history` and the number of versions in the message: the legacy copier re-creates pages without their versions, so the copy would discard them. Graduation (PGLite to Postgres) carries them.+On Windows, a PGLite brain with history gets `graduation_unsupported_platform` instead: it stays on PGLite and is shared with `gbrain mcp expose`.<a id="graduation-writer-held"></a>**Graduation refused: the brain is held (`graduation_source_writer_held`).** Graduation needs the PGLite kernel lock. A live stdio `gbrain serve` hands the brain over through the intent marker `<path>.gbrain-graduation.json` and exits; autopilot pauses. When another holder (an HTTP serve, a daemon, another command) does not release the brain within 30 seconds, the run refuses and names it with its pid and transport (`fix.next: tell_user_to_run`). The user stops that process, then the agent reruns the same `gbrain migrate` command. Verify with the read-only `gbrain migrate --status --json`. Nothing has changed in either datastore.@@ -9954,7 +9956,7 @@ timeline entry's event page) follows the same page rule, and facts and takesfence rows never count as an edit. The same assembler servesthe off-by-default hook push ([push context](../guides/push-context.md)).-### delta(since?, since_slug?, cursor?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM+### delta(since?, since_slug?, cursor?, entities?, budget_tokens?, session_id?, include_private?, beliefs?) — read, zero LLM"What changed since T" for heartbeats — pages updated afterthe cursor (oldest first) + facts recorded after the cursor + open-thread@@ -10026,6 +10028,26 @@ real rendered size, which then exceeds the budget. `since` is alwaysnormalized ISO (never the raw input string). Replay recipe:[ambient recall guide](../guides/ambient-recall.md#replay-after-a-degraded-wake).+**Belief changes (`beliefs: true`, full surface only).** Adds `beliefs`: each+belief that ended the window different from how it started, read from the+belief ledger for the same window as the wake (`since` to the wake's horizon).+`{ source_id, since, until, coverage_from, changes[], truncated, not_recorded? }`;+each change is `{ kind, slug, change, subject, before, after, before_known,+upper_bound?, cause, evidence: { event_id, recorded_at, slug, row? }, trust_tier }`.+An edit and its revert in the window report nothing. `before_known: false`+means the earlier value is unknown (no body answers at `since`), never that+it was empty; `upper_bound: true` marks a relationship end the nightly check+inferred, so it ended on or before that date. `coverage_from` is set when the+ledger starts after `since` (earlier changes are unknown, not absent), and+`not_recorded` when the source has no ledger coverage. `entities` narrows the+list 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+CLI 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).+## Latency classes (per verb)Published so harness authors place calls by cost, not by learning at timeout:diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjsindex 8bf2eb5d41..4fd946fb5b 100644--- a/scripts/check-orphan-modules.mjs+++ b/scripts/check-orphan-modules.mjs@@ -53,7 +53,6 @@ const ALLOWLIST = new Map([// string in a reviewer-visible edit. Modules reached from `scripts/**` carry// reason 'script-reachable', which the guard verifies.const PERMITTED_TEST_ONLY = [- { path: 'src/core/belief/history.ts', reason: 'held: the belief ledger history reader ships in W1 with its remote privacy probe (docs/designs/BELIEF_LEDGER.md probe 14); W2 history reads are its product caller' },{ path: 'src/core/bootstrap/template-repo.ts', reason: 'script-reachable' },{ path: 'src/eval/longmemeval/diagnostics.ts', reason: 'script-reachable' },{ path: 'src/eval/longmemeval/evidence-brief.ts', reason: 'held: eval-only wave 1 brief builder (10x memory advantage plan A3), loaded by path from gbrain-evals eval/runner/pilot; product wiring is plan item A8, conditional on the A5 pilot' },diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 82dfe1b258..b6cedc513b 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -72,6 +72,7 @@ src/core/attendance-repair.ts prepareOrigin field METAsrc/core/attendance-repair.ts readOrigin sql METAsrc/core/belief/backfill.ts preparePage field STREAM the backfill parses inline version and page bodies; a segmented page or version is skipped (summary reasons large_page_versions_pruned, segmented_version_body)src/core/belief/backfill.ts preparePage sql STREAM the backfill parses inline version and page bodies; a segmented page or version is skipped (summary reasons large_page_versions_pruned, segmented_version_body)+src/core/belief/changes.ts subjectsOf field STREAM weekly change diff: reads fence subjects from a page-at-time interval body; a segmented or unavailable interval answers null (before_known false), never a body string; inline bodies onlysrc/core/belief/purge.ts pagePurgeClaims field STREAM segmented version: NULL body parses no fence claims; the live rows' and the lifetimes' event claims still cover itsrc/core/belief/purge.ts pagePurgeClaims sql STREAM segmented version: NULL body parses no fence claims; the live rows' and the lifetimes' event claims still cover itsrc/core/belief/purge.ts registerVersionCarriers field STREAM segmented version: NULL body registers no carriers; the backfill skips the same version (segmented_version_body), so nothing it appends can copy onediff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 66f9ebf9cb..e0d4860409 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -395,7 +395,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp{ name: 'quarantine', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, load: () => import('./commands/quarantine.ts') },// #5575: memory trust. Observational startup: `trust backfill --dry-run` runs with no migrations and no writes.// W1 belief ledger coverage: enable, disable, status, reconcile, backfill (docs/designs/BELIEF_LEDGER.md section 7).- { name: 'beliefs', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/beliefs.ts') },+ { name: 'beliefs', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/beliefs.ts') },{ name: 'trust', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', skipStartupHooks: true, startup: 'observational', load: () => import('./commands/trust.ts') },// selfHelp: v0.43 (#2095): watch ships WATCH_HELP (flags + the stdin-turn protocol).// thin client: v0.43 (#2095): watch streams against a LOCAL engine; thin clients get thediff --git a/src/commands/beliefs.ts b/src/commands/beliefs.tsindex bf4106392b..fb0a84eda3 100644--- a/src/commands/beliefs.ts+++ b/src/commands/beliefs.ts@@ -18,13 +18,19 @@ import { readLedgerSource } from '../core/belief/ledger.ts';import { readManagedMode } from '../core/persistence/managed-mode.ts';import { resolveSourceId, SourceTargetError } from '../core/source-resolver.ts';import { replayPurgesCli } from './beliefs-replay-purges.ts';+import { beliefChanges, renderBeliefChanges } from '../core/belief/changes.ts';+import { parseSince } from '../core/since.ts';export const BELIEFS_USAGE = [- 'Usage: gbrain beliefs <enable|disable|status|reconcile|backfill|replay-purges> [--source <id>] [--json]',+ 'Usage: gbrain beliefs <enable|disable|status|changes|reconcile|backfill|replay-purges> [--source <id>] [--json]',' enable Start recording the belief ledger on a source: baselines every page (resumable) and sets the watermark.',' Only a managed source\'s coverage is certified; an unmanaged source is recorded but uncertified.',' disable Stop recording (appends coverage.stopped); enabling again starts a new interval with a new baseline.',' status Coverage intervals per source: watermark, certified or uncertified, baseline progress, restore gaps, drift.',+ ' changes [<entity>...] [--since 7d]',+ ' Each belief that changed in the window (default the last 7 days), before and after, with the event that caused it.',+ ' An inferred relationship end is marked as an upper bound. On a thin client this runs through the host\'s delta',+ ' and lists what a remote caller may see: world beliefs on pages visible now.',' reconcile Appends reconcile events for slugs whose state drifted from their newest event, and fills missing commit marks.',' A drifted slug\'s interval stays uncertified on a managed source.',' backfill Seeds best-effort history before the coverage start from retained page versions (never certified).',@@ -33,7 +39,24 @@ export const BELIEFS_USAGE = [' --source <id> The source (default: every covered source for status and reconcile; the resolved source, as for other commands, for the rest).',].join('\n');-const SUBCOMMANDS = ['enable', 'disable', 'status', 'reconcile', 'backfill', 'replay-purges'] as const;+const SUBCOMMANDS = ['enable', 'disable', 'status', 'changes', 'reconcile', 'backfill', 'replay-purges'] as const;++/** `beliefs changes` arguments: the entity slugs and the window start, shared with the thin-client route. */+export function beliefsChangesArgs(args: string[], now = Date.now()): { entities: string[]; since: string } {+ const entities: string[] = [];+ for (let i = 1; i < args.length; i++) {+ if (args[i] === '--since' || args[i] === '--source') i++;+ else if (!args[i]!.startsWith('-')) entities.push(args[i]!);+ }+ const at = args.indexOf('--since');+ const raw = at >= 0 ? args[at + 1] : args.find(a => a.startsWith('--since='))?.slice('--since='.length);+ if ((at >= 0 || raw !== undefined) && (!raw || raw.startsWith('-'))) throw opError('invalid_params', '--since needs a value.', 'Pass a relative age (7d, 24h) or an ISO date (2026-10-01).');+ try {+ return { entities, since: parseSince(raw ?? '7d', '--since', now)! };+ } catch (error) {+ throw opError('invalid_params', (error as Error).message, 'Pass a relative age (7d, 24h) or an ISO date (2026-10-01).');+ }+}function sourceArg(args: string[]): string | undefined {const at = args.indexOf('--source');@@ -70,7 +93,7 @@ export async function runBeliefs(engine: BrainEngine, args: string[]): Promise<vif (args.includes('--help') || args.includes('-h') || !sub) { console.log(BELIEFS_USAGE); return; }try {if (!(SUBCOMMANDS as readonly string[]).includes(sub)) {- throw opError('invalid_params', `Unknown beliefs subcommand '${sub}'.`, 'gbrain beliefs --help lists enable, disable, status, reconcile, backfill and replay-purges.');+ throw opError('invalid_params', `Unknown beliefs subcommand '${sub}'.`, 'gbrain beliefs --help lists enable, disable, status, changes, reconcile, backfill and replay-purges.');}const named = sourceArg(args);if (named !== undefined && !await readLedgerSource(engine, named)) throw unknownSource(named);@@ -100,6 +123,12 @@ export async function runBeliefs(engine: BrainEngine, args: string[]): Promise<v+ `${incomplete.length ? `; ${incomplete.length} page(s) incomplete (${[...new Set(incomplete.flatMap(p => p.reasons))].join(', ')})` : ''}.`);return;}+ if (sub === 'changes') {+ const { entities, since } = beliefsChangesArgs(args);+ const changes = await beliefChanges(engine, { sourceId: await target(), since, until: new Date().toISOString(), remote: false, entities });+ await report(args, changes, renderBeliefChanges(changes));+ return;+ }if (sub === 'replay-purges') {const { value, text } = await replayPurgesCli(engine, args);await report(args, value, text);diff --git a/src/commands/thin-client-routing.ts b/src/commands/thin-client-routing.tsindex c12329be48..de9a9697e6 100644--- a/src/commands/thin-client-routing.ts+++ b/src/commands/thin-client-routing.ts@@ -74,6 +74,26 @@ export async function routeThinClientCommand(exitCliError(sharedSkillsRemoteRefusal(id, action === 'on' || action === 'off' ? action : 'status'), 'sources');}+ if (command === 'beliefs' && sub === 'changes' && !rest.includes('--help') && !rest.includes('-h')) {+ if (rest.includes('--source') || rest.some(a => a.startsWith('--source='))) return false; // the remote token names the source+ const { beliefsChangesArgs } = await import('./beliefs.ts');+ const { renderBeliefChanges } = await import('../core/belief/changes.ts');+ const { opError, OperationError } = await import('../core/ops/contract.ts');+ const { writeCliError } = await import('../cli/cli-error.ts');+ const { jsonRequested, setCliExitVerdict } = await import('../core/cli-force-exit.ts');+ try {+ const { entities, since } = beliefsChangesArgs(args);+ const result = await call(cfg, 'delta', { since, beliefs: true, ...(entities.length ? { entities: entities.join(',') } : {}) }) as { beliefs?: import('../core/belief/changes.ts').BeliefChanges };+ if (!result?.beliefs) throw opError('unavailable', 'The remote brain\'s delta does not return belief changes: the brain host runs a gbrain older than the belief ledger weekly diff.', 'Upgrade gbrain on the brain host (gbrain upgrade there).');+ if (jsonRequested(args)) printJson(result.beliefs);+ else console.log(renderBeliefChanges(result.beliefs));+ } catch (error) {+ if (!(error instanceof OperationError)) throw error;+ setCliExitVerdict(writeCliError(error, 'beliefs', { json: jsonRequested(args) }));+ }+ return true;+ }+if (command === 'config') {const { tryRunConfigThinClient } = await import('./config.ts');return tryRunConfigThinClient(args);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 65e65498fe..76cb49e06c 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -724,6 +724,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.267.0', text: '`purge_fact` now saves each page it rewrites as a version before dropping the purged fence row, and its version redaction then removes the claim from that version as from every other, so `get_versions` and `gbrain history` list one more snapshot per page a fact purge rewrites. The snapshot holds the page as it stood before the purge, without the purged claim.' },// Remote open-loop hotfix (GBRA-120).{ since: '0.60.268.0', text: 'Remote callers (every MCP transport) no longer get open-loop-backed threads on `entity` cards, or in `context_pack` and `delta`, which build on those cards: no loop summary, `due` or `loop_id`. Use `open_loops`, which reads loops only in granted sources. The trusted local CLI still sees them on `gbrain entity`, and in `context_pack` / `delta` with `include_private`. Remote `open_loops` grouped results no longer rank counterparties by backlink counts.' },+ // Wave 4a W5 belief ledger time model. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.268.0', text: 'A relationship end that only the nightly relationship check dated (a `gbrain-dream (inferred)` timeline line) is now shown as an upper bound: relationship notes on entity cards, `context_pack`, ambient turn context and compiled context files read `ended: works_at acme-example (by 2025-03-01)` instead of `(2025-03-01)`, because the check closes the earlier relationship on the day the next one started, so the real end may be earlier. An explicit end line for the same stint now replaces the inferred end whether its date is earlier or later; before, the relationship stayed closed on the earlier inferred date even when the page dated its end later.' },+ { since: '0.60.268.0', text: '`gbrain migrate --to <engine>` through the legacy copier (graduation turned off, or Postgres to PGLite) now refuses a brain that holds page versions, with `writer_coordinator_required`, `reason: page_history` and the number of versions it would discard, instead of copying the pages without them. Nothing changes in either datastore. Graduation from PGLite to Postgres carries versions and is unaffected.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/belief/changes.ts b/src/core/belief/changes.tsindex aa95bb1a4b..32440e1400 100644--- a/src/core/belief/changes.ts+++ b/src/core/belief/changes.ts@@ -27,6 +27,7 @@ import { coverageAt } from './coverage-report.ts';import { readPageAtTime, remoteMayRead } from './page-at-time.ts';import { bodySubjects } from './backfill.ts';import { canonicalJson } from './keys.ts';+import { estimateTokens, packToBudget } from '../search/token-budget.ts';export type BeliefChangeKind = 'page' | 'fact' | 'take' | 'link' | 'link_transition';export interface BeliefChange {@@ -219,6 +220,32 @@ async function readCreationSubjects(engine: BrainEngine, q: BeliefChangesQuery,return read && interval ? subjectsOf(engine, q, read, interval) : null;}+const lineCost = (line: string) => estimateTokens(line + '\n');++/**+ * `delta {beliefs: true}`: the window's changes and the wake's `text` with their section appended (under `envelope`+ * when the wake has no text of its own); `text` comes back unchanged when nothing changed. Under a budget the header and each line pack into what pages, facts+ * and threads left (`budget`); a cut sets `truncated`.+ */+export async function deltaBeliefs(engine: BrainEngine, q: BeliefChangesQuery, budget: number | null, text: string, envelope: string): Promise<{ beliefs: BeliefChanges; text: string }> {+ let beliefs = await beliefChanges(engine, q);+ const header = `## Belief changes since ${q.since}`;+ if (budget !== null) {+ const room = budget - lineCost('') - lineCost(header);+ const kept = room > 0 ? packToBudget(beliefs.changes, c => lineCost(renderBeliefChange(c)), room).items : [];+ if (kept.length < beliefs.changes.length) beliefs = { ...beliefs, changes: kept, truncated: true };+ }+ return { beliefs, text: beliefs.changes.length ? [text || envelope, '', header, ...beliefs.changes.map(renderBeliefChange)].join('\n') : text };+}++/** The CLI's text for a whole window: a header, the coverage note, one line per change. */+export function renderBeliefChanges(b: BeliefChanges): string {+ if (b.not_recorded) return `The belief ledger is not recording ${b.source_id}; enable it with gbrain beliefs enable --source ${b.source_id}.`;+ return [`Belief changes on ${b.source_id} from ${b.since} to ${b.until}: ${b.changes.length}${b.truncated ? ' (truncated: more changed than this lists)' : ''}`,+ ...(b.coverage_from ? [` The ledger starts at ${b.coverage_from}; changes before it are unknown, not absent.`] : []),+ ...b.changes.map(renderBeliefChange)].join('\n');+}+/** One line per change, for `delta`'s text block and the CLI. */export function renderBeliefChange(c: BeliefChange): string {const day = c.evidence.recorded_at.slice(0, 10);diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 83ffa4ae98..e168eb23e5 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -22,7 +22,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],- 'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--source'],+ 'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],'book-mirror': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 505434e867..1d53db07fc 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -5263,6 +5263,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = [],"description": "Lowest trust tier to return (the connection floor still applies).","fullSurfaceOnly": true+ },+ "beliefs": {+ "type": "boolean",+ "fullSurfaceOnly": true,+ "description": "Add `beliefs`: each belief that changed in the window, before and after, with cause and evidence (belief ledger); entities narrows it."}},"scope": "read",diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 4f70beeccd..21c888e4e0 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -1218,16 +1218,9 @@ const delta: Operation = {// `text` must honor the budget AND the boundary-tie exclusion the// structured arrays reflect — the assembler's render predates both.let text = renderDelta(pages, facts, threads, effectiveSince);- let beliefs: import('../belief/changes.ts').BeliefChanges | undefined;- if (p.beliefs === true) {- const { beliefChanges, renderBeliefChange } = await import('../belief/changes.ts');- beliefs = await beliefChanges(ctx.engine, { sourceId, since: effectiveSince, until: horizon, remote: !includePrivate, entities: parseEntityList(p.entities) });- if (budgetTokens !== null) {- const pack = beliefBudget > 0 ? packToBudget(beliefs.changes, c => lineCost(renderBeliefChange(c)), beliefBudget) : dropAll(beliefs.changes);- if (pack.meta.dropped > 0) beliefs = { ...beliefs, changes: pack.items, truncated: true };- }- if (beliefs.changes.length) text = [text || TURN_CONTEXT_ENVELOPE, '', `## Belief changes since ${effectiveSince}`, ...beliefs.changes.map(renderBeliefChange)].join('\n');- }+ const diff = p.beliefs === true ? await (await import('../belief/changes.ts')).deltaBeliefs(ctx.engine, { sourceId, since: effectiveSince, until: horizon,+ remote: !includePrivate, entities: parseEntityList(p.entities) }, budgetTokens !== null ? beliefBudget : null, text, TURN_CONTEXT_ENVELOPE) : null;+ if (diff) text = diff.text;const budgetUsed = budgetTokens !== null ? estimateTokens(text) : undefined;return {@@ -1263,7 +1256,7 @@ const delta: Operation = {...(budgetTokens !== null? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }: {}),- ...(beliefs ? { beliefs } : {}),+ ...(diff ? { beliefs: diff.beliefs } : {}),};},};diff --git a/test/belief-ledger-w5-time-model.test.ts b/test/belief-ledger-w5-time-model.test.tsindex b6fd78a042..d605467a7d 100644--- a/test/belief-ledger-w5-time-model.test.ts+++ b/test/belief-ledger-w5-time-model.test.ts@@ -3,7 +3,7 @@* on PGLite and on Postgres when DATABASE_URL is set; and the `since_supplied` probe the plan required before any* takes change (a late-captured take keeps its valid time, and an update without `since` keeps the stored one).*/-import { describe, expect, test } from 'bun:test';+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { loadRelationshipNotes, relationshipNoteKey } from '../src/core/link-relationship-notes.ts';import { testBackends } from './helpers/test-backends.ts';import { beliefBrain, beliefEngineCase, type BeliefBrain } from './helpers/belief-ledger.ts';@@ -24,6 +24,14 @@ const takes = async (b: BeliefBrain, slug: string) => b.engine.executeRaw<{ row_for (const engineCase of testBackends().map(beliefEngineCase)) {describe(`W5 time model (${engineCase.name})`, () => {const brain = (run: (b: BeliefBrain) => Promise<void>) => beliefBrain(run, { managed: true, databaseUrl: engineCase.databaseUrl });+ // A bare brain (no managed persistence rows) for the legacy copier cell.+ let bare: { engine: BrainEngine; close: () => Promise<void> };+ beforeAll(async () => {+ if (engineCase.databaseUrl) { bare = await isolatedPersistencePostgres(engineCase.databaseUrl); return; }+ const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema();+ bare = { engine: pglite, close: () => pglite.disconnect() };+ }, 120_000);+ afterAll(async () => { await bare?.close(); });test('a closure only the nightly check dated reads as an upper bound; an explicit end on either side of it replaces it', () => brain(async b => {await b.put('companies/acme-example', '---\ntype: company\ntitle: Acme\n---\nA company.\n');@@ -42,17 +50,15 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {}), 120_000);test('the legacy engine copier refuses a brain whose page versions it would discard, and names how many', async () => {- let engine: BrainEngine; let close: () => Promise<void>;- if (engineCase.databaseUrl) ({ engine, close } = await isolatedPersistencePostgres(engineCase.databaseUrl));- else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; close = () => pglite.disconnect(); }- try {+ const { engine } = bare;+ {const side = { side: 'source' as const, from: engine.kind as 'pglite' | 'postgres', to: (engine.kind === 'pglite' ? 'postgres' : 'pglite') as 'pglite' | 'postgres' };await assertLegacyEngineMigration(engine, side);await engine.putPage('notes/history', { type: 'note', title: 'History', compiled_truth: 'first body' });for (let i = 0; i < 3; i++) await engine.createVersion('notes/history');await expect(assertLegacyEngineMigration(engine, side)).rejects.toMatchObject({code: 'writer_coordinator_required', reason: 'page_history', message: 'Engine migration would discard 3 page versions.' });- } finally { await close(); }+ }}, 120_000);test('since_supplied probe: a late-captured take keeps its valid time, and an update without since keeps the stored one', () => brain(async b => {diff --git a/test/belief-ledger-weekly-diff.test.ts b/test/belief-ledger-weekly-diff.test.tsindex 271ab0cf73..1ebabe0b40 100644--- a/test/belief-ledger-weekly-diff.test.ts+++ b/test/belief-ledger-weekly-diff.test.ts@@ -3,7 +3,9 @@* week" as a cited belief diff from the belief ledger: before, after, cause and an evidence pointer per belief, netted over* the window. Each cell runs on PGLite and on Postgres when DATABASE_URL is set; forced probes show the cell can fail.*/-import { describe, expect, test } from 'bun:test';+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 { testBackends } from './helpers/test-backends.ts';@@ -124,6 +126,38 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {expect(tight.budget_used).toBeLessThanOrEqual(200);const remote = await delta({ beliefs: true }, true);expect(remote.beliefs.changes).toHaveLength(3);+ // An empty window adds no section and leaves the wake's text as it was.+ const later = new Date(Date.now() + 60_000).toISOString();+ const quiet = [await delta({ since: later }), await delta({ since: later, beliefs: true })];+ expect(quiet[1]!.beliefs.changes).toEqual([]);+ expect(quiet[1]!.text).toBe(quiet[0]!.text);+ }), 120_000);++ test('gbrain beliefs changes prints the same diff for an entity and a --since window, and refuses a bad --since', () => brain(async b => {+ await b.put(slug, beliefPage({ facts: ['Acme sells widgets'] }));+ const t0 = await at(b);+ await b.put(slug, beliefPage({ facts: ['Acme sells gadgets'] }));+ await b.put('companies/widget-co', beliefPage({ facts: ['Widget Co makes widgets'] }));+ const t1 = await at(b);+ const logs: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });+ try {+ await runBeliefs(b.engine, ['changes', slug, '--since', t0, '--source', b.sourceId]);+ } finally { log.mockRestore(); }+ const expected = await changes(b, t0, t1, { entities: [slug] });+ const printed = logs.join('\n').split('\n');+ expect(printed[0]).toStartWith(`Belief changes on ${b.sourceId} from ${t0} to `);+ expect(printed.slice(1)).toEqual(expected.changes.map(renderBeliefChange));+ expect(printed.join('\n')).toContain('Acme sells gadgets');+ expect(printed.join('\n')).not.toContain('Widget Co');+ expect(beliefsChangesArgs(['changes', 'a', '--source', 's', 'b', '--since', '7d'], Date.parse('2026-10-08T00:00:00Z')))+ .toEqual({ entities: ['a', 'b'], since: '2026-10-01T00:00:00.000Z' });+ const err = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await runBeliefs(b.engine, ['changes', '--since', 'last tuesday', '--source', b.sourceId]);+ } finally { err.mockRestore(); }+ expect(currentExitCode()).toBe(2);+ setCliExitVerdict(0);}), 120_000);});}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex fab049ff7d..5b094411ca 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -26,6 +26,9 @@ test/belief-ledger-purge-review.test.tstest/belief-ledger-purge.test.tstest/belief-ledger-restore.test.tstest/belief-ledger-trust.test.ts+test/belief-ledger-w5-time-model.test.ts+test/belief-ledger-weekly-diff.test.ts+test/belief-ledger-weekly-probes.test.tstest/capture-consent-admission.test.tstest/capture-dispatch-provenance-6524.test.tstest/chronicle-backfill-max-usd.test.tsdiff --git a/test/thin-client-routing.test.ts b/test/thin-client-routing.test.tsindex b49cb7bf9d..ae2d1bb9b8 100644--- a/test/thin-client-routing.test.ts+++ b/test/thin-client-routing.test.ts@@ -201,6 +201,36 @@ describe('routeThinClientCommand — (a) op name + param mapping per route', ()});});+describe('routeThinClientCommand — beliefs changes runs through the host delta', () => {+ const window = { source_id: 'default', since: '2026-10-01T00:00:00.000Z', until: '2026-10-08T00:00:00.000Z', coverage_from: null, truncated: false,+ changes: [{ kind: 'fact', slug: 'companies/acme-example', change: 'added', subject: { claim: 'Acme sells gadgets' }, before: null, after: { fact: 'Acme sells gadgets' },+ before_known: true, cause: { event: 'fact.asserted', op: 'put_page' }, evidence: { event_id: 7, recorded_at: '2026-10-02T00:00:00.000Z', slug: 'companies/acme-example', row: 1 }, trust_tier: 'agent' }] };+ const reply = (body: unknown) => callSpy.mockImplementationOnce(async (_cfg: GBrainConfig, tool: string, args: Record<string, unknown> = {}) => {+ calls.push({ tool, args });+ return { content: [{ type: 'text', text: JSON.stringify(body) }] };+ });++ test('entities and --since map onto delta {since, beliefs, entities}; the text is the host renderer', async () => {+ reply({ pages: [], beliefs: window });+ expect(await routeThinClientCommand(cfg, 'beliefs', ['changes', 'companies/acme-example', 'people/alice-example', '--since', '2026-10-01'])).toBe(true);+ expect(soleCall()).toEqual({ tool: 'delta', args: { since: '2026-10-01T00:00:00.000Z', beliefs: true, entities: 'companies/acme-example,people/alice-example' } });+ expect(logs.join('\n')).toBe(['Belief changes on default from 2026-10-01T00:00:00.000Z to 2026-10-08T00:00:00.000Z: 1',+ '- [2026-10-02] fact on companies/acme-example: added "Acme sells gadgets" (put_page, event 7, row 1)'].join('\n'));+ });++ test('a host whose delta has no beliefs is reported, not printed as empty', async () => {+ reply({ pages: [] });+ const stderr: string[] = [];+ const write = spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { stderr.push(String(chunk)); return true; }) as never);+ try {+ expect(await routeThinClientCommand(cfg, 'beliefs', ['changes'])).toBe(true);+ } finally { write.mockRestore(); }+ expect(currentExitCode()).not.toBe(0);+ expect(stderr.join('')).toContain('Error [unavailable]: The remote brain\'s delta does not return belief changes');+ expect(logs).toEqual([]);+ });+});+describe('routeThinClientCommand — (b) host-bound forms return false', () => {const hostBound: Array<[string, string[]]> = [['search', ['modes', '--reset']],@@ -208,6 +238,8 @@ describe('routeThinClientCommand — (b) host-bound forms return false', () => {['quarantine', ['scan']],['quarantine', ['clear']],['takes', ['extract']],+ ['beliefs', ['changes', '--source', 'notes']],+ ['beliefs', ['status']],];for (const [command, args] of hostBound) {