Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

doctor: fence_integrity counts unrenderable_legacy_facts from the planner, next: report (#6278 C5, 2.3)

garrytan9aff4e7026e6
diff --git a/src/commands/doctor/checks/fence-integrity.ts b/src/commands/doctor/checks/fence-integrity.ts
index a687656bab..59d30910b3 100644
--- a/src/commands/doctor/checks/fence-integrity.ts
+++ b/src/commands/doctor/checks/fence-integrity.ts
@@ -17,10 +17,19 @@
* model-tier fences wait when `fences.repair.llm` is off or today's budget is
* spent. Output is location only: slugs, paths, fences, rows, reasons and
* tiers, never a cell value.
+ *
+ * #6278: the check also counts `unrenderable_legacy_facts`, the active
+ * `row_num IS NULL` fact rows the fence step leaves unadopted because the
+ * fence codec would change their text (or their page already carries the
+ * claim), from the planner's read-only result: pages, fact ids and reason
+ * classes, never the claim. Those rows stay active and searchable and
+ * nothing is lost, so the finding has no command (`next: report`) and never
+ * suggests `forget_fact`; its verify re-counts the rows.
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
-import { agentFix } from '../check-fix.ts';
+import { agentFix, doctorVerify } from '../check-fix.ts';
+import { auditUnadoptableFacts, planUnfencedFacts, type UnadoptableFactRecord } from '../../../core/facts/unfenced-facts.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { runFenceCensus, summarizeFenceCensus, type SourceCensus, type TierCounts } from '../../../core/fence-repair/census.ts';
import { readTrend, type TrendEntry } from '../../../core/fence-repair/census-store.ts';
@@ -38,6 +47,7 @@ import { dailyLedger, FENCE_REPAIR_LEDGER } from '../../../core/budget/daily-led
export const FENCE_NORMALIZATION_WARN_7D = 20;
const TREND_DAYS = 7;
const DOCS = 'docs/guides/write-refusals.md#invalid_fence';
+const UNRENDERABLE_DOCS = 'docs/guides/write-refusals.md#fence_unrenderable';
/** `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s): the wall-clock bound of one census scan. */
export function fenceScanTimeoutMs(): number {
@@ -94,6 +104,34 @@ function modelRepairSentence(caps: { perPageUsd: number; perDayUsd: number }, to
return `Model repair caps: $${caps.perPageUsd.toFixed(2)} per page, $${caps.perDayUsd.toFixed(2)} per day${today ? ` ($${today.committedUsd.toFixed(2)} spent today)` : ''}.`;
}
+interface UnrenderablePage { source_id: string; slug: string; rows: Array<{ fact_id: number; reason: UnadoptableFactRecord['reason']; class: UnadoptableFactRecord['class'] }> }
+interface UnrenderableLegacyFacts { total: number; complete: boolean; pages: UnrenderablePage[] }
+
+/** Legacy rows the fence step would leave unadopted, planned read-only per source within `deadline`; location only. */
+async function unrenderableLegacyFacts(engine: BrainEngine, sourceIds: string[] | undefined, deadline: number): Promise<UnrenderableLegacyFacts> {
+ const byPage = new Map<string, UnrenderablePage>();
+ let complete = true;
+ for (const sourceId of sourceIds ?? [undefined]) {
+ const audit = await auditUnadoptableFacts(engine, await planUnfencedFacts(engine, sourceId === undefined ? {} : { sourceId }), { deadline });
+ complete &&= audit.complete;
+ for (const record of audit.records) {
+ const key = `${record.source_id}\0${record.slug}`;
+ const page = byPage.get(key) ?? byPage.set(key, { source_id: record.source_id, slug: record.slug, rows: [] }).get(key)!;
+ page.rows.push({ fact_id: record.fact_id, reason: record.reason, class: record.class });
+ }
+ }
+ const pages = [...byPage.values()];
+ return { total: pages.reduce((sum, page) => sum + page.rows.length, 0), complete, pages };
+}
+
+function unrenderableSentence(found: UnrenderableLegacyFacts): string {
+ const pages = found.pages.slice(0, 5).map(page => `${page.slug} (${page.source_id}): ${[...new Set(page.rows.map(row => row.class))].sort().join(', ')}`).join('; ');
+ return `${found.total} legacy fact row(s) on ${found.pages.length} page(s) cannot be adopted into their facts fence: ${pages}${found.pages.length > 5 ? '; …' : ''}. `
+ + 'They stay active and searchable and nothing is lost: the fence codec would change their text (or the page already carries the claim), so gbrain leaves them as legacy rows '
+ + 'and those pages skip destructive fact reconciliation. There is no safe automatic fix; report the pages and reason classes with the gbrain version. Do not forget or expire a row to clear this count.'
+ + (found.complete ? '' : ' The scan did not finish within its time budget, so more rows may be affected; run gbrain doctor --only fence_integrity again.');
+}
+
/** The check's verdict after a bounded census scan (`sourceIds`: only those sources, for a scoped remote caller). */
export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutMs?: number; now?: () => Date; sourceIds?: string[] } = {}): Promise<Omit<Check, 'name'>> {
const now = opts.now ?? (() => new Date());
@@ -111,14 +149,17 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM
const total = waiting.reduce((sum, c) => sum + c.total, 0);
// T2: legacy fence repairs written and imported but not committed yet (counts for a scoped remote caller, paths locally).
const uncommitted = await readUncommittedFenceRepairs(engine, opts.sourceIds ?? census.map(c => c.source_id)).catch(() => []);
+ // The audit's deadline is on the wall clock (it bounds real work; the census's `now` is for dates).
+ const unrenderable = await unrenderableLegacyFacts(engine, opts.sourceIds, Date.now() + timeoutMs).catch((): UnrenderableLegacyFacts => ({ total: 0, complete: false, pages: [] }));
const details = {
total, partial: partial.length > 0, partial_sources: partial.map(c => c.source_id), sources: census, trend, warn_at_normalized_7d: FENCE_NORMALIZATION_WARN_7D,
model_repair: { max_usd_per_page: caps.perPageUsd, max_usd_per_day: caps.perDayUsd, spent_today_usd: today?.committedUsd ?? null, reserved_today_usd: today?.reservedUsd ?? null },
timeout_ms: timeoutMs, docs: DOCS,
uncommitted_repairs: uncommitted.length,
...(uncommitted.length && !opts.sourceIds ? { uncommitted: uncommitted.map(n => ({ source_id: n.source_id, path: n.path, commit_step: n.commit_step })) } : {}),
+ unrenderable_legacy_facts: unrenderable,
};
- if (!total && !partial.length && !noisy.length && !uncommitted.length) {
+ if (!total && !partial.length && !noisy.length && !uncommitted.length && !unrenderable.total && unrenderable.complete) {
return { status: 'ok', details, message: census.length ? `No malformed facts or takes fence is held, stored or waiting in a checkout (${census.length} source(s) scanned).` : 'No sources to scan.' };
}
const auto = await readFenceAutoRepair(engine, now());
@@ -146,13 +187,18 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM
sentences.push(`PARTIAL CENSUS: the scan of ${partial.map(c => c.source_id).join(', ')} did not finish within ${timeoutMs / 1000}s, so more fences may be malformed; `
+ 'run gbrain doctor --only fence_integrity again to resume it (raise GBRAIN_DOCTOR_FENCE_TIMEOUT_MS for a larger share per run).');
}
+ if (unrenderable.total || !unrenderable.complete) sentences.push(unrenderable.total ? unrenderableSentence(unrenderable)
+ : 'The scan for legacy fact rows the fence cannot render did not finish within its time budget; run gbrain doctor --only fence_integrity again.');
const first = waiting[0];
const fix = first ? sourceFix(first, auto)
- : partial.length ? agentFix(['gbrain', 'doctor', '--only', 'fence_integrity', '--json'], 'Resumes the fence census where the last scan stopped and reports what it found.', 'fence_integrity', { docs: DOCS })
+ : partial.length || (!unrenderable.total && !unrenderable.complete) ? agentFix(['gbrain', 'doctor', '--only', 'fence_integrity', '--json'], 'Resumes the fence census where the last scan stopped and reports what it found.', 'fence_integrity', { docs: DOCS })
: noisy.length ? agentFix(['gbrain', 'sources', 'status', noisy[0]!.source_id, '--json'], `Shows ${noisy[0]!.source_id}'s recent sync result, including fences_normalized with sample paths, so you can find what writes the malformed fences.`,
'fence_integrity', { docs: DOCS })
- : agentFix(['gbrain', 'sources', 'status', uncommitted[0]!.source_id], 'Lists the uncommitted fence repairs of this legacy source with the exact git add and git commit step for each file.',
- 'fence_integrity', { docs: DOCS });
+ : uncommitted.length ? agentFix(['gbrain', 'sources', 'status', uncommitted[0]!.source_id], 'Lists the uncommitted fence repairs of this legacy source with the exact git add and git commit step for each file.',
+ 'fence_integrity', { docs: DOCS })
+ // No command to run: the rows stay as they are, so the fix is a report; verify re-counts them.
+ : { consent: [], actor: 'agent' as const, requires_exclusive: false, docs: UNRENDERABLE_DOCS, verify: doctorVerify('fence_integrity'),
+ why: `Nothing to run: ${unrenderable.total} legacy fact row(s) stay active and searchable because their text cannot be written into a facts fence unchanged. Tell the user which pages are listed under unrenderable_legacy_facts and report them with the gbrain version; the verify re-counts the rows.` };
return { status: 'warn', details: { ...details, auto_repair: auto }, fix, message: sentences.join(' ') };
}
diff --git a/test/doctor-fence-integrity.test.ts b/test/doctor-fence-integrity.test.ts
index 48b4078def..cdafd31e2e 100644
--- a/test/doctor-fence-integrity.test.ts
+++ b/test/doctor-fence-integrity.test.ts
@@ -17,6 +17,15 @@
* step, "no action needed" appears with no maintenance run, or a cell value
* reaches the check.
* PGLite in-memory ($0); synthetic content only.
+ *
+ * #6278 (2.3): legacy fact rows the fence step cannot adopt are counted under
+ * `unrenderable_legacy_facts` from the planner's read-only result (pages,
+ * fact ids and reason classes, never the claim), the message says the rows
+ * stay active and searchable and nothing is lost and never suggests
+ * forgetting them, the fix has no command (`next: report`) and its verify
+ * re-counts the rows; a brain with none stays ok. Fails when: the count
+ * comes from a receipt (none exists for a row never submitted), the claim
+ * text reaches the output, or the fix tells the agent to run something.
*/
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
@@ -35,6 +44,7 @@ import { bannerFindingLine } from '../src/commands/doctor/upgrade-banner.ts';
import { repairForCheck } from '../src/core/repair/registry.ts';
import { LAST_GLOBAL_MAINTENANCE_KEY } from '../src/core/fence-repair/hold-fix.ts';
import { LAST_GLOBAL_AT_KEY } from '../src/core/cycle.ts';
+import { cliRenderContext, renderAction } from '../src/core/agent-output.ts';
const T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';
const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';
@@ -188,6 +198,41 @@ describe('fence_integrity doctor check', () => {
for (const blob of [line, JSON.stringify(check)]) for (const secret of SECRETS) expect(blob).not.toContain(secret);
});
+ test('legacy fact rows the fence codec cannot render are counted by page and class with next: report, never the claim (#6278)', async () => {
+ const s = await source({ 'people/alice-example.md': md('Alice Example', CLEAN) });
+ const page = await stored(s.id, 'people/alice-example', CLEAN);
+ await engine.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', ['people/alice-example.md', page.id]);
+ const STRUCK = '~~Sentinelstruckzq6 left the board~~', TRAILING = 'Sentineltrailingzq6 keeps bees ';
+ const insert = (fact: string) => engine.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)
+ VALUES ($1, 'people/alice-example', $2, 'fact', 'world', 'medium', '2026-03-01', 'mcp:remember', 0.8) RETURNING id`, [s.id, fact]);
+ const [[struck], [blank], [trailing]] = [await insert(STRUCK), await insert(' '), await insert(TRAILING)];
+ const check = await result();
+ expect(check.status).toBe('warn');
+ const found = (check.details as any).unrenderable_legacy_facts;
+ // The trailing-whitespace row is adoptable (not counted); the struck and blank rows are not.
+ expect(found).toEqual({ total: 2, complete: true, pages: [{ source_id: s.id, slug: 'people/alice-example', rows: [
+ { fact_id: Number(struck.id), reason: 'fence_unrenderable', class: 'struck' },
+ { fact_id: Number(blank.id), reason: 'fence_unrenderable', class: 'empty' }] }] });
+ expect(check.message).toContain('2 legacy fact row(s) on 1 page(s) cannot be adopted into their facts fence: people/alice-example');
+ expect(check.message).toContain('empty, struck');
+ expect(check.message).toContain('stay active and searchable and nothing is lost');
+ expect(check.message).not.toContain('forget_fact');
+ const rendered = renderAction(check.fix!, cliRenderContext());
+ expect(rendered.next).toBe('report');
+ expect(rendered.command).toBeUndefined();
+ expect(rendered.verify).toEqual({ argv: ['gbrain', 'doctor', '--only', 'fence_integrity', '--json'] });
+ expect(rendered.docs).toContain('write-refusals.md#fence_unrenderable');
+ const text = JSON.stringify(check);
+ for (const leak of ['Sentinelstruckzq6', 'Sentineltrailingzq6', 'left the board', 'keeps bees', ...SECRETS]) expect(text).not.toContain(leak);
+ // Nothing was written: the rows are exactly as inserted.
+ const rows = await engine.executeRaw<{ id: number; fact: string; row_num: number | null; expired: boolean }>(
+ 'SELECT id, fact, row_num, expired_at IS NOT NULL AS expired FROM facts WHERE id = ANY($1::integer[]) ORDER BY id', [[struck.id, blank.id, trailing.id]]);
+ expect(rows.map(r => [r.fact, r.row_num, r.expired])).toEqual([[STRUCK, null, false], [' ', null, false], [TRAILING, null, false]]);
+ await engine.executeRaw('DELETE FROM facts WHERE source_id = $1', [s.id]);
+ expect((await result()).status).toBe('ok');
+ });
+
test('a census the scan did not finish is partial and never ok, even with nothing found so far', async () => {
const s = await source({ 'notes/clean.md': md('Clean', CLEAN) });
await stored(s.id, 'notes/clean', CLEAN);