Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger: doctor coverage test with forced probe, doctor goldens, managed mode via readManagedMode, coverage.ts leaves the test-only list

garrytan55264b82e06c
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index f0f1485253..8bf2eb5d41 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/coverage.ts', reason: 'held: W1 belief ledger (#6806) lane C wires it into `gbrain beliefs enable|disable`; remove this entry in that commit' },
{ 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' },
diff --git a/src/commands/beliefs.ts b/src/commands/beliefs.ts
index efbe2c0a0e..7ed0736ea0 100644
--- a/src/commands/beliefs.ts
+++ b/src/commands/beliefs.ts
@@ -15,6 +15,7 @@ import { disableBeliefLedger, enableBeliefLedger } from '../core/belief/coverage
import { coverageIntervals, coveredSources, fillCommitMarks, orphanLifetimes, reconcileBeliefDrift, unmarkedPublications, type CoverageInterval } from '../core/belief/coverage-report.ts';
import { backfillBeliefHistory } from '../core/belief/backfill.ts';
import { readLedgerSource } from '../core/belief/ledger.ts';
+import { readManagedMode } from '../core/persistence/managed-mode.ts';
export const BELIEFS_USAGE = [
'Usage: gbrain beliefs <enable|disable|status|reconcile|backfill> [--source <id>] [--json]',
@@ -42,7 +43,7 @@ async function sourceStatus(engine: BrainEngine, sourceId: string) {
const source = await readLedgerSource(engine, sourceId);
if (!source) throw unknownSource(sourceId);
const intervals = await coverageIntervals(engine, sourceId);
- return { source_id: sourceId, managed: source.managed, active: source.coverage != null && source.coverage !== 'coverage.stopped', intervals,
+ return { source_id: sourceId, managed: await readManagedMode(engine), active: source.coverage != null && source.coverage !== 'coverage.stopped', intervals,
unmarked_publications: (await unmarkedPublications(engine, sourceId)).length, orphans: await orphanLifetimes(engine, sourceId, 5) };
}
diff --git a/test/belief-ledger-coverage.test.ts b/test/belief-ledger-coverage.test.ts
index 424343665e..4d3df3129b 100644
--- a/test/belief-ledger-coverage.test.ts
+++ b/test/belief-ledger-coverage.test.ts
@@ -9,7 +9,7 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { rmSync } from 'node:fs';
import { join } from 'node:path';
-import { __setBeliefEmitterFaultForTests, markBeliefCommits, type BeliefEventDraft } from '../src/core/belief/append.ts';
+import { __setBeliefEmitterFaultForTests, appendBeliefEvents, markBeliefCommits, type BeliefEventDraft } from '../src/core/belief/append.ts';
import { currentStateHash, readLedgerSource, withBeliefBatch } from '../src/core/belief/ledger.ts';
import { deleteSourceRow } from '../src/core/source-delete.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
@@ -27,6 +27,10 @@ import { assertLegacyEngineMigration } from '../src/core/persistence/maintenance
import { copiedEntries, copyAll, digestMismatches } from './helpers/graduation-copy-harness.ts';
import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
import { testBackends } from './helpers/test-backends.ts';
+import { beliefLedgerEntry } from '../src/commands/doctor/checks/belief-ledger.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { COVERAGE_KEY } from '../src/core/belief/keys.ts';
import { beliefBrain, beliefEngineCase, beliefPage, shape, type BeliefBrain } from './helpers/belief-ledger.ts';
afterEach(() => { __setBeliefEmitterFaultForTests(null); });
@@ -38,6 +42,18 @@ const fault = (f: (drafts: BeliefEventDraft[]) => BeliefEventDraft[]) => __setBe
const dbNow = async (b: BeliefBrain) => new Date(new Date((await b.engine.executeRaw<{ t: string }>(`SELECT date_trunc('milliseconds', clock_timestamp()) + interval '1 millisecond' AS t`))[0]!.t).getTime()).toISOString();
const pause = () => new Promise(resolve => setTimeout(resolve, 20));
+async function doctor(b: BeliefBrain, opts: Partial<DoctorContext> = {}): Promise<Check> {
+ const [check] = await beliefLedgerEntry.run({ engine: b.engine, tier: 'standard', doFix: false, dryRun: false, orphanRatioSourceId: b.sourceId, ...opts } as DoctorContext) as Check[];
+ expect(check!.name).toBe('belief_ledger_coverage');
+ return check!;
+}
+
+async function bypassLink(b: BeliefBrain, target: string) {
+ await b.engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source, context, origin_page_id)
+ SELECT a.id, p.id, 'mentions', 'markdown', 'bypass', a.id FROM pages a, pages p
+ WHERE a.source_id = $1 AND a.slug = 'companies/acme-example' AND p.source_id = $1 AND p.slug = $2`, [b.sourceId, target]);
+}
+
async function seeded(b: BeliefBrain) {
await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));
await b.put('companies/acme-example', page());
@@ -329,6 +345,53 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
}, { managed: false });
}, 120_000);
+ test('doctor belief_ledger_coverage: off is information with an ask_user enable; a drift warns, --fix reconciles it, a partial purge replay asks the user', async () => {
+ await brain(async b => {
+ await seeded(b);
+ for (const slug of ['people/bob-example', 'people/carol-example']) await b.put(slug, beliefPage({ type: 'person', title: slug }));
+ const off = await doctor(b);
+ expect(off).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice',
+ fix: { argv: ['gbrain', 'beliefs', 'enable', '--source', b.sourceId], ask_user: true } });
+ await b.enable();
+ const clean = await doctor(b, { tier: 'deep' });
+ expect(clean.status).toBe('ok');
+ expect(clean.message).toContain(`${b.sourceId}: recording since`);
+ expect(clean.details!.sources).toMatchObject([{ source_id: b.sourceId, certified: true, drift: { count: 0, exact: true } }]);
+ await bypassLink(b, 'people/bob-example');
+ const drifted = await doctor(b);
+ expect(drifted).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'beliefs', 'reconcile', '--source', b.sourceId, '--json'], actor: 'agent' } });
+ expect(drifted.message).toContain(`${b.sourceId}: 1 drifted slug(s) (e.g. companies/acme-example)`);
+ const before = await b.lastId();
+ const fixed = await doctor(b, { doFix: true });
+ expect(fixed.status).toBe('ok');
+ expect(fixed.message).toContain('1 drift mark(s)');
+ expect(shape(await b.events(before)).sort()).toEqual(['fact:reconcile', 'fact:reconcile', 'link:reconcile', 'link:reconcile', 'page:reconcile', 'take:reconcile', 'take:reconcile']);
+ // Forced probe: an emitter that drops every reconcile event leaves the drift in place, so --fix still warns.
+ fault(drafts => drafts.filter(d => d.eventType !== 'reconcile'));
+ await bypassLink(b, 'people/carol-example');
+ const unfixed = await doctor(b, { doFix: true });
+ expect(unfixed.status).toBe('warn');
+ expect(unfixed.message).toContain(`${b.sourceId}: 1 drifted slug(s)`);
+ __setBeliefEmitterFaultForTests(null);
+ expect((await doctor(b, { doFix: true })).status).toBe('ok');
+ const source = (await readLedgerSource(b.engine, b.sourceId))!;
+ const restore = async (purgeReplay: string) => {
+ const publicationId = randomUUID();
+ await b.engine.transaction(tx => appendBeliefEvents(tx, [{ sourceId: b.sourceId, incarnation: source.incarnation, lifetime: null, slug: '', subjectKind: 'coverage',
+ subjectKey: COVERAGE_KEY, eventType: 'coverage.restored', trustTier: 'unknown', tierBasis: 'unknown', visibility: 'world', value: null, stateHash: '',
+ cause: { op: 'coverage.restored', archive_created_at: '2026-10-01T00:00:00.000Z', purge_replay: purgeReplay, purge_requests: ['purge-1'] } }],
+ { publicationId, origin: 'live', purgesPossible: false }));
+ await markBeliefCommits(b.engine, [publicationId]);
+ };
+ await restore('complete');
+ expect((await doctor(b)).status).toBe('ok');
+ await restore('partial');
+ const asked = await doctor(b);
+ expect(asked).toMatchObject({ status: 'warn', fix: { actor: 'user', ask_user: true } });
+ expect(asked.message).toContain('purge replay partial for purge-1');
+ }, { enable: false });
+ }, 180_000);
+
test('probe 9: graduation PGLite -> ' + engineCase.name + ' carries an identical ledger: equal event_key sets, digests and replay', async () => {
await beliefBrain(async b => {
await seeded(b);
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 94280e86a7..8bb065b4eb 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -181,6 +181,7 @@
" [OK] planner_stats_stale: Planner statistics are fresh on 6 hot tables.",
" [OK] retrieval_feedback_health: Retrieval feedback is off; rankings do not learn from ratings. Turn it on with: gbrain config set feedback.enabled true",
" [OK] revision_backfill: Every page has its revision; the page revision backfill is complete.",
+ " [INFO] belief_ledger_coverage: The belief ledger is off: no source records what this brain had recorded, and when.",
" [OK] trust_tiers: 0% of 13 row(s) have an unverified origin (unknown tier); the backfill has classified every row it has a signal for.",
" [OK] trust_scan: Every agent-written or lower row has been scanned by the current write-gate detector; flagged rows carry their flag, and proactive surfaces withhold them when trust.agent_activation is suppress.",
" [OK] trust_sources_unclaimed: No unclaimed source holds rows from before trust tiers.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 7ed7eb1c2f..60bf7e6dc9 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -2501,6 +2501,45 @@
"name": "revision_backfill",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "beliefs",
+ "enable",
+ "--source",
+ "default",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain beliefs enable --source default --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/designs/BELIEF_LEDGER.md#73-the-doctor-coverage-check",
+ "next": "ask_user",
+ "requires_exclusive": false,
+ "user_message": "Do you want gbrain to keep a belief ledger (a recorded history of facts, takes and links) for this source?",
+ "verify": {
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "belief_ledger_coverage",
+ "--json",
+ "--brain",
+ "host"
+ ]
+ },
+ "why": "Enabling baselines every page of the source and records each later change; only a managed source is certified."
+ },
+ "message": "The belief ledger is off: no source records what this brain had recorded, and when.",
+ "name": "belief_ledger_coverage",
+ "readiness_state": "disabled_by_choice",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index e3e6519fed..e82a129a8f 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -2326,6 +2326,45 @@
"name": "revision_backfill",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "beliefs",
+ "enable",
+ "--source",
+ "default",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain beliefs enable --source default --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/designs/BELIEF_LEDGER.md#73-the-doctor-coverage-check",
+ "next": "ask_user",
+ "requires_exclusive": false,
+ "user_message": "Do you want gbrain to keep a belief ledger (a recorded history of facts, takes and links) for this source?",
+ "verify": {
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "belief_ledger_coverage",
+ "--json",
+ "--brain",
+ "host"
+ ]
+ },
+ "why": "Enabling baselines every page of the source and records each later change; only a managed source is certified."
+ },
+ "message": "The belief ledger is off: no source records what this brain had recorded, and when.",
+ "name": "belief_ledger_coverage",
+ "readiness_state": "disabled_by_choice",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index b75bdc84c9..665e0d29ea 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -2371,6 +2371,45 @@
"name": "revision_backfill",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "beliefs",
+ "enable",
+ "--source",
+ "default",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain beliefs enable --source default --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/designs/BELIEF_LEDGER.md#73-the-doctor-coverage-check",
+ "next": "ask_user",
+ "requires_exclusive": false,
+ "user_message": "Do you want gbrain to keep a belief ledger (a recorded history of facts, takes and links) for this source?",
+ "verify": {
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "belief_ledger_coverage",
+ "--json",
+ "--brain",
+ "host"
+ ]
+ },
+ "why": "Enabling baselines every page of the source and records each later change; only a managed source is certified."
+ },
+ "message": "The belief ledger is off: no source records what this brain had recorded, and when.",
+ "name": "belief_ledger_coverage",
+ "readiness_state": "disabled_by_choice",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index b21bd79830..363c03c1b3 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -2367,6 +2367,45 @@
"name": "revision_backfill",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "beliefs",
+ "enable",
+ "--source",
+ "default",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain beliefs enable --source default --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/designs/BELIEF_LEDGER.md#73-the-doctor-coverage-check",
+ "next": "ask_user",
+ "requires_exclusive": false,
+ "user_message": "Do you want gbrain to keep a belief ledger (a recorded history of facts, takes and links) for this source?",
+ "verify": {
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "belief_ledger_coverage",
+ "--json",
+ "--brain",
+ "host"
+ ]
+ },
+ "why": "Enabling baselines every page of the source and records each later change; only a managed source is certified."
+ },
+ "message": "The belief ledger is off: no source records what this brain had recorded, and when.",
+ "name": "belief_ledger_coverage",
+ "readiness_state": "disabled_by_choice",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index f3fc37b7ba..3afc56e495 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -773,6 +773,10 @@
"category": "meta",
"name": "revision_backfill"
},
+ {
+ "category": "brain",
+ "name": "belief_ledger_coverage"
+ },
{
"category": "brain",
"name": "trust_tiers"