Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(repair): the fences kind end to end and the Tier 3 call; prefer moving a misaligned cell over a rule on its own column in gate (f) (#6188)

garrytan033b712744d1
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 0d35bb2026..6ff0df6e9a 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -18,6 +18,7 @@ import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { clearHealthMemo } from '../core/health-memo.ts';
import { OperationError, opError } from '../core/ops/contract.ts';
import { readFix } from '../core/ops/op-fix.ts';
+import { shellQuote } from '../core/agent-output.ts';
import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult } from '../core/repair/core.ts';
import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';
import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, LLM_REPAIR_REGISTRY, PREVIEW_BOUND_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMayEmbed, repairMaySpend,
@@ -197,7 +198,13 @@ function human(result: RepairResult, opts: { diff: boolean } = { diff: false }):
for (const c of result.capacity) lines.push(` capacity ${c.scope} ${c.resource}: ${c.used} of ${c.limit} (stops at ${c.stop_at})`);
if (result.resumed_from) lines.push(` resuming after item ${result.resumed_from.phase}:${result.resumed_from.id}`);
if (result.mode === 'apply') lines.push(` applied ${result.applied}, skipped ${result.skipped}${result.complete ? ', complete' : ''}`);
+ if (result.mode === 'apply' && result.repaired !== undefined) {
+ const left = Object.entries(result.remaining ?? {}).map(([k, v]) => `${k}=${v}`).join(', ');
+ lines.push(` repaired ${result.repaired}; ${left ? `still waiting: ${left}` : 'nothing left in this selection'}`);
+ }
+ if (result.scan?.partial) lines.push(' scan: partial (the census did not finish within its bound; more candidates may exist, rerun to resume it)');
if (result.stopped) lines.push(` STOPPED: ${result.stopped.message}`);
+ if (result.stopped?.fix?.argv) lines.push(` fix: ${shellQuote(result.stopped.fix.argv)}${result.stopped.fix.consent.length ? ` (asks the user first: ${result.stopped.fix.consent.join(', ')})` : ''}`);
for (const entry of result.listing ?? []) lines.push(` ${entry.class}: ${entry.item}${entry.detail ? ` (${entry.detail})` : ''}`);
const render = repairSpec(result.kind).handler.render;
if (result.details && render) lines.push(...render(result.details, opts));
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 56a268a33d..dccc4b6d46 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1248,6 +1248,13 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
const backlog = new Map((await drainMod.readManagedSyncBacklog(engine).catch(() => [])).map(b => [b.source_id, b]));
const sharedSkillsView = await import('../core/shared-skills/source-opt-out.ts');
const sharedSkills = new Map(await Promise.all(sources.map(async source => [source.id, await sharedSkillsView.readSharedSkillsSourceView(engine, source.id).catch(() => null)] as const)));
+ // #6188 (T2): legacy fence repairs written to disk but not committed yet, with the exact commit step.
+ const { readUncommittedFenceRepairs } = await import('../core/fence-repair/uncommitted.ts');
+ const uncommitted = new Map<string, Array<{ path: string; repaired_at: string; backup: string | null; commit_step: string; classes: string[] }>>();
+ for (const notice of await readUncommittedFenceRepairs(engine, sources.map(source => source.id)).catch(() => [])) {
+ uncommitted.set(notice.source_id, [...(uncommitted.get(notice.source_id) ?? []),
+ { path: notice.path, repaired_at: notice.repaired_at, backup: notice.backup, commit_step: notice.commit_step, classes: notice.receipt.classes }]);
+ }
if (json) {
const enriched = metrics.map((m) => ({
...m,
@@ -1258,6 +1265,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
...(backlog.get(m.source_id) ? { managed_backlog: backlog.get(m.source_id) } : {}),
...(gitHolds.get(m.source_id) ? { git_holds: gitHolds.get(m.source_id) } : {}),
...(sharedSkills.get(m.source_id) ? { shared_skills: sharedSkills.get(m.source_id) } : {}),
+ ...(uncommitted.get(m.source_id) ? { fence_repairs_uncommitted: uncommitted.get(m.source_id) } : {}),
}));
console.log(JSON.stringify({ schema_version: 1, sources: enriched }, null, 2));
return;
@@ -1298,6 +1306,10 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
for (const [sourceId, status] of connectors) for (const line of statusView.connectorStatusLines(sourceId, status)) console.log(line);
for (const [sourceId, status] of gitHolds) for (const line of statusView.gitHoldStatusLines(sourceId, status)) console.log(line);
for (const b of backlog.values()) console.log(` ${drainMod.formatManagedSyncBacklog(b)}`);
+ for (const [sourceId, notices] of uncommitted) {
+ console.log(` ${sourceId}: ${notices.length} uncommitted fence repair(s); gbrain rewrote and imported them (backups kept), commit each when you are ready:`);
+ for (const notice of notices) console.log(` ${notice.path} (${notice.classes.join(', ')}): ${notice.commit_step}`);
+ }
for (const view of sharedSkills.values()) if (view && (only || view.configured === false || view.parked)) for (const line of sharedSkillsView.sharedSkillsStatusLines(view)) console.log(` ${line}`);
for (const m of metrics) {
const warns: string[] = [];
diff --git a/src/core/fence-repair/validate-cells.ts b/src/core/fence-repair/validate-cells.ts
index 541cfca17b..0c3f797977 100644
--- a/src/core/fence-repair/validate-cells.ts
+++ b/src/core/fence-repair/validate-cells.ts
@@ -95,6 +95,10 @@ function cellOk(check: RowCheck, column: string, text: string): boolean {
const own = check.byColumn.get(column);
if (check.aligned && own && !own.movable && own.text !== text) return ruleChange(check, column, own, text);
if (own && !own.used && own.text === text) return use(own);
+ // A misaligned row realigns by moving text unchanged; prefer that over a rule rewriting this column's own cell,
+ // or an empty kind cell (kind_map reads it as `fact`) would claim the column and strand the real `fact` cell.
+ const exact = check.aligned ? undefined : check.sources.find(s => !s.used && s.movable && s !== own && s.text === text);
+ if (exact) return use(exact);
if (own && !own.used && ruleChange(check, column, own, text)) return true;
const moved = check.sources.find(s => !s.used && s.movable && s !== own
&& (s.text === text || (!check.aligned && check.named(column) && ruleFits(check, column, s, text))));
diff --git a/src/core/repair/fences.ts b/src/core/repair/fences.ts
index 3af8281a13..e9e86bff22 100644
--- a/src/core/repair/fences.ts
+++ b/src/core/repair/fences.ts
@@ -44,7 +44,7 @@ import { pricingSetCommand } from '../budget/no-pricing.ts';
import type { CapSource } from '../consent.ts';
import { sha256 } from '../persistence/digest.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
-import { recordFenceHoldRepair } from '../persistence/sync-holds.ts';
+import { readGitSourceHolds, recordFenceHoldRepair } from '../persistence/sync-holds.ts';
import { attemptStore } from '../fence-repair/attempts.ts';
import { listFenceCandidates, runFenceCensus, type FenceCandidate } from '../fence-repair/census.ts';
import { fenceRepairLlmEnabled, readFenceRepairCaps } from '../fence-repair/config.ts';
@@ -482,7 +482,22 @@ async function tier3(ctx: OperationContext, src: FenceSource, target: FenceTarge
}
/** Verification and the summary counts: what this run repaired by tier, what is left by reason, and the oldest hold. */
-async function reportFences(ctx: OperationContext, scope: RepairScope, result: RepairResult, _opts: RepairPlanOptions) {
+/** Candidates of the selection this run did not touch, by the reason they are held (the last repair's, else the census's). */
+async function heldInScope(engine: BrainEngine, scope: RepairScope, opts: RepairPlanOptions, result: RepairResult): Promise<Record<string, number>> {
+ const selection: Selection = { source_ids: scope.source_ids, only: opts.only ?? [], skip: opts.skip ?? [], slugs: opts.slugs ?? [], no_llm: opts.noLlm === true };
+ const touched = new Set((result.outcome_items ?? []).map(outcome => outcome.item));
+ const holds = new Map((await readGitSourceHolds(engine, { sourceIds: scope.source_ids })).flatMap(source => source.holds.map(hold => [`${hold.source_id}:${hold.path}`, hold] as const)));
+ const out: Record<string, number> = {};
+ for (const cand of await listFenceCandidates(engine, scope.source_ids)) {
+ if (!selected(cand, selection) || touched.has(`${cand.source_id}:${cand.key}`)) continue;
+ const hold = cand.path ? holds.get(`${cand.source_id}:${cand.path}`) : undefined;
+ const reason = hold?.meta.fence_repair?.reason ?? cand.reasons[0] ?? 'unparseable';
+ out[reason] = (out[reason] ?? 0) + 1;
+ }
+ return out;
+}
+
+async function reportFences(ctx: OperationContext, scope: RepairScope, result: RepairResult, opts: RepairPlanOptions) {
const repairedByTier: Record<RepairTier, number> = { deterministic: 0, resolver: 0, llm: 0 };
const remaining: Record<string, number> = {};
for (const [reason, count] of Object.entries(result.residuals)) if (reason !== 'already_clean') remaining[reason] = (remaining[reason] ?? 0) + count;
@@ -494,6 +509,8 @@ async function reportFences(ctx: OperationContext, scope: RepairScope, result: R
}
const unattempted = result.affected - result.applied - result.skipped;
if (unattempted > 0 && result.stopped) remaining[result.stopped.reason] = (remaining[result.stopped.reason] ?? 0) + unattempted;
+ // An --expect apply replays the approved set only; re-check the selection for what the preview listed as held.
+ if (opts.expect) for (const [reason, count] of Object.entries(await heldInScope(ctx.engine, scope, opts, result))) remaining[reason] = (remaining[reason] ?? 0) + count;
} else if (result.affected) remaining.pending_repair = result.affected;
const [oldest] = await ctx.engine.executeRaw<{ held_at: string | null }>(`SELECT min(completed_keys->0->>'held_at') AS held_at FROM op_checkpoints
WHERE op='sync-hold' AND completed_keys->0->>'code'='invalid_fence' AND completed_keys->0->>'source_id'=ANY($1::text[])`, [scope.source_ids]).catch(() => [{ held_at: null }]);
diff --git a/test/fence-repair-llm.test.ts b/test/fence-repair-llm.test.ts
new file mode 100644
index 0000000000..1662be12c4
--- /dev/null
+++ b/test/fence-repair-llm.test.ts
@@ -0,0 +1,157 @@
+/**
+ * #6188 PR4: Tier 3 fence repair, the model call (src/core/fence-repair/llm.ts).
+ *
+ * Protects: the model sees only the fence header and the residual rows a
+ * row-level issue names (never the valid rows, never the rest of the page),
+ * no tools and no fallback model; every failure class is distinct
+ * (llm_unavailable, llm_empty, llm_refused, llm_malformed, llm_truncated) and
+ * a truncated answer is rejected even when it parses; a wrong row count is a
+ * gate (e) failure; the corrective re-ask carries the model's own answer plus
+ * the gate letter and row numbers only; the splice rebuilds only the fence;
+ * the prompt bytes are pinned (a change must bump FENCE_REPAIR_PROMPT_VERSION).
+ * Fails when: valid rows or page prose leak into the prompt, a tool or a
+ * fallback chain reaches the call, a refusal or truncation is treated as an
+ * answer, or the re-ask quotes anything beyond its own answer.
+ * Why new: the Tier 3 module is new in PR4.
+ * Seams: the gateway's chat transport seam (__setChatTransportForTests).
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { __setChatTransportForTests, configureGateway, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';
+import { buildTier3Prompt, callTier3, correctionMessage, extractSingleTable, FENCE_REPAIR_PROMPT_VERSION, spliceTier3, tier3Requests } from '../src/core/fence-repair/llm.ts';
+import { safeNormalizeFences } from '../src/core/fence-repair/normalize.ts';
+import { validateFenceRepair } from '../src/core/fence-repair/validate.ts';
+
+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';
+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';
+const NARROW = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';
+const SEP = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';
+const VALID = 'Validrowclaimzq9 stays private';
+const PROSE = 'Pageproseqz9 is never sent';
+const BROKEN = 'Brokenrowclaimzq9 ships';
+/** One valid row and one row with an extra empty cell in the middle (extra_cells, row-level). */
+const rowLevel = `${PROSE}\n\n${FB}\n${FH}\n| 1 | ${VALID} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |\n| 2 | ${BROKEN} | | fact | 0.8 | private | low | 2026-02-01 | | chat | ctx |\n${FBE}\n`;
+/** A fence with rows but no header (no_header, fence-level). */
+const noHeader = `${PROSE}\n\n${FB}\n| 1 | ${BROKEN} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |\n${FBE}\n`;
+
+const result = (text: string, stopReason: ChatResult['stopReason'] = 'end'): ChatResult => ({ text, blocks: [], stopReason,
+ usage: { input_tokens: 400, output_tokens: 80, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-opus-4-7', providerId: 'anthropic' });
+
+function stub(answers: Array<ChatResult | Error>) {
+ const calls: ChatOpts[] = [];
+ __setChatTransportForTests(async opts => {
+ calls.push(opts);
+ const next = answers.shift()!;
+ if (next instanceof Error) throw next;
+ return next;
+ });
+ return calls;
+}
+
+function residualOf(text: string) {
+ const page = { compiled_truth: text, timeline: '' };
+ const normalized = safeNormalizeFences(page, { pageVisibility: 'private' });
+ return { page, normalized, ...tier3Requests(normalized.page, normalized.residual, 'private') };
+}
+
+afterEach(() => __setChatTransportForTests(null));
+
+describe('Tier 3 requests and prompt', () => {
+ test('a row-level issue sends the header and that row only; a fence-level issue sends every row; page prose never', () => {
+ const row = residualOf(rowLevel);
+ expect(row.normalized.residual.map(i => i.reason)).toEqual(['extra_cells']);
+ expect(row.requests).toHaveLength(1);
+ const req = row.requests[0]!;
+ expect(req.rows.map(r => r.occurrence)).toEqual([1]);
+ const prompt = buildTier3Prompt(req);
+ const all = `${prompt.system}\n${prompt.user}`;
+ expect(all).toContain(BROKEN);
+ expect(all).not.toContain(VALID);
+ expect(all).not.toContain(PROSE);
+ expect(prompt.user).toContain('extra_cells: row(s) 2');
+ const fence = residualOf(noHeader);
+ expect(fence.requests[0]!.header).toBeNull();
+ expect(fence.requests[0]!.rows).toHaveLength(1);
+ expect(buildTier3Prompt(fence.requests[0]!).user).not.toContain(PROSE);
+ });
+
+ test('prompt bytes are pinned; a prompt change must bump FENCE_REPAIR_PROMPT_VERSION', () => {
+ const prompt = buildTier3Prompt(residualOf(noHeader).requests[0]!);
+ const digest = createHash('sha256').update(`${prompt.system}\u0000${prompt.user}`).digest('hex');
+ expect({ version: FENCE_REPAIR_PROMPT_VERSION, digest }).toEqual({ version: 1, digest: PROMPT_DIGEST });
+ });
+
+ test('a fence with a stray text line inside is not eligible (rebuilding the table would drop it)', () => {
+ const stray = `${FB}\n| 1 | ${BROKEN} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |\na stray note\n${FBE}\n`;
+ const out = residualOf(stray);
+ expect(out.requests).toEqual([]);
+ expect(out.ineligible.map(i => i.why)).toEqual(['stray_lines']);
+ });
+});
+
+describe('extracting the answer', () => {
+ const req = { kind: 'facts' as const, layout: 'narrow' as const };
+ test('a single table (optionally in one code fence) is accepted; prose, a wrong header or nothing is not', () => {
+ expect(extractSingleTable(`${NARROW}\n${SEP}\n| 1 | x | fact | 1 | private | high | | | | |`, req)).toMatchObject({ ok: true });
+ expect(extractSingleTable('```markdown\n' + `${NARROW}\n${SEP}\n| 1 | x | fact | 1 | private | high | | | | |` + '\n```', req)).toMatchObject({ ok: true });
+ expect(extractSingleTable(`Here is the table:\n${NARROW}\n${SEP}\n| 1 | x |`, req)).toEqual({ ok: false, reason: 'llm_malformed' });
+ expect(extractSingleTable('| # | claim | type |\n|---|---|---|\n| 1 | x | fact |', req)).toEqual({ ok: false, reason: 'llm_malformed' });
+ expect(extractSingleTable(' ', req)).toEqual({ ok: false, reason: 'llm_empty' });
+ expect(extractSingleTable("I can't help rewrite that table.", req)).toEqual({ ok: false, reason: 'llm_refused' });
+ });
+});
+
+describe('the gateway call', () => {
+ const realigned = `${NARROW}\n${SEP}\n| 2 | ${BROKEN} | fact | 0.8 | private | low | 2026-02-01 | | chat | ctx |`;
+
+ test('no tools, no fallback, the configured model; a realigned answer splices into a page that passes every gate', async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', chat_fallback_chain: ['openai:gpt-6-luna'] } as never);
+ const calls = stub([result(realigned)]);
+ const { page, normalized, requests } = residualOf(rowLevel);
+ const answer = await callTier3(requests[0]!, { model: 'anthropic:claude-fable-5' });
+ expect(answer.ok).toBe(true);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]!.tools).toBeUndefined();
+ expect(calls[0]!.allowFallback).toBe(false);
+ expect(calls[0]!.model).toBe('anthropic:claude-fable-5');
+ expect(calls[0]!.temperature).toBe(0);
+ const spliced = spliceTier3(normalized.page, requests[0]!, (answer as Extract<typeof answer, { ok: true }>).table)!;
+ expect(spliced.compiled_truth.startsWith(`${PROSE}\n\n${FB}\n${NARROW}\n${SEP}\n| 1 | ${VALID} |`)).toBe(true);
+ const final = safeNormalizeFences(spliced, { pageVisibility: 'private' });
+ expect(final.residual).toEqual([]);
+ expect(validateFenceRepair(page, final.page, { pageVisibility: 'private', tier: 'llm', issues: [...normalized.fixes, ...normalized.residual] })).toEqual({ ok: true });
+ });
+
+ test('each failure class is distinct; a truncated answer that parses is still rejected; a wrong row count is a gate (e) failure', async () => {
+ const req = residualOf(rowLevel).requests[0]!;
+ const cases: Array<[ChatResult | Error, string]> = [
+ [Object.assign(new Error('rate limited'), { status: 429 }), 'llm_unavailable'],
+ [result(''), 'llm_empty'],
+ [result('', 'refusal'), 'llm_refused'],
+ [result(realigned, 'content_filter'), 'llm_refused'],
+ [result('Sure! I fixed it.'), 'llm_malformed'],
+ [result(realigned, 'length'), 'llm_truncated'],
+ [result(`${realigned}\n| 3 | Extra row | fact | 1 | private | high | | | | |`), 'row_count_changed'],
+ ];
+ for (const [answer, reason] of cases) expect(await reasonOf(req, answer)).toBe(reason);
+ });
+
+ test('the corrective re-ask repeats the model\'s own answer and names only the gate letter and rows', async () => {
+ const req = residualOf(rowLevel).requests[0]!;
+ const calls = stub([result(realigned)]);
+ await callTier3(req, { model: 'anthropic:claude-opus-4-7', correction: { answer: 'PRIOR-ANSWER', gate: 'f', rows: [2] } });
+ const messages = calls[0]!.messages;
+ expect(messages.map(m => m.role)).toEqual(['user', 'assistant', 'user']);
+ expect(messages[1]!.content).toBe('PRIOR-ANSWER');
+ expect(messages[2]!.content).toBe(correctionMessage('f', [2]));
+ expect(String(messages[2]!.content)).toBe("Your table was rejected by validation gate (f) cell_changed at row(s) 2: a cell's text changed, or a valid cell moved out of its column. Return the corrected full table following every rule above. Output only the table.");
+ });
+});
+
+async function reasonOf(req: Parameters<typeof callTier3>[0], answer: ChatResult | Error): Promise<string> {
+ stub([answer]);
+ const out = await callTier3(req, { model: 'anthropic:claude-opus-4-7' });
+ return out.ok ? 'ok' : out.reason;
+}
+
+const PROMPT_DIGEST = '9f3cf734abd6aac8b28ee094b226c4c654ab0e85e07a0c6aed6235eb97221114';
diff --git a/test/repair-fences.test.ts b/test/repair-fences.test.ts
new file mode 100644
index 0000000000..46756df087
--- /dev/null
+++ b/test/repair-fences.test.ts
@@ -0,0 +1,451 @@
+/**
+ * #6188 PR4: `gbrain repair fences`, end to end on managed, legacy,
+ * database-only and mirror sources, with the model behind the gateway's chat
+ * transport seam.
+ *
+ * Protects: the preview lists every tier with its estimated model cost and
+ * makes no model call; the printed apply command runs as printed and repairs
+ * each tier (managed: file rewritten, imported, hold cleared, Git commit
+ * whose subject names the path and classes, a fence-repair receipt; legacy:
+ * backup, import and an uncommitted-repair notice that clears once the path
+ * is committed; database-only: a revision-bound page write; mirror: the page
+ * is repaired and the file never written); every gate failure keeps the hold
+ * with its gate; the attempt memo makes the second run on an unchanged
+ * rejected file spend nothing, while a transient provider error does not
+ * consume it; an agent journey where every model proposal is rejected never
+ * reports anything repaired; budget exhausted (run stop, exit 1, the D15
+ * message and paid fix), model repair disabled, unpriced model under a user
+ * cap; changed_since_preview, sync_in_progress and owner_unavailable write
+ * nothing; a remote caller cannot reach Tier 3; --max-usd only lowers the cap
+ * and only paid-model kinds accept it; Tier 2 accepts only a strict
+ * people/companies match and never a private page on a world page; the
+ * location-only privacy rule on holds, receipts, results and commits.
+ * Fails when: any of those paths regresses (a write without the gates, a
+ * second paid call for the same bytes, a hidden spend, a remote write, an
+ * unrunnable printed command).
+ * Why new: the fences kind is new in PR4.
+ * Seams: __setChatTransportForTests (no provider call); test/postgres-unit-arms.txt runs the Postgres arm.
+ */
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';
+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { parseFactsFence } from '../src/core/facts-fence.ts';
+import { parseTakesFence } from '../src/core/takes-fence.ts';
+import { resolveRepairScope, type RepairResult } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { fencesRepair, type FencesPreviewDetails } from '../src/core/repair/fences.ts';
+import { readUncommittedFenceRepairs } from '../src/core/fence-repair/uncommitted.ts';
+import { parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-fences-'));
+const engines: BrainEngine[] = [];
+let legacyEngine: PGLiteEngine;
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: 'sk-test-not-used', GBRAIN_FENCE_REPAIR_SCAN_MS: '60000' };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message = 'content') => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };
+const quiet = { info() {}, warn() {}, error() {} };
+
+// Unique strings that must never leave a file through a hold, receipt, result field or commit message.
+const CLAIM = 'Sentinelclaimzr4 ships quarterly', HOLDER = 'Alice Example', MCLAIM = 'Sentinelmanualzr4 opens an office';
+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';
+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';
+const NARROW = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';
+const SEP = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';
+const T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';
+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';
+const row = (claim: string) => `| 1 | ${claim} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |`;
+const md = (title: string, body: string, extra = '') => `---\ntitle: ${title}\n${extra}---\nA synthetic page.\n\n${body}`;
+/** Tier 3: rows but no header. */
+const noHeader = (claim = CLAIM) => `${FB}\n${row(claim)}\n${FBE}\n`;
+/** Tier 1: a missing end marker and an invented kind. */
+const fixable = (claim = 'Synthetic vendor partnership') => `${FB}\n${FH}\n| 1 | ${claim} | partnership | 0.9 | private | high | 2026-01-01 | | chat | |\n`;
+/** Tier 2: a display-name holder. */
+const holder = (who = HOLDER) => `${T}\n${TH}\n| 1 | Synthetic take | take | ${who} | 0.7 | 2026-01 | chat |\n${TE}\n`;
+/** Manual: a visibility word with no mapping. */
+const manual = (claim = MCLAIM) => `${FB}\n${FH}\n| 1 | ${claim} | fact | 0.9 | sideways | high | 2026-01-01 | | chat | ctx |\n${FBE}\n`;
+const answer = (claim: string, text = `${NARROW}\n${SEP}\n${row(claim)}`, stop: ChatResult['stopReason'] = 'end'): ChatResult => ({ text, blocks: [], stopReason: stop,
+ usage: { input_tokens: 500, output_tokens: 120, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-opus-4-7', providerId: 'anthropic' });
+
+let calls: ChatOpts[] = [];
+function transport(reply: (opts: ChatOpts, n: number) => ChatResult | Error) {
+ calls = [];
+ __setChatTransportForTests(async opts => { calls.push(opts); const out = reply(opts, calls.length); if (out instanceof Error) throw out; return out; });
+}
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+ legacyEngine = new PGLiteEngine(); await legacyEngine.connect({}); await legacyEngine.initSchema();
+}, 120_000);
+
+afterEach(() => { __setChatTransportForTests(null); _resetCliExitVerdictForTests(); });
+
+afterAll(async () => {
+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
+ await legacyEngine.disconnect();
+ await closePostgres?.(); resetGateway(); rmSync(home, { recursive: true, force: true });
+});
+
+function newRoot(prefix: string, files: Record<string, string>) {
+ const id = `${prefix}-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);
+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');
+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ const write = (path: string, content: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); };
+ for (const [path, content] of Object.entries(files)) write(path, content);
+ commit(root, 'fixture');
+ return { id, root, write, read: (path: string) => readFileSync(join(root, path), 'utf8') };
+}
+
+async function managed(engine: BrainEngine, files: Record<string, string>, opts: { mirror?: boolean } = {}) {
+ const r = newRoot('fen', files);
+ writeFileSync(join(r.root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(join(r.root, '.git', 'hooks', 'post-commit'), 0o755);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw(`INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)`, [r.id, r.root, JSON.stringify(opts.mirror ? { mirror_read_only: true } : {})]);
+ await claimWorktree(engine, r.id, r.root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { ...r, ...helpers(engine, r.id) };
+}
+
+function helpers(engine: BrainEngine, id: string) {
+ const sync = () => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ const holds = async () => (await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? [];
+ const run = async (opts: { apply?: boolean; expect?: string; only?: string[]; slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number } = {}) => {
+ const runner = await repairRunner(engine, { apply: opts.apply === true, noEmbed: true, logger: quiet });
+ return runner.run('fences', await resolveRepairScope(engine, id), { explicit: true, sourceFlag: id, expect: opts.expect, only: opts.only, slugs: opts.slugs,
+ noLlm: opts.noLlm, maxLlmUsd: opts.maxLlmUsd });
+ };
+ return { sync, holds, run };
+}
+
+/** Prints of `gbrain repair` with these args. */
+async function cli(engine: BrainEngine, args: string[]): Promise<string> {
+ const out: string[] = [];
+ const log = console.log;
+ console.log = (...parts: unknown[]) => { out.push(parts.join(' ')); };
+ try { await runRepairCommand(engine, args); } finally { console.log = log; }
+ return out.join('\n');
+}
+
+async function gitEffectsSettled(engine: BrainEngine, sourceId: string) {
+ for (let i = 0; i < 100; i++) {
+ await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 10 });
+ const open = await engine.executeRaw("SELECT 1 FROM persistence_effects WHERE source_id=$1 AND kind='git' AND state<>'committed'", [sourceId]);
+ if (!open.length) return;
+ await Bun.sleep(100);
+ }
+ throw new Error('git effects did not settle');
+}
+
+const details = (result: RepairResult) => result.details as unknown as FencesPreviewDetails;
+const hashOf = (result: RepairResult) => result.apply_command.split('--expect ')[1]!.split(' ')[0]!;
+const expectNoSecrets = (value: unknown) => { const text = typeof value === 'string' ? value : JSON.stringify(value); for (const secret of [CLAIM, MCLAIM, 'Sentinelclaimzr4', 'Sentinelmanualzr4']) expect(text).not.toContain(secret); };
+/** Result fields that carry no diff: the preview's diffs show file lines to the operator by design (D14). */
+const surfaceOf = (result: RepairResult) => ({ ...result, details: undefined });
+
+async function each(run: (engine: BrainEngine) => Promise<void>) {
+ await withEnv(env, async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6' } as never);
+ for (const engine of engines) {
+ try { await run(engine); } finally { await disposePersistenceConsumer(engine); }
+ }
+ });
+}
+
+test('preview lists every tier with its cost and calls no model; the printed apply command repairs each tier and leaves the manual one held', () => each(async engine => {
+ const s = await managed(engine, { 'people/alice-example.md': md('Alice Example', 'A synthetic person.\n'), 'notes/a.md': md('A', 'Plain.\n'),
+ 'people/model.md': md('Model', noHeader()), 'people/holder.md': md('Holder', holder()), 'people/manual.md': md('Manual', manual()) });
+ expect((await s.sync()).held_count).toBe(3);
+ s.write('people/later.md', md('Later', fixable()));
+ transport(() => answer(CLAIM));
+ const preview = JSON.parse(await cli(engine, ['fences', '--source', s.id, '--json'])) as { results: RepairResult[] };
+ const result = preview.results[0]!;
+ expect(calls).toHaveLength(0);
+ expect(result.listing!.map(entry => [entry.item, entry.class]).sort()).toEqual([
+ [`${s.id}:people/holder.md`, 'resolver'], [`${s.id}:people/later.md`, 'deterministic'], [`${s.id}:people/manual.md`, 'enum_unmapped'], [`${s.id}:people/model.md`, 'llm']]);
+ expect(details(result).counts).toEqual({ deterministic: 1, resolver: 1, llm: 1, held: 1 });
+ expect(result.cost.llm_usd).toBeGreaterThan(0);
+ expect(result.cost.llm_cap_remaining_usd).toBe(1);
+ expect(details(result).samples.deterministic!.diff).toContain(`+${FBE}`);
+ expect(details(result).samples.resolver!.diff).toContain('people/alice-example');
+ expect(details(result).held[0]!.resolution).toContain('visibility');
+ expect(result.apply_command).toBe(`gbrain repair fences --source ${s.id} --apply --expect ${hashOf(result)}`);
+ expect(s.read('people/model.md')).toBe(md('Model', noHeader()));
+ // The printed command runs exactly as printed.
+ const applied = (JSON.parse(await cli(engine, [...result.apply_command.split(' ').slice(2), '--json'])) as { results: RepairResult[] }).results[0]!;
+ expect(applied).toMatchObject({ mode: 'apply', applied: 3, repaired: 3, remaining: { enum_unmapped: 1 }, outcomes: { repaired: 3 } });
+ expect(calls).toHaveLength(1);
+ const prompt = `${calls[0]!.system}\n${JSON.stringify(calls[0]!.messages)}`;
+ expect(prompt).toContain(CLAIM);
+ expect(prompt).not.toContain(MCLAIM);
+ expect(prompt).not.toContain('A synthetic page.');
+ expect(parseFactsFence(s.read('people/model.md')).warnings).toEqual([]);
+ expect(parseFactsFence(s.read('people/later.md')).warnings).toEqual([]);
+ expect(parseTakesFence(s.read('people/holder.md')).takes[0]!.holder).toBe('people/alice-example');
+ expect((await engine.getPage('people/model', { sourceId: s.id }))?.compiled_truth).toContain(CLAIM);
+ // Only the manual file is still held, with the reason the repair left on it.
+ const holds = await s.holds();
+ expect(holds.map(h => h.path)).toEqual(['people/manual.md']);
+ expect(holds[0]!.meta.fence?.reason).toBe('enum_unmapped');
+ // A bare apply (the maintenance run) records on the hold why it stays.
+ expect(await s.run({ apply: true })).toMatchObject({ applied: 0, remaining: { enum_unmapped: 1 } });
+ expect((await s.holds())[0]!.meta.fence_repair).toMatchObject({ reason: 'enum_unmapped', tier: 'manual', next_attempt_after: null });
+ // Commits name the path and the classes; receipts carry the fence-repair actor, tier, model, hashes and cost; nothing carries a cell value.
+ await gitEffectsSettled(engine, s.id);
+ // One commit per file reads `gbrain: repair fence in <path> (<classes>)`; a batched commit lists `<path> (<classes>)` per body line.
+ const log = git(s.root, 'log', '--format=%B');
+ expect(log).toContain('people/model.md (no_header)');
+ expect(log).toContain('people/holder.md (holder_verified)');
+ expect(git(s.root, 'status', '--porcelain', '--', 'people/model.md')).toBe('');
+ const receipts = await engine.executeRaw<{ outcome: Record<string, any> }>("SELECT outcome FROM persistence_requests WHERE source_id=$1 AND outcome ? 'fence_repair' ORDER BY sequence", [s.id]);
+ expect(receipts.map(r => r.outcome.fence_repair.tier).sort()).toEqual(['deterministic', 'llm', 'resolver']);
+ const llmReceipt = receipts.find(r => r.outcome.fence_repair.tier === 'llm')!.outcome.fence_repair;
+ expect(llmReceipt).toMatchObject({ actor: 'fence-repair', classes: ['no_header'], model: 'anthropic:claude-opus-4-7' });
+ expect(llmReceipt.cost_usd).toBeGreaterThan(0);
+ expectNoSecrets([holds, receipts.map(r => r.outcome.fence_repair), surfaceOf(applied), git(s.root, 'log', '--format=%B')]);
+}), 240_000);
+
+test('every model proposal rejected: the hold keeps its gate, nothing is reported repaired, and a second run on the same bytes spends nothing', () => each(async engine => {
+ const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) });
+ await s.sync();
+ transport(() => answer('A different claim'));
+ const first = await s.run({ apply: true });
+ expect(first).toMatchObject({ applied: 0, repaired: 0, remaining: { claim_changed: 1 }, outcomes: { held: 1 } });
+ expect(calls).toHaveLength(2);
+ expect(String(calls[1]!.messages[2]!.content)).toContain('gate (b) claim_changed');
+ expect((await s.holds())[0]!.meta.fence_repair).toMatchObject({ reason: 'claim_changed', gate: 'b' });
+ expect(first.cost.llm_usd).toBeGreaterThan(0);
+ const human = await cli(engine, ['fences', '--source', s.id, '--apply']);
+ expect(human).toContain('repaired 0; still waiting: claim_changed=1');
+ expect(human).not.toContain('repaired 1');
+ // The memo: the same bytes, model, rules and prompt are never sent again.
+ const again = await s.run({ apply: true });
+ expect(calls).toHaveLength(2);
+ expect(again).toMatchObject({ applied: 0, repaired: 0, remaining: { claim_changed: 1 } });
+ expect(again.cost.llm_usd).toBe(0);
+ const preview = await s.run();
+ expect(details(preview).held[0]).toMatchObject({ reason: 'claim_changed', gate: 'b' });
+ expect(s.read('people/model.md')).toBe(md('Model', noHeader()));
+ // New bytes are a new memo key: the next run asks again.
+ s.write('people/model.md', md('Model', noHeader(), 'tags: [synthetic]\n')); commit(s.root, 'edit');
+ await s.sync();
+ transport(() => answer(CLAIM));
+ expect(await s.run({ apply: true })).toMatchObject({ repaired: 1 });
+ expect(calls).toHaveLength(1);
+ expectNoSecrets([await s.holds(), surfaceOf(first), surfaceOf(again)]);
+}), 240_000);
+
+test('a transient provider error keeps the memo; model repair off and --no-llm hold without a call; a user cap with an unpriced model holds no_pricing', () => each(async engine => {
+ const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) });
+ await s.sync();
+ transport(() => Object.assign(new Error('rate limited'), { status: 429 }));
+ expect(await s.run({ apply: true })).toMatchObject({ repaired: 0, remaining: { llm_unavailable: 1 } });
+ expect((await s.holds())[0]!.meta.fence_repair).toMatchObject({ reason: 'llm_unavailable', tier: 'llm' });
+ transport(() => answer(CLAIM));
+ expect(await s.run({ apply: true, noLlm: true })).toMatchObject({ repaired: 0, remaining: { llm_disabled: 1 } });
+ await engine.setConfig('fences.repair.llm', 'false');
+ expect(await s.run({ apply: true })).toMatchObject({ repaired: 0, remaining: { llm_disabled: 1 } });
+ expect(calls).toHaveLength(0);
+ await engine.setConfig('fences.repair.llm', 'true');
+ await engine.setConfig('models.fence_repair', 'anthropic:claude-unpriced-zr4');
+ await engine.setConfig('fences.repair.max_usd_per_page', '0.05');
+ const refused = await s.run();
+ expect(details(refused).held[0]).toMatchObject({ reason: 'no_pricing' });
+ expect(details(refused).held[0]!.resolution).toContain('gbrain pricing set');
+ expect(calls).toHaveLength(0);
+ // Under the default caps an unpriced model warns and runs, metered at the ceiling rate.
+ await engine.executeRaw("DELETE FROM config WHERE key='fences.repair.max_usd_per_page'");
+ const warned = await s.run();
+ expect(warned.warnings?.join(' ')).toContain('gbrain pricing set anthropic:claude-unpriced-zr4');
+ expect(warned.cost.llm_usd).toBeGreaterThan(0);
+ const ran = await s.run({ apply: true });
+ expect(ran).toMatchObject({ repaired: 1 });
+ expect(calls).toHaveLength(1);
+ expect(calls[0]!.model).toBe('anthropic:claude-unpriced-zr4');
+ await engine.executeRaw("DELETE FROM config WHERE key IN ('models.fence_repair','fences.repair.llm')");
+}), 240_000);
+
+test('the daily ledger refusing the next call stops the run with the reset time, the waiting pages and the paid fix (exit 1)', () => each(async engine => {
+ const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) });
+ await s.sync();
+ transport(() => answer(CLAIM));
+ await engine.setConfig('fences.repair.max_usd_per_day', '0.001');
+ const out = JSON.parse(await cli(engine, ['fences', '--source', s.id, '--apply', '--json'])) as { results: RepairResult[] };
+ const result = out.results[0]!;
+ expect(currentExitCode()).toBe(1);
+ expect(calls).toHaveLength(0);
+ expect(result.stopped).toMatchObject({ reason: 'budget_exhausted', fix: { argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<usd>'], consent: ['paid'], actor: 'agent' } });
+ expect(result.stopped!.message).toMatch(/resets at \d{4}-\d{2}-\d{2}T00:00:00\.000Z/);
+ expect(result.stopped!.message).toContain('1 page(s) wait');
+ expect((await s.holds())[0]!.meta.fence_repair).toMatchObject({ reason: 'budget_exhausted' });
+ expect((await s.holds())[0]!.meta.fence_repair!.next_attempt_after).toMatch(/T00:00:00\.000Z$/);
+ await engine.executeRaw("DELETE FROM config WHERE key='fences.repair.max_usd_per_day'");
+}), 240_000);
+
+test('a file changed since the preview, an unfinished sync and a non-owner host write nothing', () => each(async engine => {
+ const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) });
+ await s.sync();
+ transport(() => answer(CLAIM));
+ const preview = await s.run();
+ const edited = md('Model', noHeader(), 'tags: [edited]\n');
+ s.write('people/model.md', edited);
+ expect(await s.run({ apply: true, expect: hashOf(preview) })).toMatchObject({ applied: 0, outcomes: { skipped: 1 }, remaining: { changed_since_preview: 1 } });
+ expect(s.read('people/model.md')).toBe(edited);
+ expect(calls).toHaveLength(0);
+ s.write('people/model.md', md('Model', noHeader()));
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`,
+ [`probe-${s.id}`, JSON.stringify([{ sourceId: s.id, runId: 'probe', index: 0, done: false }])]);
+ const busy = await s.run({ apply: true });
+ expect(busy).toMatchObject({ applied: 0, remaining: { sync_in_progress: 1 } });
+ expect((await s.holds())[0]!.meta.fence_repair).toMatchObject({ reason: 'sync_in_progress' });
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [`probe-${s.id}`]);
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$1::uuid WHERE id=(SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$2 LIMIT 1)', [randomUUID(), s.id]);
+ });
+ const elsewhere = await s.run({ apply: true });
+ expect(elsewhere).toMatchObject({ applied: 0, remaining: { owner_unavailable: 1 } });
+ expect(calls).toHaveLength(0);
+ expect(s.read('people/model.md')).toBe(md('Model', noHeader()));
+}), 240_000);
+
+test('a read-only mirror is repaired in the database only and its hold cleared; the file is never written', () => each(async engine => {
+ const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) }, { mirror: true });
+ await s.sync();
+ expect((await s.holds()).map(h => h.path)).toEqual(['people/model.md']);
+ transport(() => answer(CLAIM));
+ const applied = await s.run({ apply: true });
+ expect(applied).toMatchObject({ repaired: 1 });
+ expect(applied.outcome_items![0]!.detail).toMatchObject({ mode: 'mirror', storage: 'database_only' });
+ expect(s.read('people/model.md')).toBe(md('Model', noHeader()));
+ expect(parseFactsFence((await engine.getPage('people/model', { sourceId: s.id }))!.compiled_truth).facts.map(f => f.claim)).toEqual([CLAIM]);
+ expect(await s.holds()).toEqual([]);
+}), 240_000);
+
+test('a remote caller can never reach Tier 3 or a write', () => each(async engine => {
+ const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) });
+ await s.sync();
+ transport(() => answer(CLAIM));
+ const plan = await fencesRepair.plan(engine, await resolveRepairScope(engine, s.id), null, { apply: true });
+ const ctx = { engine, config: { engine: engine.kind }, logger: quiet, dryRun: false, remote: true, sourceId: s.id } as unknown as OperationContext;
+ let error: unknown;
+ try { await fencesRepair.apply(ctx, plan.items[0]!, { embed: false }); } catch (e) { error = e; }
+ expect(error).toBeInstanceOf(OperationError);
+ expect((error as OperationError).code).toBe('permission_denied');
+ expect(calls).toHaveLength(0);
+ expect(s.read('people/model.md')).toBe(md('Model', noHeader()));
+}), 240_000);
+
+test('--max-usd lowers the cap only, is printed in the apply command, and only paid-model kinds accept it', () => each(async engine => {
+ const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) });
+ await s.sync();
+ transport(() => answer(CLAIM));
+ expect(() => parseRepairArgs(['timeline', '--max-usd', '1'])).toThrow(/applies only to a kind that may call a paid model/);
+ expect(() => parseRepairArgs(['timeline', '--max-usd', '1'])).toThrow(OperationError);
+ expect(() => parseRepairArgs(['fences', '--max-usd', 'lots'])).toThrow(/non-negative USD amount/);
+ const dayLeft = (await s.run()).cost.llm_cap_remaining_usd!;
+ expect(dayLeft).toBeGreaterThan(0.25);
+ const high = await s.run({ maxLlmUsd: 5 });
+ expect(high.cost.llm_cap_remaining_usd).toBe(dayLeft);
+ const low = await s.run({ maxLlmUsd: 0.25 });
+ expect(low.cost.llm_cap_remaining_usd).toBe(0.25);
+ expect(low.apply_command).toContain('--max-usd 0.25 --apply --expect ');
+ const none = await s.run({ apply: true, maxLlmUsd: 0 });
+ expect(none.stopped).toMatchObject({ reason: 'budget_exhausted' });
+ expect(calls).toHaveLength(0);
+ expect(s.read('people/model.md')).toBe(md('Model', noHeader()));
+}), 240_000);
+
+test('Tier 2 takes only a strict people/companies match and never a private page on a world page', () => each(async engine => {
+ const s = await managed(engine, { 'people/alice-example.md': md('Alice Example', 'Private person.\n', 'visibility: private\n'),
+ 'people/world.md': md('World', holder(), 'visibility: world\n'), 'people/bare.md': md('Bare', holder('Alice')) });
+ await s.sync();
+ const preview = await s.run();
+ const held = Object.fromEntries(details(preview).held.map(h => [h.item.split(':')[1], h.reason]));
+ expect(held).toEqual({ 'people/world.md': 'holder_unresolved', 'people/bare.md': 'holder_unresolved' });
+ expect(preview.affected).toBe(0);
+}), 240_000);
+
+test('legacy sources: backup, import and an uncommitted-repair notice that clears once the path is committed; a symlink is never written', async () => withEnv(env, async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6' } as never);
+ const engine = legacyEngine;
+ const r = newRoot('leg', { 'notes/model.md': md('Model', noHeader()), 'notes/later.md': md('Later', fixable()) });
+ writeFileSync(join(home, `${r.id}-target.md`), md('Target', noHeader('Linked claim')));
+ symlinkSync(join(home, `${r.id}-target.md`), join(r.root, 'notes/linked.md'));
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [r.id, r.root]);
+ const h = helpers(engine, r.id);
+ transport(() => answer(CLAIM));
+ const preview = await h.run();
+ expect(preview.listing!.map(entry => [entry.item, entry.class]).sort()).toEqual([[`${r.id}:notes/later.md`, 'deterministic'], [`${r.id}:notes/model.md`, 'llm']]);
+ const applied = await h.run({ apply: true, expect: hashOf(preview) });
+ expect(applied).toMatchObject({ repaired: 2 });
+ const detail = applied.outcome_items!.find(o => o.item.endsWith('notes/model'))!.detail!;
+ expect(detail).toMatchObject({ mode: 'legacy', committed: 'commit_step' });
+ expect(existsSync(String(detail.backup))).toBe(true);
+ expect(readFileSync(String(detail.backup), 'utf8')).toBe(md('Model', noHeader()));
+ expect(parseFactsFence(r.read('notes/model.md')).warnings).toEqual([]);
+ expect((await engine.getPage('notes/model', { sourceId: r.id }))?.compiled_truth).toContain(CLAIM);
+ const notices = await readUncommittedFenceRepairs(engine, [r.id]);
+ expect(notices.map(n => n.path).sort()).toEqual(['notes/later.md', 'notes/model.md']);
+ const step = notices.find(n => n.path === 'notes/model.md')!.commit_step;
+ expect(step).toContain("commit -m 'gbrain: repair fence in notes/model.md (no_header)'");
+ execFileSync('bash', ['-c', step]);
+ expect(git(r.root, 'log', '-1', '--format=%s')).toBe('gbrain: repair fence in notes/model.md (no_header)');
+ expect((await readUncommittedFenceRepairs(engine, [r.id])).map(n => n.path)).toEqual(['notes/later.md']);
+ expect(readFileSync(join(home, `${r.id}-target.md`), 'utf8')).toBe(md('Target', noHeader('Linked claim')));
+}), 240_000);
+
+test('a database-only page takes a revision-bound page write', async () => withEnv(env, async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6' } as never);
+ const engine = legacyEngine;
+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES('dbonly','dbonly','{}') ON CONFLICT DO NOTHING");
+ await engine.putPage('notes/db-only', { type: 'note', title: 'Db only', compiled_truth: `Intro.\n\n${noHeader()}`, timeline: '' }, { sourceId: 'dbonly' });
+ const h = helpers(engine, 'dbonly');
+ transport(() => answer(CLAIM));
+ const preview = await h.run();
+ expect(preview.listing!.map(entry => [entry.item, entry.class])).toEqual([['dbonly:notes/db-only', 'llm']]);
+ const applied = await h.run({ apply: true, expect: hashOf(preview), slugs: [] });
+ expect(applied).toMatchObject({ repaired: 1 });
+ expect(applied.outcome_items![0]!.detail).toMatchObject({ mode: 'db', slug: 'notes/db-only' });
+ const page = await engine.getPage('notes/db-only', { sourceId: 'dbonly' });
+ expect(parseFactsFence(page!.compiled_truth).warnings).toEqual([]);
+ expect(parseFactsFence(page!.compiled_truth).facts.map(f => f.claim)).toEqual([CLAIM]);
+}), 240_000);
+
+test('--slug reaches a page the census has not judged and binds it into the hash and the apply command', async () => withEnv(env, async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6' } as never);
+ const engine = legacyEngine;
+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES('slugged','slugged','{}') ON CONFLICT DO NOTHING");
+ await importFromContent(engine, 'notes/one', md('One', noHeader('Slug claim one')), { sourceId: 'slugged', noEmbed: true });
+ await importFromContent(engine, 'notes/two', md('Two', noHeader('Slug claim two')), { sourceId: 'slugged', noEmbed: true });
+ const h = helpers(engine, 'slugged');
+ transport(() => answer('Slug claim one'));
+ const one = await h.run({ slugs: ['notes/one'] });
+ expect(one.listing!.map(entry => entry.item)).toEqual(['slugged:notes/one']);
+ expect(one.apply_command).toBe(`gbrain repair fences --source slugged --slug notes/one --apply --expect ${hashOf(one)}`);
+ expect(hashOf(one)).not.toBe(hashOf(await h.run()));
+ let refused: unknown;
+ try { await h.run({ apply: true, expect: hashOf(one) }); } catch (error) { refused = error; }
+ expect((refused as OperationError).code).toBe('preview_changed');
+ expect(await h.run({ apply: true, expect: hashOf(one), slugs: ['notes/one'] })).toMatchObject({ repaired: 1 });
+ expect(parseFactsFence((await engine.getPage('notes/two', { sourceId: 'slugged' }))!.compiled_truth).warnings.length).toBeGreaterThan(0);
+}), 240_000);