Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): the fences repair kind: Tier 2 verified holders, Tier 3 model rewrite under the ledger and attempt memo, write-back paths and receipts (#6188)
garrytana7a9ca253de0
diff --git a/src/core/fence-repair/llm.ts b/src/core/fence-repair/llm.tsnew file mode 100644index 0000000000..7425d9812f--- /dev/null+++ b/src/core/fence-repair/llm.ts@@ -0,0 +1,267 @@+/**+ * Tier 3 fence repair (#6188): the configured chat model realigns the rows a+ * fence's residual issues name, and nothing else.+ *+ * What the model sees: the fence kind and section, the page's visibility,+ * the canonical header, the schema vocabulary, the residual reason codes+ * with row numbers, and the header line plus the residual rows exactly as+ * written. For a fence-level issue (`no_header`, `header_unmapped`, or an+ * issue that names no row) that is every row of that fence; otherwise only+ * the named rows. Never the valid rows of a row-level issue, never the rest+ * of the page, never tools.+ *+ * What it must return: one markdown table (the canonical header, the+ * separator, one row per input row in order) and nothing else. A single+ * wrapping code fence is tolerated; any other text outside the table is+ * `llm_malformed`. Failure classes: `llm_unavailable` (the provider threw:+ * timeout, rate limit, server error; transient, the attempt memo is not+ * consumed), `llm_empty`, `llm_refused` (refusal or content-filter stop, or a+ * prose refusal), `llm_malformed` (no single table, wrong header, prose),+ * `llm_truncated` (any stop other than a normal end, rejected even if the+ * text parses). A table with the wrong number of rows is a gate (e) failure,+ * so it earns the one corrective re-ask like any other gate failure.+ *+ * The corrective re-ask repeats the conversation with the model's own answer+ * and names the failed gate letter and row numbers only.+ *+ * Pure helpers (`tier3Requests`, `buildTier3Prompt`, `extractSingleTable`,+ * `spliceTier3`) do no I/O; `callTier3` is the one gateway call, testable+ * through the gateway's chat transport seam (`__setChatTransportForTests`).+ */+import { chat, type ChatMessage, type ChatResult } from '../ai/gateway.ts';+import { isSeparatorRow, parseRowCells } from '../fence-shared.ts';+import { sectionsOf } from './page-checks.ts';+import { extractRawRows, primaryFence, type RawFence, type RawRow } from './raw-rows.ts';+import { ALLOWED, BASE_WIDTH, CANONICAL_HEADER, COLUMNS, COLUMN_DEFAULTS } from './schema.ts';+import { GATE_REASONS } from './reasons.ts';+import type { FenceIssue, FenceKind, FencePage, FenceReason, FenceSection, GateLetter } from './types.ts';++/** Bump when the prompt text changes: it is part of the attempt-memo key, so a new prompt retries rejected pages. */+export const FENCE_REPAIR_PROMPT_VERSION = 1;++/** Residual reasons a model may clear (everything else is manual or the resolver's). */+export const TIER3_REASONS: ReadonlySet<FenceReason> = new Set(['header_unmapped', 'no_header', 'row_before_header', 'short_row', 'extra_cells']);+const FENCE_LEVEL: ReadonlySet<FenceReason> = new Set(['header_unmapped', 'no_header']);++export type Tier3Failure = 'llm_unavailable' | 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_truncated';++/** One fence the model is asked to repair. */+export interface Tier3Request {+ kind: FenceKind;+ section: FenceSection;+ pageVisibility: 'private' | 'world';+ layout: 'narrow' | 'wide';+ /** The header line as written, or null when the fence has none. */+ header: string | null;+ /** The rows sent, as written, in fence order, with their data-row ordinal. */+ rows: Array<{ occurrence: number; text: string }>;+ /** Residual reasons with the row numbers they name (location only). */+ issues: Array<{ reason: FenceReason; rows: number[] }>;+}++/** Why a fence cannot go to the model (it stays held with its own reason). */+export type Tier3Ineligible = { kind: FenceKind; section: FenceSection; why: 'no_fence' | 'stray_lines' | 'no_end_marker' };++/**+ * The model requests for a page's residual issues, one per fence, or why a+ * fence is not eligible. Callers send only issues whose reason is in+ * TIER3_REASONS.+ */+export function tier3Requests(page: FencePage, issues: readonly FenceIssue[], pageVisibility: 'private' | 'world'): { requests: Tier3Request[]; ineligible: Tier3Ineligible[] } {+ const requests: Tier3Request[] = [];+ const ineligible: Tier3Ineligible[] = [];+ const texts = new Map(sectionsOf(page));+ const groups = new Map<string, FenceIssue[]>();+ for (const issue of issues) {+ const key = `${issue.section}\u0000${issue.fence}`;+ groups.set(key, [...(groups.get(key) ?? []), issue]);+ }+ for (const group of groups.values()) {+ const { section, fence: kind } = group[0]!;+ const text = texts.get(section) ?? '';+ const fence = primaryFence(extractRawRows(text, section), kind);+ if (!fence) { ineligible.push({ kind, section, why: 'no_fence' }); continue; }+ if (!fence.end) { ineligible.push({ kind, section, why: 'no_end_marker' }); continue; }+ if (strayLines(text, fence)) { ineligible.push({ kind, section, why: 'stray_lines' }); continue; }+ const named = new Set(group.flatMap(issue => fence.rows.filter(row => row.line === issue.line).map(row => row.occurrence)));+ const fenceLevel = group.some(issue => FENCE_LEVEL.has(issue.reason) || issue.line === null || !fence.rows.some(row => row.line === issue.line));+ const sent = fence.rows.filter(row => fenceLevel || named.has(row.occurrence));+ const byReason = new Map<FenceReason, Set<number>>();+ for (const issue of group) {+ const rows = byReason.get(issue.reason) ?? new Set<number>();+ if (issue.row !== null) rows.add(issue.row);+ byReason.set(issue.reason, rows);+ }+ requests.push({ kind, section, pageVisibility, layout: wideLayout(kind, fence) ? 'wide' : 'narrow',+ header: fence.header ? text.slice(fence.header.start, fence.header.end) : null,+ rows: sent.map(row => ({ occurrence: row.occurrence, text: text.slice(row.start, row.end) })),+ issues: [...byReason].map(([reason, rows]) => ({ reason, rows: [...rows].sort((a, b) => a - b) })) });+ }+ return { requests, ineligible };+}++/** Wide when the header names a wide-layout column, or (no header) when the rows that parse carry more than the narrow width. */+function wideLayout(kind: FenceKind, fence: RawFence): boolean {+ const base = BASE_WIDTH[kind];+ if (fence.header) return fence.columns.some(column => column !== null && COLUMNS[kind].indexOf(column) >= base);+ return fence.rows.some(row => row.accepted && row.cells.length > base);+}++/** Non-blank lines inside the fence that are neither the header, a separator nor a data row: rebuilding the table would drop them. */+function strayLines(text: string, fence: RawFence): boolean {+ const region = text.slice(fence.begin.end, fence.end!.start);+ const tableLines = (fence.header ? 1 : 0) + fence.separators.length + fence.rows.length;+ return region.split('\n').filter(line => line.trim()).length !== tableLines;+}++function headerOf(req: Pick<Tier3Request, 'kind' | 'layout'>): { header: string; separator: string } {+ const h = CANONICAL_HEADER[req.kind];+ return req.layout === 'wide' ? { header: h.wide, separator: h.wideSep } : { header: h.narrow, separator: h.narrowSep };+}++function vocabulary(kind: FenceKind): string {+ return Object.entries(ALLOWED[kind]).filter(([column]) => column !== '#').map(([column, values]) => `- ${column}: ${values.join(', ')}`).join('\n');+}++const GATE_TEXT: Record<GateLetter, string> = {+ a: 'it still does not parse as a valid fence table',+ b: 'a claim cell changed',+ c: 'an existing row number changed',+ d: 'a row became more visible than the input allows',+ e: 'rows were added, dropped, merged, split or reordered',+ f: "a cell's text changed, or a valid cell moved out of its column",+ g: 'it would expose text that sat outside the table',+};++/** The system and first user message. Location and the rows as written; no other page text. */+export function buildTier3Prompt(req: Tier3Request): { system: string; user: string } {+ const { header, separator } = headerOf(req);+ const defaults = Object.entries(COLUMN_DEFAULTS[req.kind]);+ const system = [+ `You repair one malformed markdown table from a gbrain ${req.kind} fence. You move cells into the right columns and supply the canonical header; you never change what a cell says.`,+ '',+ 'Return exactly one markdown table and nothing else: no prose, no explanation, no code fence.',+ 'The table starts with this header and separator, unchanged:',+ header,+ separator,+ 'Then one row per input row, in the same order. Do not add, drop, merge, split or reorder rows.',+ '',+ 'Rules:',+ '1. Copy every cell exactly as written: same words, spelling, case, punctuation, links, numbers, dates and ~~strikethrough~~. Only its column may change.',+ '2. The claim cell of each output row is the claim of the matching input row, unchanged.',+ '3. Keep each row number in the # column. If an input row has none, leave # empty.',+ `4. Put each cell in the column its content belongs to. A column with no matching input cell stays empty${defaults.length+ ? `, except a column the input header lacks entirely, which takes its default: ${defaults.map(([column, value]) => `${column} ${value}`).join(', ')}` : ''}.`,+ '5. Never invent, translate, summarize or correct a value. A cell you cannot place goes in the column it was written under.',+ `6. This page is ${req.pageVisibility}-visible. A row's visibility may be world only when that row already says world or public and the page is world-visible; otherwise keep what the row says or leave it empty.`,+ '7. Write a literal | inside a cell as \\|.',+ '',+ 'Allowed values per column:',+ vocabulary(req.kind),+ ].join('\n');+ const user = [+ `Fence: ${req.kind} (${req.section} section). Page visibility: ${req.pageVisibility}.`,+ 'Problems found (reason codes, with row numbers where known):',+ ...req.issues.map(issue => `- ${issue.reason}${issue.rows.length ? `: row(s) ${issue.rows.join(', ')}` : ''}`),+ '',+ 'Header as written:',+ req.header ?? '(none)',+ '',+ `Rows as written (${req.rows.length}):`,+ ...req.rows.map(row => row.text),+ ].join('\n');+ return { system, user };+}++/** The follow-up after a gate rejection: the gate letter, its reason code and row numbers only. */+export function correctionMessage(gate: GateLetter, rows: readonly number[]): string {+ return `Your table was rejected by validation gate (${gate}) ${GATE_REASONS[gate]}${rows.length ? ` at row(s) ${rows.join(', ')}` : ''}: ${GATE_TEXT[gate]}. `+ + 'Return the corrected full table following every rule above. Output only the table.';+}++/** Token bounds for one call: the prompt's size and an output ceiling sized from the rows sent. */+export function tier3TokenBudget(req: Tier3Request, prior?: { answer: string }): { inputTokens: number; maxOutputTokens: number } {+ const prompt = buildTier3Prompt(req);+ const rowChars = req.rows.reduce((sum, row) => sum + row.text.length, 0) + headerOf(req).header.length * 2;+ const inputChars = prompt.system.length + prompt.user.length + (prior ? prior.answer.length + 400 : 0);+ return { inputTokens: Math.ceil(inputChars / 3) + 64, maxOutputTokens: Math.min(4096, Math.max(512, Math.ceil(rowChars * 1.5 / 3) + 256)) };+}++export interface Tier3Table { header: string; separator: string; rows: string[] }++const REFUSAL = /\b(cannot|can['’]t|unable to|won['’]t|will not|refuse|not able to)\b/i;++/**+ * The single table in a model answer, or why there is none. A single+ * wrapping code fence is stripped; any other non-table line is prose.+ */+export function extractSingleTable(text: string, req: Pick<Tier3Request, 'kind' | 'layout'>): { ok: true; table: Tier3Table } | { ok: false; reason: 'llm_empty' | 'llm_refused' | 'llm_malformed' } {+ let body = text.trim();+ if (!body) return { ok: false, reason: 'llm_empty' };+ const fenced = /^```[\w-]*\n([\s\S]*?)\n```$/.exec(body);+ if (fenced) body = fenced[1]!.trim();+ const lines = body.split('\n').map(line => line.trim()).filter(Boolean);+ if (!lines.some(line => line.startsWith('|'))) return { ok: false, reason: REFUSAL.test(body) ? 'llm_refused' : 'llm_malformed' };+ if (lines.some(line => !line.startsWith('|')) || lines.length < 2) return { ok: false, reason: 'llm_malformed' };+ const headerCells = parseRowCells(lines[0]!)?.map(cell => cell.trim().toLowerCase()).join('|');+ const sepCells = parseRowCells(lines[1]!);+ const layout = (['narrow', 'wide'] as const).find(width => headerCells === COLUMNS[req.kind].slice(0, width === 'wide' ? COLUMNS[req.kind].length : BASE_WIDTH[req.kind]).join('|'));+ if (!layout || !sepCells || !isSeparatorRow(sepCells)) return { ok: false, reason: 'llm_malformed' };+ const rows = lines.slice(2);+ if (rows.some(row => parseRowCells(row) === null || isSeparatorRow(parseRowCells(row)!))) return { ok: false, reason: 'llm_malformed' };+ const { header, separator } = headerOf({ kind: req.kind, layout });+ return { ok: true, table: { header, separator, rows } };+}++/**+ * The page with one request's fence rebuilt from the model's table: the+ * canonical header and separator, then every data row in fence order, the+ * sent rows replaced by the answer's rows in order. Everything outside the+ * fence region is unchanged. Null when the answer's row count differs.+ */+export function spliceTier3<T extends FencePage>(page: T, req: Tier3Request, table: Tier3Table): T | null {+ if (table.rows.length !== req.rows.length) return null;+ const field = req.section === 'body' ? 'compiled_truth' : 'timeline';+ const text = (page[field] ?? '') as string;+ const fence = primaryFence(extractRawRows(text, req.section), req.kind);+ if (!fence?.end) return null;+ const answers = new Map(req.rows.map((row, i) => [row.occurrence, table.rows[i]!]));+ const lines = [table.header, table.separator, ...fence.rows.map((row: RawRow) => answers.get(row.occurrence) ?? text.slice(row.start, row.end))];+ const rebuilt = `${text.slice(0, fence.begin.end)}\n${lines.join('\n')}\n${text.slice(fence.end.start)}`;+ return { ...page, [field]: rebuilt };+}++export type Tier3Answer =+ | { ok: true; table: Tier3Table; text: string; result: ChatResult }+ | { ok: false; reason: Tier3Failure; text?: string; result?: ChatResult; error?: string }+ /** The answer parsed but has the wrong number of rows: a gate (e) failure, eligible for the corrective re-ask. */+ | { ok: false; reason: 'row_count_changed'; text: string; result: ChatResult; table: Tier3Table };++export interface Tier3CallOptions {+ model: string;+ /** The first attempt's answer and the gate it failed, for the corrective re-ask. */+ correction?: { answer: string; gate: GateLetter; rows: readonly number[] };+ timeoutMs?: number;+ signal?: AbortSignal;+}++/** One gateway call (no tools, no fallback model, temperature 0), classified. */+export async function callTier3(req: Tier3Request, opts: Tier3CallOptions): Promise<Tier3Answer> {+ const prompt = buildTier3Prompt(req);+ const messages: ChatMessage[] = [{ role: 'user', content: prompt.user }];+ if (opts.correction) messages.push({ role: 'assistant', content: opts.correction.answer }, { role: 'user', content: correctionMessage(opts.correction.gate, opts.correction.rows) });+ const budget = tier3TokenBudget(req, opts.correction ? { answer: opts.correction.answer } : undefined);+ let result: ChatResult;+ try {+ result = await chat({ model: opts.model, system: prompt.system, messages, maxTokens: budget.maxOutputTokens, temperature: 0, allowFallback: false,+ thinking: 'off', purpose: 'fence_repair', ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}), ...(opts.signal ? { abortSignal: opts.signal } : {}) });+ } catch (error) {+ return { ok: false, reason: 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };+ }+ if (result.stopReason === 'refusal' || result.stopReason === 'content_filter') return { ok: false, reason: 'llm_refused', text: result.text, result };+ if (result.stopReason !== 'end') return { ok: false, reason: result.text.trim() ? 'llm_truncated' : 'llm_empty', text: result.text, result };+ const extracted = extractSingleTable(result.text, req);+ if (!extracted.ok) return { ok: false, reason: extracted.reason, text: result.text, result };+ if (extracted.table.rows.length !== req.rows.length) return { ok: false, reason: 'row_count_changed', text: result.text, result, table: extracted.table };+ return { ok: true, table: extracted.table, text: result.text, result };+}diff --git a/src/core/fence-repair/repair-io.ts b/src/core/fence-repair/repair-io.tsnew file mode 100644index 0000000000..7308e75285--- /dev/null+++ b/src/core/fence-repair/repair-io.ts@@ -0,0 +1,302 @@+/**+ * #6188 fence repair I/O: which sources this host may repair, reading one+ * candidate's current bytes, and the four write-back paths.+ *+ * Sources. On a managed brain a source with a canonical checkout is repaired+ * only on its active owner host (`owner_unavailable` elsewhere), and never+ * while its managed sync cursor is unfinished or a queued or running write+ * names the candidate (`sync_in_progress`, E9). A legacy (unmanaged) source+ * writes its recorded checkout. A read-only mirror is repaired in the+ * database only.+ *+ * Write-back (spec section 12 step 7):+ * - managed: `managed_file_repair` writes the exact repaired bytes bound to+ * the before-hash and page revision, imports them, clears the hold and+ * commits through the Git effect (subject from the receipt's classes);+ * - legacy (T2): the confined path is re-read and must still hash to the+ * read bytes (`changed_since_read`), is backed up, written, imported+ * (restored from the backup if the import refuses) and an "uncommitted+ * fence repair" notice records the commit step;+ * - db: a revision-bound put_page of the page with its repaired sections;+ * - mirror: the same put_page (database-only by the mirror rule), and the+ * path's hold is cleared.+ * Every write carries the location-only receipt (actor fence-repair).+ */+import { copyFileSync, existsSync, lstatSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import type { BrainEngine } from '../engine.ts';+import { OperationError, type OperationContext } from '../ops/contract.ts';+import { gbrainPath } from '../config.ts';+import { createFrontmatterBackup, makeFrontmatterBackupRunId } from '../brain-writer.ts';+import { importFromFile } from '../import-file.ts';+import { screenFenceCtx } from '../import-screen.ts';+import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';+import { resolveSlugForPath } from '../sync.ts';+import { sha256 } from '../persistence/digest.ts';+import { localHostId } from '../persistence/identity.ts';+import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';+import { sourceMirrorReadOnly } from '../persistence/mirror-read-only.ts';+import { isSourceDbOnlySlug } from '../persistence/source-storage.ts';+import { confinedRepairTarget, prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';+import { clearGitHold, readGitHold, type GitHoldRecord } from '../persistence/sync-holds.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import { repairRequestId } from '../repair/core.ts';+import { clearCandidateParts } from './census-store.ts';+import { legacyCommitStep, recordUncommittedFenceRepair } from './uncommitted.ts';+import type { FenceRepairReceipt } from './receipt.ts';+import type { FenceCtx, FencePage } from './types.ts';++export type FenceRepairMode = 'managed' | 'legacy' | 'db' | 'mirror';++export interface FenceSource {+ id: string;+ incarnation: string;+ managed: boolean;+ mirror: boolean;+ /** The checkout this host reads and (unless a mirror) writes; null when the source has none here. */+ root: string | null;+ /** Managed brain: another host owns this source's checkout, or its owner is not active. */+ ownerElsewhere: boolean;+ /** Managed brain: a managed sync of this source has not finished (E9). */+ syncUnfinished: boolean;+ /** Paths and slugs a queued, running or recovering write of this source names. */+ busy: { paths: Set<string>; slugs: Set<string> };+ activePack?: Awaited<ReturnType<typeof repairScreenConfig>>['activePack'];+}++function inGit(root: string): boolean {+ try { execFileSync('git', ['-C', root, 'rev-parse', '--is-inside-work-tree'], { stdio: 'ignore' }); return true; } catch { return false; }+}++/** This host's view of one source for fence repair; null when the source is gone or archived. */+export async function loadFenceSource(engine: BrainEngine, sourceId: string): Promise<FenceSource | null> {+ const [row] = await engine.executeRaw<{ id: string; incarnation: string; local_path: string | null }>(+ 'SELECT id, incarnation::text AS incarnation, local_path FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);+ if (!row) return null;+ const managed = await managedPersistenceEnabled(engine);+ const mirror = await sourceMirrorReadOnly(engine, sourceId);+ let root: string | null = null;+ let ownerElsewhere = false;+ if (managed) {+ const binding = await getWorktreeBinding(engine, sourceId);+ if (binding) {+ if (binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) ownerElsewhere = true;+ else root = join(binding.local_path, binding.relative_path);+ }+ } else {+ const local = row.local_path ?? (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);+ root = local && existsSync(local) ? local : null;+ }+ const [cursor] = managed ? await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM op_checkpoints WHERE op='managed-sync'+ AND COALESCE(completed_keys->0->>'done','false')<>'true' AND completed_keys->0->>'sourceId'=$1`, [sourceId]) : [{ n: 0 }];+ const pending = await engine.executeRaw<{ slug: string; path: string | null; source_path: string | null }>(`SELECT slug, intent->>'path' AS path, intent->>'sourcePath' AS source_path+ FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')`, [sourceId]).catch(() => []);+ const config = await repairScreenConfig(engine, sourceId);+ return { id: row.id, incarnation: row.incarnation, managed, mirror, root, ownerElsewhere, syncUnfinished: Number(cursor?.n ?? 0) > 0,+ busy: { paths: new Set(pending.flatMap(p => [p.path, p.source_path].filter((v): v is string => !!v))), slugs: new Set(pending.map(p => p.slug)) },+ ...(config.activePack ? { activePack: config.activePack } : {}) };+}++/** One candidate's current bytes: a working-tree file, or a stored page. */+export interface FenceTarget {+ mode: FenceRepairMode;+ sourceId: string;+ /** The census key (page slug, or `path:<file>`). */+ key: string;+ slug: string;+ path: string | null;+ sourcePath: string | null;+ page: FencePage;+ /** The file's text (file targets). */+ content: string | null;+ /** sha256 of the file bytes, or of the page's two sections. */+ before: string;+ snapshot: PageSnapshot | null;+ hold: GitHoldRecord | null;+ ctx: FenceCtx;+}++/** sha256 a stored page's fence sections are bound by (the census uses the same). */+export function pageSha(page: FencePage): string {+ return sha256(`${page.compiled_truth ?? ''}\u0000${page.timeline ?? ''}`);+}++export type TargetRead = { ok: true; target: FenceTarget } | { ok: false; reason: 'gone' | 'not_utf8' | 'unsafe_path' };++/** Reads a candidate as it is now. A held or walked file is read from the checkout; anything else is read from the page store. */+export async function readFenceTarget(engine: BrainEngine, src: FenceSource, cand: { key: string; path: string | null }): Promise<TargetRead> {+ const hold = cand.path ? await readGitHold(engine, src.id, src.incarnation, cand.path) : null;+ const holdSlug = hold?.slug ?? (cand.key.startsWith('path:') ? null : cand.key);+ if (cand.path && src.root) {+ const abs = join(src.root, cand.path);+ if (existsSync(abs)) {+ try { confinedRepairTarget(src.root, cand.path, src.id); } catch (error) {+ if (error instanceof OperationError) return { ok: false, reason: 'unsafe_path' };+ throw error;+ }+ const bytes = readFileSync(abs);+ const content = bytes.toString('utf8');+ if (!Buffer.from(content, 'utf8').equals(bytes)) return { ok: false, reason: 'not_utf8' };+ const sourcePath = hold?.source_path ?? cand.path;+ const [byOrigin] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2 AND deleted_at IS NULL LIMIT 1', [src.id, sourcePath]);+ const slug = byOrigin?.slug ?? holdSlug ?? resolveSlugForPath(sourcePath);+ const dbOnly = src.managed && isSourceDbOnlySlug(src.root, slug, 'not_db_only');+ if (!dbOnly) {+ const parsed = parseMarkdown(content, cand.path, src.activePack ? { activePack: src.activePack } : undefined);+ return { ok: true, target: { mode: src.mirror ? 'mirror' : src.managed ? 'managed' : 'legacy', sourceId: src.id, key: cand.key, slug, path: cand.path, sourcePath,+ page: { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline ?? '' }, content, before: sha256(bytes),+ snapshot: await engine.readPageSnapshot(slug, { sourceId: src.id, includeDeleted: true }), hold, ctx: screenFenceCtx(parsed, src.activePack) } };+ }+ }+ }+ const slug = holdSlug;+ const snapshot = slug ? await engine.readPageSnapshot(slug, { sourceId: src.id }) : null;+ if (!snapshot || snapshot.page.deleted_at) return { ok: false, reason: 'gone' };+ const page = { compiled_truth: snapshot.page.compiled_truth ?? '', timeline: snapshot.page.timeline ?? '' };+ return { ok: true, target: { mode: src.mirror ? 'mirror' : 'db', sourceId: src.id, key: cand.key, slug: snapshot.page.slug, path: null,+ sourcePath: snapshot.page.source_path ?? null, page, content: null, before: pageSha(page), snapshot, hold,+ ctx: screenFenceCtx({ type: snapshot.page.type as never, frontmatter: (snapshot.page.frontmatter ?? {}) as Record<string, unknown> }, src.activePack) } };+}++function indexesOf(lines: readonly string[], needle: readonly string[]): number[] {+ const hits: number[] = [];+ for (let i = 0; i + needle.length <= lines.length; i++) {+ let match = true;+ for (let j = 0; j < needle.length && match; j++) match = lines[i + j] === needle[j];+ if (match) hits.push(i);+ }+ return hits;+}++/**+ * The file with each repaired section spliced back in place: per section the+ * changed line range (common prefix and suffix kept), located in the file by+ * that range plus the fewest context lines that make it unique. Null when+ * the range cannot be located once, or when the result does not parse back+ * to exactly the repaired sections.+ */+export function spliceFileSections(content: string, path: string, before: FencePage, after: FencePage): string | null {+ let lines = content.split('\n');+ for (const field of ['compiled_truth', 'timeline'] as const) {+ if ((before[field] ?? '') === (after[field] ?? '')) continue;+ const b = (before[field] ?? '').split('\n');+ const a = (after[field] ?? '').split('\n');+ let head = 0;+ while (head < b.length && head < a.length && b[head] === a[head]) head++;+ let tail = 0;+ while (tail < b.length - head && tail < a.length - head && b[b.length - 1 - tail] === a[a.length - 1 - tail]) tail++;+ const removed = b.slice(head, b.length - tail);+ const added = a.slice(head, a.length - tail);+ let placed = false;+ for (let k = 0; !placed; k++) {+ const pre = b.slice(Math.max(0, head - k), head);+ const post = b.slice(b.length - tail, Math.min(b.length, b.length - tail + k));+ const needle = [...pre, ...removed, ...post];+ const hits = needle.length ? indexesOf(lines, needle) : [];+ if (hits.length === 1) {+ lines = [...lines.slice(0, hits[0]! + pre.length), ...added, ...lines.slice(hits[0]! + pre.length + removed.length)];+ placed = true;+ } else if (!hits.length && needle.length) return null;+ else if (head - k <= 0 && b.length - tail + k >= b.length) return null;+ }+ }+ const out = lines.join('\n');+ const parsed = parseMarkdown(out, path);+ if (parsed.compiled_truth.trim() !== (after.compiled_truth ?? '').trim() || (parsed.timeline ?? '').trim() !== (after.timeline ?? '').trim()) return null;+ return out;+}++export type WriteOutcome =+ | { ok: true; detail: Record<string, unknown>; after_sha256: string }+ | { ok: false; reason: string; message: string };++/** The receipt fields the writer completes (hashes) from what the caller decided (tier, classes, model, spend). */+export type ReceiptParts = Omit<FenceRepairReceipt, 'before_sha256' | 'after_sha256'>;++/** Writes one repaired candidate through its mode's path. Trusted local callers only (the caller checks `ctx.remote === false`). */+export async function writeFenceRepair(ctx: OperationContext, src: FenceSource, target: FenceTarget, after: FencePage, parts: ReceiptParts, opts: { embed: boolean }): Promise<WriteOutcome> {+ const engine = ctx.engine;+ const local = { ...ctx, remote: false, sourceId: src.id } as OperationContext;+ const clearCensus = async () => {+ await clearCandidateParts(engine, { sourceId: src.id, incarnation: src.incarnation }, 'page', [target.key]);+ await clearCandidateParts(engine, { sourceId: src.id, incarnation: src.incarnation }, 'file', [target.key]);+ };+ const fileContent = target.content !== null && target.path ? spliceFileSections(target.content, target.path, target.page, after) : null;+ if (target.content !== null && fileContent === null) {+ return { ok: false, reason: 'unparseable', message: `gbrain could not place the repaired fence back into ${target.path}; edit the fence there by hand.` };+ }+ if (target.mode === 'managed') {+ const receipt: FenceRepairReceipt = { ...parts, before_sha256: target.before, after_sha256: sha256(Buffer.from(fileContent!, 'utf8')) };+ const config = await repairScreenConfig(engine, src.id);+ const publication = await prepareRepairPublication(engine, { sourceId: src.id, slug: target.slug, sourcePath: target.sourcePath!, path: target.path!, root: src.root!,+ content: fileContent!, snapshot: target.snapshot, base: target.snapshot, ...config });+ if (publication.status === 'refused') return { ok: false, reason: publication.refusal.code === 'invalid_fence' ? 'still_invalid' : publication.refusal.code,+ message: `Importing the repaired ${target.path} would be refused (${publication.refusal.code}), so nothing was written.` };+ if (publication.status === 'overlay') return { ok: false, reason: 'canonical_overlay',+ message: `Importing the repaired ${target.path} would keep page data the file does not carry (tags added outside the file, a withdrawal or sanitized text), so nothing was written. Edit the fence in the file by hand.` };+ try {+ const outcome = await submitManagedFileRepair(local, { sourceId: src.id,+ requestId: await repairRequestId(local, 'fences', { source_id: src.id, slug: target.slug }, `${receipt.before_sha256}:${receipt.after_sha256}`),+ slug: target.slug, path: target.path!, sourcePath: target.sourcePath!, content: fileContent!, beforeHash: target.before, resultDigest: publication.digest,+ ...(target.snapshot && !target.snapshot.page.deleted_at ? { expected_revision: target.snapshot.revision } : {}), noEmbed: !opts.embed, fenceRepair: receipt } as Parameters<typeof submitManagedFileRepair>[1]);+ await clearCensus();+ const persistence = outcome.persistence as { git_state?: string } | undefined;+ return { ok: true, after_sha256: receipt.after_sha256, detail: { mode: 'managed', path: target.path, imported: outcome.status, hold_cleared: outcome.hold_cleared === true,+ committed: persistence?.git_state ?? 'not_requested' } };+ } catch (error) {+ if (error instanceof OperationError && ['changed_since_preview', 'revision_conflict', 'page_identity_changed', 'source_changed'].includes(error.code)) {+ return { ok: false, reason: 'changed_since_read', message: `${target.path} changed while it was being repaired; the next run reads it again.` };+ }+ throw error;+ }+ }+ if (target.mode === 'legacy') {+ const root = src.root!;+ let abs: string;+ try { abs = confinedRepairTarget(root, target.path!, src.id); } catch (error) {+ if (error instanceof OperationError) return { ok: false, reason: 'unsafe_path', message: `${target.path} is a symlink, sits under one, or resolves outside the source root; gbrain never writes through one.` };+ throw error;+ }+ if (sha256(readFileSync(abs)) !== target.before) return { ok: false, reason: 'changed_since_read', message: `${target.path} changed after the repair read it, so nothing was written.` };+ const receipt: FenceRepairReceipt = { ...parts, before_sha256: target.before, after_sha256: sha256(Buffer.from(fileContent!, 'utf8')) };+ const backup = createFrontmatterBackup(abs, { sourcePath: root, backupRoot: gbrainPath('backups', 'fences', makeFrontmatterBackupRunId()) });+ writeFileSync(abs, fileContent!);+ const imported = await importFromFile(engine, abs, target.sourcePath ?? target.path!, { sourceId: src.id, noEmbed: !opts.embed });+ if (imported.status === 'error' || imported.refusal) {+ copyFileSync(backup, abs);+ return { ok: false, reason: 'still_invalid', message: `The repaired ${target.path} did not import (${imported.refusal?.code ?? 'error'}), so the file was restored from its backup.` };+ }+ if (target.hold) await clearGitHold(engine, { sourceId: src.id, incarnation: src.incarnation, path: target.path!, observedAt: new Date().toISOString() });+ await clearCensus();+ const commitStep = inGit(root) ? legacyCommitStep(root, target.path!, receipt.classes) : null;+ if (commitStep) await recordUncommittedFenceRepair(engine, { source_id: src.id, incarnation: src.incarnation, path: target.path!, root, repaired_at: new Date().toISOString(),+ backup, commit_step: commitStep, receipt });+ return { ok: true, after_sha256: receipt.after_sha256, detail: { mode: 'legacy', path: target.path, backup, imported: imported.status, fence_repair: receipt,+ ...(commitStep ? { committed: 'commit_step', commit_step: commitStep } : { committed: 'not_in_git' }) } };+ }+ const snapshot = target.snapshot;+ const content = fileContent ?? (snapshot ? serializePageToMarkdown({ ...snapshot.page, compiled_truth: after.compiled_truth, timeline: after.timeline }, snapshot.tags) : null);+ if (content === null) return { ok: false, reason: 'changed_since_read', message: `${target.slug} is gone.` };+ const receipt: FenceRepairReceipt = { ...parts, before_sha256: target.before, after_sha256: fileContent !== null ? sha256(Buffer.from(fileContent, 'utf8')) : pageSha(after) };+ try {+ const outcome = await submitPageMutation(local, { operation: 'put_page', params: { slug: target.slug, source_id: src.id, content,+ ...(snapshot && !snapshot.page.deleted_at ? { expected_revision: snapshot.revision } : {}),+ request_id: await repairRequestId(local, 'fences', { source_id: src.id, slug: target.slug }, `${receipt.before_sha256}:${receipt.after_sha256}`), fence_repair: receipt } });+ if (target.mode === 'mirror' && target.hold) await clearGitHold(engine, { sourceId: src.id, incarnation: src.incarnation, path: target.hold.path, observedAt: new Date().toISOString() });+ await clearCensus();+ return { ok: true, after_sha256: receipt.after_sha256, detail: { mode: target.mode, slug: target.slug, ...(target.path ? { path: target.path } : {}), status: outcome.status,+ ...(target.mode === 'mirror' ? { storage: 'database_only' } : {}) } };+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'changed_since_preview', 'source_changed'].includes(error.code)) {+ return { ok: false, reason: 'changed_since_read', message: `${target.slug} changed while it was being repaired; the next run reads it again.` };+ }+ throw error;+ }+}++/** True when the path is a regular file in the checkout (not a link). */+export function checkoutFileExists(root: string, path: string): boolean {+ try { return lstatSync(join(root, path)).isFile(); } catch { return false; }+}diff --git a/src/core/fence-repair/repair-tiers.ts b/src/core/fence-repair/repair-tiers.tsnew file mode 100644index 0000000000..828aaf5ff8--- /dev/null+++ b/src/core/fence-repair/repair-tiers.ts@@ -0,0 +1,265 @@+/**+ * #6188 fence repair tiers for one candidate: the free tiers (Tier 1 rules,+ * Tier 2 verified holders) decide a proposal or what is left, and Tier 3 (the+ * chat model) runs only for residual rows a model can realign, under the+ * per-page cap, the daily USD ledger and the attempt memo.+ *+ * Tier 2 (E12): each `holder_unresolved` cell is looked up with+ * `resolveStrictEntityReference` (no same-name arm), accepting only a+ * `people/` or `companies/` page, with private pages excluded on a world+ * page. A miss stays residual and, being manual-only after Tier 2, is never+ * sent to the model.+ *+ * Every proposal, whichever tier made it, passes `validateFenceRepair`+ * gates (a)-(g) against the bytes as read and is a Tier 1 fixed point (a+ * model answer that is not is normalized once and checked again, E14).+ * Messages and stored verdicts carry reason codes, gate letters and row+ * numbers only.+ */+import type { BrainEngine } from '../engine.ts';+import { resolveStrictEntityReference } from '../entities/resolve.ts';+import { chatCallUsd, estimateChatCallUsd, type DailyLedger } from '../budget/daily-ledger.ts';+import type { PricingOverrides } from '../budget/reservation-cost.ts';+import type { NoPricingGuidance } from '../budget/no-pricing.ts';+import type { CapSource } from '../consent.ts';+import { attemptMemoKey, type AttemptClaim, type AttemptStore } from './attempts.ts';+import { storedFenceRows } from './import-step.ts';+import { safeNormalizeFences, FENCE_RULES_VERSION } from './normalize.ts';+import { extractRawRows } from './raw-rows.ts';+import { scanCanonicalFences } from './refusal.ts';+import { GATE_REASONS, renderFenceFix, type FenceMessageLocation } from './reasons.ts';+import { residualLocation } from './tier1.ts';+import { validateFenceRepair } from './validate.ts';+import { callTier3, FENCE_REPAIR_PROMPT_VERSION, spliceTier3, tier3Requests, tier3TokenBudget, TIER3_REASONS, type Tier3Request, type Tier3Table } from './llm.ts';+import type { FenceCtx, FenceFix, FenceIssue, FencePage, FenceReason, GateLetter } from './types.ts';+import type { FenceTarget } from './repair-io.ts';++export type FenceAnalysis =+ | { status: 'clean' }+ | { status: 'proposal'; tier: 'deterministic' | 'resolver'; after: FencePage; fixes: FenceFix[]; ctx: FenceCtx }+ | { status: 'llm'; base: FencePage; fixes: FenceFix[]; residual: FenceIssue[]; requests: Tier3Request[]; ctx: FenceCtx }+ | { status: 'manual'; reason: FenceReason; location: FenceMessageLocation; resolution: string; gate?: GateLetter; rows?: number[] };++/** The holder text of the row an issue names, read from the bytes as written. */+function holderAt(page: FencePage, issue: FenceIssue): string | null {+ const text = issue.section === 'body' ? page.compiled_truth : page.timeline;+ for (const fence of extractRawRows(text ?? '', issue.section).fences) {+ if (fence.kind !== issue.fence) continue;+ const row = fence.rows.find(r => r.line === issue.line);+ const who = row?.byColumn.get('who')?.text.trim();+ if (who) return who;+ }+ return null;+}++/** Tier 2: the verified `people/` / `companies/` slug for each unresolved holder text that resolves strictly. */+async function verifyHolders(engine: BrainEngine, sourceId: string, page: FencePage, issues: readonly FenceIssue[], ctx: FenceCtx): Promise<Map<string, string>> {+ const verified = new Map<string, string>();+ const texts = new Set(issues.filter(i => i.reason === 'holder_unresolved').map(i => holderAt(page, i)).filter((t): t is string => !!t));+ for (const text of texts) {+ const found = await resolveStrictEntityReference(engine, sourceId, text, { excludePrivate: ctx.pageVisibility === 'world' });+ if (found.slug && /^(people|companies)\//.test(found.slug)) verified.set(text, found.slug);+ }+ return verified;+}++function manual(issues: readonly FenceIssue[], extra: { gate?: GateLetter; rows?: number[]; reason?: FenceReason } = {}): FenceAnalysis {+ const location = residualLocation(issues);+ const at = extra.reason ? { ...location, reason: extra.reason, rows: extra.rows ?? location.rows } : location;+ return { status: 'manual', reason: at.reason, location: at, resolution: renderFenceFix(at), ...(extra.gate ? { gate: extra.gate } : {}), ...(extra.rows ? { rows: extra.rows } : {}) };+}++/** A page whose output is a Tier 1 fixed point that compiles. */+function settled(page: FencePage, ctx: FenceCtx): boolean {+ const again = safeNormalizeFences(page, ctx);+ return !again.fixes.length && !again.residual.length && !scanCanonicalFences(page).defects.length;+}++/**+ * The free tiers over a candidate's current bytes: `clean` (nothing to do),+ * a validated `proposal`, `llm` (only Tier 3 residuals are left, with the+ * model requests), or `manual` with the exact location-only edit.+ */+export async function analyzeFences(engine: BrainEngine, target: FenceTarget, opts: { pageId: number | null }): Promise<FenceAnalysis> {+ const page = target.page;+ if (!scanCanonicalFences(page).defects.length) return { status: 'clean' };+ let ctx: FenceCtx = { ...target.ctx };+ let base = safeNormalizeFences(page, ctx);+ if (base.fixes.some(f => f.class === 'renumber')) {+ ctx = { ...ctx, storedRows: await storedFenceRows(engine, target.sourceId, target.slug, opts.pageId) };+ base = safeNormalizeFences(page, ctx);+ }+ let tier: 'deterministic' | 'resolver' = 'deterministic';+ if (base.residual.some(i => i.reason === 'holder_unresolved')) {+ const verified = await verifyHolders(engine, target.sourceId, page, base.residual, ctx);+ if (verified.size) {+ ctx = { ...ctx, verifiedHolders: verified };+ base = safeNormalizeFences(page, ctx);+ tier = 'resolver';+ }+ }+ if (!base.residual.length) {+ if (!base.fixes.length) return manual([{ row: null, column: null, ...scanIssue(page) }]);+ const verdict = validateFenceRepair(page, base.page, { ...ctx, tier, issues: base.fixes });+ if (!verdict.ok) return manual(base.fixes.map(f => ({ ...f, reason: verdict.reason })), { gate: verdict.gate, rows: verdict.rows, reason: verdict.reason });+ if (!settled(base.page, ctx)) return manual(base.fixes.map(f => ({ ...f, reason: 'normalizer_failed' as const })), { reason: 'normalizer_failed' });+ return { status: 'proposal', tier, after: base.page, fixes: base.fixes, ctx };+ }+ const manualIssues = base.residual.filter(i => !TIER3_REASONS.has(i.reason));+ if (manualIssues.length) return manual(manualIssues);+ const { requests, ineligible } = tier3Requests(base.page, base.residual, ctx.pageVisibility);+ if (ineligible.length || !requests.length) return manual(base.residual);+ return { status: 'llm', base: base.page, fixes: base.fixes, residual: base.residual, requests, ctx };+}++function scanIssue(page: FencePage): Pick<FenceIssue, 'fence' | 'section' | 'reason' | 'line'> {+ const defect = scanCanonicalFences(page).defects[0]!;+ return { fence: defect.fence, section: defect.section, reason: defect.reason, line: defect.line };+}++/** The first call's estimate for every request of a page (the per-page cap also covers one corrective re-ask). */+export function tier3Estimate(requests: readonly Tier3Request[], pricing: { model: string; overrides?: PricingOverrides; capSource: CapSource }):+ { ok: true; usd: number; estimated: boolean } | { ok: false; reason: 'no_pricing'; guidance: NoPricingGuidance } {+ let usd = 0;+ let estimated = false;+ for (const req of requests) {+ const budget = tier3TokenBudget(req);+ const quote = estimateChatCallUsd({ model: pricing.model, inputTokens: budget.inputTokens, maxOutputTokens: budget.maxOutputTokens, overrides: pricing.overrides, capSource: pricing.capSource });+ if (!quote.ok) return quote;+ usd += quote.quote.usd;+ estimated ||= quote.quote.estimated;+ }+ return { ok: true, usd, estimated };+}++export interface Tier3Deps {+ ledger: DailyLedger;+ store: AttemptStore;+ model: string;+ overrides?: PricingOverrides;+ capSource: CapSource;+ perPageUsd: number;+ perDayUsd: number;+ /** What is left of the run's own paid-model allowance (`--max-usd`, doctor); undefined = none. */+ allowanceUsd?: number;+ /** Per-call provider timeout. */+ timeoutMs: number;+ now: () => Date;+}++export type Tier3Outcome =+ | { ok: true; after: FencePage; spentUsd: number; claim: AttemptClaim; cleared: FenceReason[] }+ | { ok: false; reason: FenceReason | 'claimed_elsewhere'; spentUsd: number; message: string; gate?: GateLetter; rows?: number[];+ /** The whole run should stop (the daily ledger refused the call). */+ stop?: boolean; resetsAt?: string; memoHit?: boolean; guidance?: NoPricingGuidance };++/** The attempt-store candidate of a target: one per file path, else per page slug. */+export function attemptCandidate(target: FenceTarget, incarnation: string) {+ return { sourceId: target.sourceId, incarnation, key: target.path ? `path:${target.path}` : `slug:${target.slug}` };+}++export function tier3Memo(target: FenceTarget, model: string): string {+ return attemptMemoKey({ contentSha256: target.before, model, fenceVersion: FENCE_RULES_VERSION, promptVersion: FENCE_REPAIR_PROMPT_VERSION });+}++/**+ * Tier 3 for one candidate: claim the attempt (a rejected memo returns its+ * stored verdict and spends nothing), call the model per fence under the+ * ledger, splice, normalize, validate, and re-ask once with the failed gate.+ * On success the claim is left `settled`: the caller publishes it after the+ * write lands, or marks it transient when the write could not run.+ */+export async function runTier3(target: FenceTarget, analysis: Extract<FenceAnalysis, { status: 'llm' }>, incarnation: string, deps: Tier3Deps): Promise<Tier3Outcome> {+ const claimed = await deps.store.claim(attemptCandidate(target, incarnation), tier3Memo(target, deps.model));+ if (!claimed.ok) {+ if (claimed.reason === 'claimed_elsewhere') return { ok: false, reason: 'claimed_elsewhere', spentUsd: 0, message: 'Another repair run holds this candidate; it is left to that run.' };+ if (claimed.reason === 'store_unavailable') return { ok: false, reason: 'ledger_unavailable', spentUsd: 0, message: 'The repair attempt store could not be read, so no model call was made.' };+ const record = claimed.record;+ const reason = (record.reason ?? 'still_invalid') as FenceReason;+ return { ok: false, reason, spentUsd: 0, memoHit: true, ...(record.gate ? { gate: record.gate as GateLetter } : {}), ...(record.rows ? { rows: record.rows } : {}),+ message: `The model's repair of these exact bytes was already rejected (${reason}${record.gate ? `, gate ${record.gate}` : ''}); no new call is made until the file, the model or the rules change.` };+ }+ let claim = claimed.claim;+ let spent = 0;+ const tables = new Map<number, { table: Tier3Table; text: string }>();+ const transient = async (reason: FenceReason, message: string, extra: Partial<Extract<Tier3Outcome, { ok: false }>> = {}): Promise<Tier3Outcome> => {+ await deps.store.transient(claim, reason);+ return { ok: false, reason, spentUsd: spent, message, ...extra };+ };+ const reject = async (reason: FenceReason, message: string, gate?: GateLetter, rows?: number[]): Promise<Tier3Outcome> => {+ await deps.store.reject(claim, { reason, ...(gate ? { gate } : {}), ...(rows ? { rows } : {}) });+ return { ok: false, reason, spentUsd: spent, message, ...(gate ? { gate } : {}), ...(rows ? { rows } : {}) };+ };+ let correction: { index: number; gate: GateLetter; rows: number[] } | null = null;+ for (let round = 0; round < 2; round++) {+ const indexes = correction ? [correction.index] : analysis.requests.map((_, i) => i);+ for (const index of indexes) {+ const req = analysis.requests[index]!;+ const prior = correction ? tables.get(index)!.text : undefined;+ const budget = tier3TokenBudget(req, prior !== undefined ? { answer: prior } : undefined);+ const quote = estimateChatCallUsd({ model: deps.model, inputTokens: budget.inputTokens, maxOutputTokens: budget.maxOutputTokens, overrides: deps.overrides, capSource: deps.capSource });+ if (!quote.ok) return transient('no_pricing', `A spend cap is set but gbrain has no price for ${deps.model}; no call was made.`, { guidance: quote.guidance });+ const estimate = quote.quote.usd;+ if (spent + estimate > deps.perPageUsd + 1e-9) {+ if (correction) return reject(GATE_REASONS[correction.gate], `The model's repair failed gate ${correction.gate} and a corrective re-ask would exceed the per-page cap.`, correction.gate, correction.rows);+ return transient('budget_exhausted', `The estimated model cost ($${estimate.toFixed(4)}) exceeds fences.repair.max_usd_per_page ($${deps.perPageUsd.toFixed(2)}).`);+ }+ if (deps.allowanceUsd !== undefined && spent + estimate > deps.allowanceUsd + 1e-9) {+ if (correction) return reject(GATE_REASONS[correction.gate], `The model's repair failed gate ${correction.gate} and this run's allowance cannot cover a corrective re-ask.`, correction.gate, correction.rows);+ return transient('budget_exhausted', `This run's paid-model allowance ($${deps.allowanceUsd.toFixed(4)} left) cannot cover the estimate ($${estimate.toFixed(4)}).`, { stop: true });+ }+ const reserved = await deps.ledger.reserve(estimate, { capUsd: deps.perDayUsd });+ if (!reserved.ok) {+ if (reserved.reason === 'ledger_unavailable') return transient('ledger_unavailable', 'The spend ledger could not be read, so no model call was made; the next run retries.');+ return transient('budget_exhausted', `The daily fence-repair budget is spent ($${(reserved.committedUsd + reserved.reservedUsd).toFixed(4)} of $${reserved.capUsd.toFixed(2)} committed or reserved today; `+ + `this call needs $${reserved.estimateUsd.toFixed(4)}). It resets at ${reserved.resetsAt}.`, { stop: true, resetsAt: reserved.resetsAt });+ }+ const moved = await deps.store.dispatched(claim, reserved.reservation.id);+ if (!moved.ok) {+ await deps.ledger.release(reserved.reservation.id);+ if (moved.reason === 'lost_claim') return { ok: false, reason: 'claimed_elsewhere', spentUsd: spent, message: 'Another repair run took over this candidate.' };+ return reject(correction ? GATE_REASONS[correction.gate] : 'llm_malformed', 'The attempt reached its call limit.', correction?.gate, correction?.rows);+ }+ claim = moved.claim;+ if (!await deps.ledger.dispatch(reserved.reservation.id)) {+ await deps.ledger.release(reserved.reservation.id);+ await deps.store.settled(claim).then(r => { if (r.ok) claim = r.claim; });+ return transient('ledger_unavailable', 'The spend ledger refused to dispatch the reservation, so no model call was made.');+ }+ const answer = await callTier3(req, { model: deps.model, timeoutMs: deps.timeoutMs, ...(correction ? { correction: { answer: prior!, gate: correction.gate, rows: correction.rows } } : {}) });+ const actual = answer.result ? chatCallUsd(deps.model, { inputTokens: answer.result.usage.input_tokens, outputTokens: answer.result.usage.output_tokens }, deps.overrides).usd : estimate;+ const settle = await deps.ledger.settle(reserved.reservation.id, actual);+ spent += settle.settled ? settle.actualUsd : actual;+ const done = await deps.store.settled(claim);+ if (done.ok) claim = done.claim;+ if (!answer.ok && answer.reason === 'llm_unavailable') return transient('llm_unavailable', `The repair model was unavailable (${answer.error ?? 'provider error'}); the next run retries.`);+ if (!answer.ok && answer.reason !== 'row_count_changed') return reject(answer.reason, `The repair model's answer was unusable (${answer.reason}).`);+ tables.set(index, { table: answer.table, text: answer.text });+ }+ let current: FencePage | null = analysis.base;+ for (const [index, req] of analysis.requests.entries()) current = current && spliceTier3(current, req, tables.get(index)!.table);+ let failure: { gate: GateLetter; rows: number[]; index: number } | null = null;+ let after: FencePage | null = null;+ if (!current) {+ const index = analysis.requests.findIndex((req, i) => tables.get(i)!.table.rows.length !== req.rows.length);+ failure = { gate: 'e', rows: [], index: Math.max(0, index) };+ } else {+ const final = safeNormalizeFences(current, analysis.ctx);+ const verdict = final.residual.length ? { ok: false as const, gate: 'a' as GateLetter, rows: final.residual.flatMap(i => i.row === null ? [] : [i.row]), fence: final.residual[0]!.fence, section: final.residual[0]!.section }+ : validateFenceRepair(target.page, final.page, { ...analysis.ctx, tier: 'llm', issues: [...analysis.fixes, ...analysis.residual] });+ if (verdict.ok && settled(final.page, analysis.ctx)) after = final.page;+ else {+ const v = verdict.ok ? { gate: 'a' as GateLetter, rows: [] as number[], fence: null, section: null } : verdict;+ const index = analysis.requests.findIndex(req => req.kind === v.fence && req.section === v.section);+ failure = { gate: v.gate, rows: v.rows, index: index < 0 ? 0 : index };+ }+ }+ if (after) {+ const cleared = [...new Set(analysis.residual.map(i => i.reason))].sort();+ return { ok: true, after, spentUsd: spent, claim, cleared };+ }+ if (round === 0) { correction = failure; continue; }+ return reject(GATE_REASONS[failure!.gate], `LLM repair rejected by gate ${failure!.gate}; needs a manual edit${failure!.rows.length ? ` at row(s) ${failure!.rows.join(', ')}` : ''}.`, failure!.gate, failure!.rows);+ }+ return reject('still_invalid', 'LLM repair did not settle.');+}diff --git a/src/core/fence-repair/uncommitted.ts b/src/core/fence-repair/uncommitted.tsnew file mode 100644index 0000000000..64924942b9--- /dev/null+++ b/src/core/fence-repair/uncommitted.ts@@ -0,0 +1,77 @@+/**+ * #6188 (T2): "uncommitted fence repair" notices. A legacy (unmanaged)+ * source has no Git effect, so when the fence repair rewrites one of its+ * files it backs the file up, imports it, and records a notice here naming+ * the path, the backup and the exact `git add` / `git commit` step. The+ * notice stays until that path is committed: every read checks+ * `git status --porcelain -- <path>` and drops the notices whose path is+ * clean. `gbrain sources status` and doctor `fence_integrity` show them.+ *+ * One row per (source, incarnation, path) in `op_checkpoints`+ * (`fence-repair-uncommitted`); the record carries source_id and+ * incarnation, so the checkpoint purge keeps it while the source lives.+ * Location, hashes and the fix classes only, never a cell value.+ */+import { execFileSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import type { BrainEngine } from '../engine.ts';+import { shellQuote } from '../agent-output.ts';+import type { FenceRepairReceipt } from './receipt.ts';+import { fenceRepairCommitSubject } from './receipt.ts';++type Exec = Pick<BrainEngine, 'executeRaw'>;++export const FENCE_UNCOMMITTED_OP = 'fence-repair-uncommitted';++export interface UncommittedFenceRepair {+ source_id: string;+ incarnation: string;+ path: string;+ root: string;+ repaired_at: string;+ backup: string | null;+ /** The exact command that commits the repaired file. */+ commit_step: string;+ receipt: FenceRepairReceipt;+}++const fingerprint = (sourceId: string, incarnation: string, path: string) => `${sourceId}:${incarnation}:${path}`;++/** The commit step printed for a legacy repair: stage only this path and commit it with the fence-repair subject. */+export function legacyCommitStep(root: string, path: string, classes: readonly string[]): string {+ return `git -C ${shellQuote([root])} add -- ${shellQuote([path])} && git -C ${shellQuote([root])} commit -m ${shellQuote([fenceRepairCommitSubject(path, classes)])} -- ${shellQuote([path])}`;+}++export async function recordUncommittedFenceRepair(engine: Exec, notice: UncommittedFenceRepair): Promise<void> {+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,+ [FENCE_UNCOMMITTED_OP, fingerprint(notice.source_id, notice.incarnation, notice.path), JSON.stringify([notice])]);+}++/** True when the path has no uncommitted change in its checkout (a path outside Git is never "committed"). */+function committed(root: string, path: string): boolean {+ if (!existsSync(root)) return true;+ try {+ const status = execFileSync('git', ['-C', root, 'status', '--porcelain', '--untracked-files=all', '--', path], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });+ if (status.trim()) return false;+ execFileSync('git', ['-C', root, 'ls-files', '--error-unmatch', '--', path], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+}++/** Outstanding notices of the scoped sources (all when unscoped); a notice whose path is now committed is dropped on read. */+export async function readUncommittedFenceRepairs(engine: Exec, sourceIds?: readonly string[]): Promise<UncommittedFenceRepair[]> {+ const rows = await engine.executeRaw<{ fingerprint: string; record: UncommittedFenceRepair }>(`SELECT fingerprint, completed_keys->0 AS record FROM op_checkpoints+ WHERE op=$1 AND ($2::text[] IS NULL OR completed_keys->0->>'source_id'=ANY($2::text[])) ORDER BY fingerprint`, [FENCE_UNCOMMITTED_OP, sourceIds ? [...sourceIds] : null]);+ const out: UncommittedFenceRepair[] = [];+ for (const row of rows) {+ if (committed(row.record.root, row.record.path)) {+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [FENCE_UNCOMMITTED_OP, row.fingerprint]);+ continue;+ }+ out.push(row.record);+ }+ return out;+}diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.tsindex a7442c2a65..56ba9bee47 100644--- a/src/core/op-checkpoint.ts+++ b/src/core/op-checkpoint.ts@@ -3,6 +3,7 @@ import type { BrainEngine } from './engine.ts';import { withRetry, BULK_RETRY_OPTS, RetryAbortError } from './retry.ts';import { FENCE_REPAIR_ATTEMPT_OP } from './fence-repair/attempts.ts';import { FENCE_CANDIDATE_OP, FENCE_SCAN_OP } from './fence-repair/census-store.ts';+import { FENCE_UNCOMMITTED_OP } from './fence-repair/uncommitted.ts';/** Max paths per append-INSERT round-trip; bounds the param-array size. */const APPEND_CHUNK = 1000;@@ -489,8 +490,9 @@ export function syncFingerprint(p: { sourceId?: string; lastCommit: string }): s* that window, and the row is cheap (few KB). Durable state is exempt: Git* sync holds, their summary while it counts any, retry requests, sync* import provenance, the blocked-cursor conversion log, and the #6188 fence- * census (candidates and scan cursors) and paid fence-repair attempt claims- * and memos of a live source incarnation leave only on resolution (or with+ * census (candidates and scan cursors), paid fence-repair attempt claims+ * and memos, and uncommitted legacy fence-repair notices of a live source+ * incarnation leave only on resolution (or with* the incarnation), and connector hold-retry requests never expire (#5988).*/export async function purgeStaleCheckpoints(@@ -507,7 +509,7 @@ export async function purgeStaleCheckpoints(WHERE updated_at < now() - ($1 || ' days')::intervalAND op NOT IN ('managed-atoms','managed-atoms-generation','managed-connector','managed-connector-retry','managed-connector-state','managed-connector-migration')AND op<>'connector-hold-retry'- AND NOT (op IN ('sync-hold','sync-hold-retry','sync-import-provenance','sync-hold-summary','sync-conversions','${FENCE_CANDIDATE_OP}','${FENCE_SCAN_OP}','${FENCE_REPAIR_ATTEMPT_OP}')+ AND NOT (op IN ('sync-hold','sync-hold-retry','sync-import-provenance','sync-hold-summary','sync-conversions','${FENCE_CANDIDATE_OP}','${FENCE_SCAN_OP}','${FENCE_REPAIR_ATTEMPT_OP}','${FENCE_UNCOMMITTED_OP}')AND NOT (op='sync-hold-summary' AND COALESCE((completed_keys->0->>'count')::int,0)=0)AND EXISTS (SELECT 1 FROM sources s WHERE s.id=op_checkpoints.completed_keys->0->>'source_id'AND s.incarnation::text=op_checkpoints.completed_keys->0->>'incarnation'))diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 45a53e8cd5..a7b1be6d49 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'captured-facts' | 'loop-facts' | 'failed-writes' | 'frontmatter';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'captured-facts' | 'loop-facts' | 'failed-writes' | 'frontmatter' | 'fences';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex c9739e8c75..a7006bd27e 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -101,7 +101,7 @@ export interface RepairHandler {* Kind-specific result fields, computed once the dry run or apply finished (for example a verification re-check* of the selected scope). Runs only when the run ended without an exception.*/- report?(ctx: OperationContext, scope: RepairScope, result: RepairResult, opts: RepairPlanOptions): Promise<Partial<Pick<RepairResult, 'repaired' | 'remaining' | 'verification'>>>;+ report?(ctx: OperationContext, scope: RepairScope, result: RepairResult, opts: RepairPlanOptions): Promise<Partial<Pick<RepairResult, 'repaired' | 'remaining' | 'verification' | 'stopped'>>>;}/**diff --git a/src/core/repair/fences.ts b/src/core/repair/fences.tsindex bfa8593ca6..3af8281a13 100644--- a/src/core/repair/fences.ts+++ b/src/core/repair/fences.ts@@ -1,16 +1,60 @@/**- * `gbrain repair fences` (#6188): repairs malformed facts and takes fences.- * Skeleton: the kind is registered so the CLI, the cycle phase and the- * surfaces can wire to it; the plan and apply land next.+ * `gbrain repair fences` (#6188): repairs malformed facts and takes fences+ * that sync held, that pages store, or that a checkout holds unsynced.*- * Per-item outcomes (RepairItemOutcome) this kind returns:- * - `repaired` (applied): detail `{ tier, classes, mode, path?, slug }`, `llm_usd` for a Tier 3 repair.- * - `held` (not applied): `reason` is a FenceReason (gate, llm_*, budget_exhausted, llm_disabled, no_pricing,- * manual-only residual, ...), detail `{ tier, mode, path?, slug, gate?, rows? }`.- * - `skipped` (not applied): `reason` owner_unavailable | sync_in_progress | changed_since_read | changed_since_preview.+ * Candidates come from the fence census (holds, stored pages, files), after+ * a bounded census scan; `--only <path>` and `--slug <slug>` also reach a+ * file or page the census has not judged yet. Per candidate the current+ * bytes are re-read and the free tiers run first (Tier 1 rules, then Tier 2+ * holder names verified against `people/` and `companies/` pages); a+ * candidate whose only residuals are rows a model can realign goes to Tier 3+ * (fence-repair/llm.ts) at apply time, under `fences.repair.llm`, the+ * per-page and daily caps (`fences.repair.max_usd_per_page` / `_per_day`,+ * the daily USD ledger) and any lower `--max-usd`, with the attempt memo so+ * an unchanged rejected file never costs twice. Every proposal passes gates+ * (a)-(g) and is a Tier 1 fixed point before it is written+ * (fence-repair/repair-io.ts has the four write-back paths).+ *+ * Preview (no --apply) is read-only and calls no model: per candidate the+ * planned tier, rows and classes, the exact diff for Tier 1/2 (one sample+ * per tier; all with --diff or --json), the estimated model cost against the+ * day's remaining cap, and a preview hash bound to the selection.+ * `--apply --expect <hash>` applies exactly that set (`changed_since_preview`+ * for anything whose bytes or revision moved); a bare `--apply` (from+ * `--all`, `doctor --remediate`, the maintenance cycle) applies the current+ * plan, rotating its start so a backlog under a time budget is not starved.+ *+ * Per-item outcomes: `repaired` (detail: tier, classes, mode, path or slug),+ * `held` (reason: a FenceReason; the hold records it for the surfaces), or+ * `skipped` (owner_unavailable, sync_in_progress, changed_since_read,+ * changed_since_preview, claimed_elsewhere, already_clean). When the daily+ * ledger refuses a call the run stops with `budget_exhausted` (D15). The+ * result adds `repaired`, `remaining` by reason, `scan` and `verification`;+ * a run whose every model proposal is rejected reports 0 repaired.*/-import type { FenceTier } from '../fence-repair/types.ts';-import type { RepairHandler, RepairPlan } from './core.ts';+import type { BrainEngine } from '../engine.ts';+import type { OperationContext } from '../ops/contract.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';+import { shellQuote, type Action } from '../agent-output.ts';+import { parseMarkdown } from '../markdown.ts';+import { resolveModel, TIER_DEFAULTS } from '../model-config.ts';+import { loadPricingOverrides } from '../budget/budget-tracker.ts';+import { dailyLedger, FENCE_REPAIR_LEDGER, nextUtcMidnight } from '../budget/daily-ledger.ts';+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 { attemptStore } from '../fence-repair/attempts.ts';+import { listFenceCandidates, runFenceCensus, type FenceCandidate } from '../fence-repair/census.ts';+import { fenceRepairLlmEnabled, readFenceRepairCaps } from '../fence-repair/config.ts';+import { FENCE_REASONS } from '../fence-repair/reasons.ts';+import { FENCE_REPAIR_ACTOR } from '../fence-repair/receipt.ts';+import { checkoutFileExists, loadFenceSource, pageSha, readFenceTarget, spliceFileSections, writeFenceRepair, type FenceRepairMode, type FenceSource, type FenceTarget } from '../fence-repair/repair-io.ts';+import { analyzeFences, attemptCandidate, runTier3, tier3Estimate, tier3Memo, type FenceAnalysis } from '../fence-repair/repair-tiers.ts';+import type { FenceFix, FenceIssue, FencePage, FenceReason, FenceTier, GateLetter } from '../fence-repair/types.ts';+import { lineDiff } from './frontmatter.ts';+import type { RepairHandler, RepairItem, RepairItemOutcome, RepairListing, RepairPlan, RepairPlanOptions, RepairResult, RepairScope } from './core.ts';/** The fences result's `verification` (report hook): what the run did and what is left, for the CLI and the cycle phase report. */export interface FenceRepairVerification {@@ -28,13 +72,436 @@ export interface FenceRepairVerification {partial: boolean;}+type RepairTier = Exclude<FenceTier, 'manual'>;+interface Selection { source_ids: string[]; only: string[]; skip: string[]; slugs: string[]; no_llm: boolean }++/** One previewed repair: everything the hash binds (location, hashes, tier), never a cell value. */+interface ApprovedFence {+ source_id: string; key: string; slug: string; path: string | null; mode: FenceRepairMode;+ before: string; revision: string | null; page_id: number | null;+ tier: RepairTier;+ /** sha256 of the repaired bytes (Tier 1/2); null for Tier 3 (rewritten at apply time). */+ after: string | null;+ classes: string[]; rows: number[]; columns: string[];+ estimate_usd: number;+ held: boolean;+ /** Model items from this one to the end of the plan (the pages a budget stop leaves waiting). */+ llm_waiting: number;+}+interface ApprovedSetItem extends ApprovedFence { selection: Selection }+interface FenceItem extends RepairItem { entry: ApprovedFence; hash: string | null; last: boolean; scan_partial: boolean }++interface FileDiff { item: string; tier: RepairTier; classes: string[]; diff: string }+interface HeldEntry { item: string; reason: string; tier: FenceTier; resolution: string; gate?: GateLetter; rows?: number[] }+export interface FencesPreviewDetails {+ counts: Record<RepairTier | 'held', number>;+ model: string | null;+ llm_enabled: boolean;+ samples: Partial<Record<RepairTier, FileDiff>>;+ diffs: FileDiff[];+ llm_items: Array<{ item: string; rows: number[]; reasons: string[]; estimate_usd: number }>;+ held: HeldEntry[];+ caps: { max_usd_per_page: number; max_usd_per_day: number; day_remaining_usd: number | null; run_max_usd: number | null };+ next_actions: Action[];+}++const SCAN_MS = () => { const n = parseInt(process.env.GBRAIN_FENCE_REPAIR_SCAN_MS ?? '', 10); return Number.isFinite(n) && n > 0 ? n : 10_000; };+const CALL_TIMEOUT_MS = () => { const n = parseInt(process.env.GBRAIN_FENCE_REPAIR_CALL_TIMEOUT_MS ?? '', 10); return Number.isFinite(n) && n > 0 ? n : 90_000; };+const ROTATION_OP = 'fence-repair-rotation';++export async function resolveFenceRepairModel(engine: Pick<BrainEngine, 'getConfig'>): Promise<string> {+ return resolveModel(engine, { configKey: 'models.fence_repair', tier: 'deep', fallback: TIER_DEFAULTS.deep });+}++function previewArgv(scope: RepairScope, selection: Selection): string[] {+ return ['gbrain', 'repair', 'fences', ...(scope.source_ids.length === 1 ? ['--source', scope.source_ids[0]!] : []),+ ...selection.only.flatMap(path => ['--only', path]), ...selection.skip.flatMap(path => ['--skip', path]), ...selection.slugs.flatMap(slug => ['--slug', slug]),+ ...(selection.no_llm ? ['--no-llm'] : [])];+}++const itemName = (entry: Pick<ApprovedFence, 'source_id' | 'path' | 'slug'>) => `${entry.source_id}:${entry.path ?? entry.slug}`;++function fixLocation(fixes: readonly FenceFix[], residual: readonly FenceIssue[]) {+ const all = [...fixes, ...residual];+ return { rows: [...new Set(all.flatMap(f => f.row === null ? [] : [f.row]))].sort((a, b) => a - b).slice(0, 200),+ columns: [...new Set(all.flatMap(f => f.column === null ? [] : [f.column]))].sort().slice(0, 40) };+}++function classesOf(fixes: readonly FenceFix[], cleared: readonly string[] = []): string[] {+ return [...new Set([...fixes.map(f => f.class), ...cleared])].sort();+}++/** The repaired bytes as the hash binds them: the spliced file, or the page's two sections. */+function afterBytes(target: FenceTarget, after: FencePage): { sha: string; text: string } | null {+ if (target.content !== null && target.path) {+ const content = spliceFileSections(target.content, target.path, target.page, after);+ return content === null ? null : { sha: sha256(Buffer.from(content, 'utf8')), text: content };+ }+ return { sha: pageSha(after), text: `${after.compiled_truth}\n${after.timeline}` };+}++interface Settings {+ llmEnabled: boolean; model: string; overrides: Awaited<ReturnType<typeof loadPricingOverrides>>; capSource: CapSource;+ perPageUsd: number; perDayUsd: number; dayRemaining: number | null; runMaxUsd: number | null;+}++async function settings(engine: BrainEngine, opts: Pick<RepairPlanOptions, 'noLlm' | 'maxLlmUsd'>): Promise<Settings> {+ const caps = await readFenceRepairCaps(engine);+ const model = await resolveFenceRepairModel(engine);+ const day = await dailyLedger(engine, FENCE_REPAIR_LEDGER).readDay().catch(() => null);+ return { llmEnabled: !opts.noLlm && await fenceRepairLlmEnabled(engine), model, overrides: await loadPricingOverrides(engine),+ capSource: caps.perPageSource === 'user' || caps.perDaySource === 'user' || opts.maxLlmUsd !== undefined ? 'user' : 'default',+ perPageUsd: caps.perPageUsd, perDayUsd: caps.perDayUsd, dayRemaining: day ? Math.max(0, caps.perDayUsd - day.committedUsd - day.reservedUsd) : null,+ runMaxUsd: opts.maxLlmUsd ?? null };+}++/** The tier a reason's hold state records. */+function heldTier(reason: string): FenceTier {+ const spec = FENCE_REASONS[reason as FenceReason];+ return spec?.manualOnly || spec?.stage === 'gate' ? 'manual' : spec?.tier ?? 'manual';+}++async function recordHeld(engine: BrainEngine, src: FenceSource, cand: { path: string | null; held: boolean }, held: { reason: string; gate?: GateLetter; rows?: number[]; next?: string | null }): Promise<void> {+ if (!cand.held || !cand.path || !(held.reason in FENCE_REASONS)) return;+ const reason = held.reason as FenceReason;+ await recordFenceHoldRepair(engine, { sourceId: src.id, incarnation: src.incarnation, path: cand.path, state: { reason, tier: heldTier(reason), at: new Date().toISOString(),+ next_attempt_after: held.next ?? null, ...(held.gate ? { gate: held.gate } : {}), ...(held.rows?.length ? { rows: held.rows.slice(0, 50) } : {}) } }).catch(() => false);+}++/** Candidates the selection names that the census has not judged yet: a file under a source root, or a stored page. */+async function extraCandidates(engine: BrainEngine, scope: RepairScope, selection: Selection, found: readonly FenceCandidate[], sources: Map<string, FenceSource | null>): Promise<{ extra: FenceCandidate[]; unknown: string[] }> {+ const extra: FenceCandidate[] = [];+ const unknown: string[] = [];+ const base = (sourceId: string, key: string, path: string | null): FenceCandidate => ({ source_id: sourceId, key, path, page_id: null, origins: [path ? 'file' : 'page'],+ bucket: path ? 'file' : 'page', tier: 'manual', reasons: [], location: null, bound: {} });+ for (const path of selection.only) {+ if (found.some(c => c.path === path)) continue;+ const hits = scope.source_ids.filter(id => { const src = sources.get(id); return !!src?.root && checkoutFileExists(src.root, path); });+ if (!hits.length) unknown.push(`--only ${path}`);+ for (const id of hits) extra.push(base(id, `path:${path}`, path));+ }+ for (const slug of selection.slugs) {+ if (found.some(c => c.key === slug)) continue;+ const rows = await engine.executeRaw<{ source_id: string }>('SELECT source_id FROM pages WHERE slug=$1 AND source_id=ANY($2::text[]) AND deleted_at IS NULL', [slug, scope.source_ids]);+ if (!rows.length) unknown.push(`--slug ${slug}`);+ for (const row of rows) extra.push(base(row.source_id, slug, null));+ }+ return { extra, unknown };+}++function selected(cand: FenceCandidate, selection: Selection): boolean {+ if (cand.path && selection.skip.includes(cand.path)) return false;+ if (!selection.only.length && !selection.slugs.length) return true;+ return (!!cand.path && selection.only.includes(cand.path)) || selection.slugs.includes(cand.key);+}++async function rotationAfter(engine: BrainEngine, brainId: string): Promise<string | null> {+ const [row] = await engine.executeRaw<{ last: string | null }>("SELECT completed_keys->0->>'last' AS last FROM op_checkpoints WHERE op=$1 AND fingerprint=$2", [ROTATION_OP, brainId]);+ return row?.last ?? null;+}++async function saveRotation(engine: BrainEngine, brainId: string, last: string): Promise<void> {+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`, [ROTATION_OP, brainId, JSON.stringify([{ last }])]);+}++const rotationKey = (entry: Pick<ApprovedFence, 'source_id' | 'key'>) => `${entry.source_id}\u0000${entry.key}`;++function item(entry: ApprovedFence, index: number, hash: string | null, last: boolean, partial: boolean): FenceItem {+ return { cursor: { phase: 1, id: index + 1 }, source_id: entry.source_id, slug: entry.slug, chars: 0, action: `${entry.tier}:${entry.path ?? entry.slug}`,+ ...(entry.tier === 'llm' ? { llm_usd: entry.estimate_usd } : {}), entry, hash, last, scan_partial: partial };+}++/** The read-only fix that previews one candidate's repair again. */+const previewFix = (sourceId: string, path: string | null, slug: string): Action => ({ argv: ['gbrain', 'repair', 'fences', '--source', sourceId, ...(path ? ['--only', path] : ['--slug', slug])],+ consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews this fence repair again from the bytes as they are now; nothing is written.' });+export const fencesRepair: RepairHandler = {kind: 'fences',- outcomeItemsLimit: 200,- async plan(): Promise<RepairPlan> {- return { items: [], residuals: {}, llm: { usd: 0, cap_remaining_usd: null }, scan: { fresh_at: null, partial: true } };+ outcomeItemsLimit: 1000,+ async plan(engine, scope, _after, opts): Promise<RepairPlan> {+ const selection: Selection = { source_ids: scope.source_ids, only: [...(opts?.only ?? [])].sort(), skip: [...(opts?.skip ?? [])].sort(),+ slugs: [...(opts?.slugs ?? [])].sort(), no_llm: opts?.noLlm === true };+ const preview = previewArgv(scope, selection);+ if (opts?.apply && opts.expect) {+ const approved = await loadApprovedSet<ApprovedSetItem>(engine, { command: 'fences', hash: opts.expect, previewCommand: shellQuote(preview) });+ if (approved.items.some(entry => digestOf(entry.selection) !== digestOf(selection))) throw previewChangedError(opts.expect, shellQuote(preview));+ const items = approved.items.map(({ selection: _chosen, ...entry }, index) => item(entry, index, opts.expect!, index === approved.items.length - 1, false));+ const s = await settings(engine, opts);+ return { items, preview_hash: opts.expect, residuals: {}, llm: { usd: items.reduce((sum, i) => sum + (i.llm_usd ?? 0), 0), cap_remaining_usd: s.llmEnabled ? s.dayRemaining : 0 } };+ }+ const now = Date.now();+ const runs = await runFenceCensus(engine, { sourceIds: scope.source_ids, deadline: Math.min(now + SCAN_MS(), opts?.deadline ?? Infinity) });+ const sources = new Map<string, FenceSource | null>();+ for (const id of scope.source_ids) sources.set(id, await loadFenceSource(engine, id));+ const found = await listFenceCandidates(engine, scope.source_ids);+ const { extra, unknown } = await extraCandidates(engine, scope, selection, found, sources);+ let candidates = [...found, ...extra].filter(cand => selected(cand, selection));+ const rotation = opts?.apply ? await rotationAfter(engine, scope.brain_id) : null;+ if (rotation) candidates = [...candidates.filter(c => rotationKey({ source_id: c.source_id, key: c.key }) > rotation), ...candidates.filter(c => rotationKey({ source_id: c.source_id, key: c.key }) <= rotation)];+ const s = await settings(engine, opts ?? { noLlm: false });+ const store = attemptStore(engine);+ const residuals: Record<string, number> = {};+ const warnings = unknown.map(name => `${name}: no such file, page or fence candidate in scope; check the source-relative path or slug.`);+ const approved: ApprovedFence[] = [];+ const diffs: FileDiff[] = [];+ const held: HeldEntry[] = [];+ const llmItems: FencesPreviewDetails['llm_items'] = [];+ const hold = (cand: FenceCandidate, entry: HeldEntry) => { held.push(entry); residuals[entry.reason] = (residuals[entry.reason] ?? 0) + 1; return entry; };+ let unpricedWarned = false;+ for (const cand of candidates) {+ const name = `${cand.source_id}:${cand.path ?? cand.key}`;+ const isHeld = cand.origins.includes('hold');+ const src = sources.get(cand.source_id) ?? null;+ if (!src) continue;+ const keep = async (entry: HeldEntry, next: string | null = null) => {+ hold(cand, entry);+ if (opts?.apply) await recordHeld(engine, src, { path: cand.path, held: isHeld }, { reason: entry.reason, gate: entry.gate, rows: entry.rows, next });+ };+ if (src.ownerElsewhere) { await keep({ item: name, reason: 'owner_unavailable', tier: 'manual', resolution: `Run gbrain repair fences --source ${src.id} on the owner host (gbrain sources writer status --source ${src.id} names it).` }); continue; }+ if (src.syncUnfinished || (cand.path && src.busy.paths.has(cand.path)) || src.busy.slugs.has(cand.key)) {+ await keep({ item: name, reason: 'sync_in_progress', tier: cand.tier, resolution: `A sync or write of ${src.id} still names this file; finish it (gbrain sync --source ${src.id} --no-pull) and the next run repairs it.` });+ continue;+ }+ const read = await readFenceTarget(engine, src, { key: cand.key, path: cand.path });+ if (!read.ok) {+ if (read.reason !== 'gone') await keep({ item: name, reason: read.reason, tier: 'manual', resolution: read.reason === 'unsafe_path'+ ? `${cand.path} is a symlink, sits under one, or resolves outside the source root; gbrain never writes through one. Replace it with the real file.`+ : `${cand.path} is not valid UTF-8; re-save it as UTF-8 and preview again.` });+ continue;+ }+ const target = read.target;+ const analysis = await analyzeFences(engine, target, { pageId: target.snapshot?.page.id ?? null });+ if (analysis.status === 'clean') { residuals.already_clean = (residuals.already_clean ?? 0) + 1; continue; }+ if (analysis.status === 'manual') {+ await keep({ item: name, reason: analysis.reason, tier: 'manual', resolution: analysis.resolution, ...(analysis.gate ? { gate: analysis.gate } : {}), ...(analysis.rows ? { rows: analysis.rows } : {}) });+ continue;+ }+ const base: Omit<ApprovedFence, 'tier' | 'after' | 'classes' | 'rows' | 'columns' | 'estimate_usd' | 'llm_waiting'> = { source_id: src.id, key: cand.key, slug: target.slug, path: target.path,+ mode: target.mode, before: target.before, revision: target.snapshot?.revision ?? null, page_id: target.snapshot?.page.id ?? null, held: isHeld };+ if (analysis.status === 'proposal') {+ const bytes = afterBytes(target, analysis.after);+ if (!bytes) { await keep({ item: name, reason: 'unparseable', tier: 'manual', resolution: `gbrain could not place the repaired fence back into ${target.path}; edit the fence there by hand.` }); continue; }+ const at = fixLocation(analysis.fixes, []);+ approved.push({ ...base, tier: analysis.tier, after: bytes.sha, classes: classesOf(analysis.fixes), ...at, estimate_usd: 0, llm_waiting: 0 });+ const beforeText = target.content ?? `${target.page.compiled_truth}\n${target.page.timeline}`;+ diffs.push({ item: name, tier: analysis.tier, classes: classesOf(analysis.fixes), diff: lineDiff(target.path ?? target.slug, beforeText, bytes.text) });+ continue;+ }+ const reasons = [...new Set(analysis.residual.map(i => i.reason))];+ const at = fixLocation(analysis.fixes, analysis.residual);+ const llmHeld = (reason: FenceReason, resolution: string, next: string | null = null) => keep({ item: name, reason, tier: 'llm', resolution, rows: at.rows }, next);+ if (!s.llmEnabled) {+ await llmHeld('llm_disabled', `Model repair is off (${selection.no_llm ? '--no-llm' : 'fences.repair.llm false'}), so row(s) ${at.rows.join(', ') || '?'} stay held (${reasons.join(', ')}). `+ + 'Fix them by hand, or ask the user before turning model repair on: gbrain config set fences.repair.llm true.');+ continue;+ }+ if (target.mode === 'managed' && target.snapshot && !target.snapshot.page.deleted_at) {+ const fileTags = new Set(parseMarkdown(target.content ?? '', target.path ?? 'page.md').tags);+ if (target.snapshot.tags.some(tag => !fileTags.has(tag))) {+ await keep({ item: name, reason: 'canonical_overlay', tier: 'manual', resolution: `The page of ${target.path} carries tags its file does not, so a repaired file could not publish as written; add the tags to the file's frontmatter (gbrain get --source ${src.id} -- ${target.slug} shows them), then preview again.` });+ continue;+ }+ }+ const estimate = tier3Estimate(analysis.requests, { model: s.model, overrides: s.overrides, capSource: s.capSource });+ if (!estimate.ok) {+ await llmHeld('no_pricing', `A spend cap is set but gbrain has no price for ${s.model}. ${estimate.guidance.lookup} Register it with: ${estimate.guidance.register_command}`);+ continue;+ }+ if (estimate.estimated && !unpricedWarned) {+ unpricedWarned = true;+ warnings.push(`gbrain has no price for the fence repair model ${s.model}; model repair runs under the default caps and is metered at an estimated ceiling (the highest chat rate gbrain knows). Make it exact with: ${pricingSetCommand(s.model, 'chat')}`);+ }+ if (s.perPageUsd === 0 || s.perDayUsd === 0) {+ await llmHeld('budget_exhausted', `Model repair spend is set to 0 (fences.repair.max_usd_per_${s.perPageUsd === 0 ? 'page' : 'day'}), so these rows stay held. Raising it is the user's call: gbrain config set fences.repair.max_usd_per_${s.perPageUsd === 0 ? 'page' : 'day'} <usd>.`);+ continue;+ }+ if (estimate.usd > s.perPageUsd + 1e-9) {+ await llmHeld('budget_exhausted', `The estimated model cost ($${estimate.usd.toFixed(4)}) exceeds fences.repair.max_usd_per_page ($${s.perPageUsd.toFixed(2)}). Raising it is the user's call: gbrain config set fences.repair.max_usd_per_page <usd>.`);+ continue;+ }+ const memo = await store.read(attemptCandidate(target, src.incarnation));+ if (memo && memo.memo === tier3Memo(target, s.model) && memo.state === 'rejected') {+ const reason = (memo.reason ?? 'still_invalid') as FenceReason;+ await keep({ item: name, reason, tier: 'manual', resolution: `${s.model}'s repair of these exact bytes was rejected (${reason}${memo.gate ? `, gate ${memo.gate}` : ''}); it is not retried until the file, the model or the rules change. `+ + `Fix row(s) ${(memo.rows ?? at.rows).join(', ') || '?'} by hand.`, ...(memo.gate ? { gate: memo.gate as GateLetter } : {}), ...(memo.rows ? { rows: memo.rows } : {}) });+ continue;+ }+ approved.push({ ...base, tier: 'llm', after: null, classes: [...new Set([...classesOf(analysis.fixes), ...reasons])].sort(), ...at, estimate_usd: estimate.usd, llm_waiting: 0 });+ llmItems.push({ item: name, rows: at.rows, reasons, estimate_usd: estimate.usd });+ }+ let waiting = 0;+ for (const entry of [...approved].reverse()) { if (entry.tier === 'llm') waiting++; entry.llm_waiting = entry.tier === 'llm' ? waiting : 0; }+ const sourcesRows = await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);+ const hash = previewHash({ kind: 'fences-v1', brain_id: scope.brain_id, sources: sourcesRows, selection, items: approved });+ if (approved.length && !opts?.apply) await saveApprovedSet<ApprovedSetItem>(engine, { command: 'fences', hash }, approved.map(entry => ({ ...entry, selection })));+ const partial = runs.some(run => !run.complete);+ const freshAt = runs.every(run => run.fresh_at) ? runs.map(run => run.fresh_at!).sort()[0] ?? null : null;+ const listing: RepairListing[] = [+ ...approved.map(entry => ({ item: itemName(entry), class: entry.tier, detail: `${entry.classes.join(', ')}${entry.rows.length ? `; rows ${entry.rows.join(', ')}` : ''}`+ + `${entry.tier === 'llm' ? `; rewritten by ${s.model} at apply time, gated by (a)-(g); est. $${entry.estimate_usd.toFixed(4)}` : ''}` })),+ ...held.map(entry => ({ item: entry.item, class: entry.reason, detail: entry.resolution })),+ ];+ const llmUsd = approved.reduce((sum, entry) => sum + entry.estimate_usd, 0);+ const apply = [...preview, ...(s.runMaxUsd !== null ? ['--max-usd', String(s.runMaxUsd)] : []), '--apply', '--expect', hash];+ const next_actions: Action[] = approved.length ? [{ argv: apply, consent: [], actor: 'agent', requires_exclusive: false, plan_hash: hash, preview_argv: preview,+ why: `Applies exactly the ${approved.length} previewed fence repair(s)${llmItems.length ? `, ${llmItems.length} of them by the model (estimated $${llmUsd.toFixed(4)})` : ''}; a file or page that changed since this preview is skipped.`,+ verify: { argv: ['gbrain', 'doctor', '--only', 'fence_integrity', '--json'] } }] : [];+ const counts = { deterministic: 0, resolver: 0, llm: 0, held: held.length };+ for (const entry of approved) counts[entry.tier]++;+ const details: FencesPreviewDetails = { counts, model: s.llmEnabled ? s.model : null, llm_enabled: s.llmEnabled,+ samples: Object.fromEntries((['deterministic', 'resolver'] as const).flatMap(tier => { const d = diffs.find(x => x.tier === tier); return d ? [[tier, d]] : []; })),+ diffs, llm_items: llmItems, held, caps: { max_usd_per_page: s.perPageUsd, max_usd_per_day: s.perDayUsd, day_remaining_usd: s.dayRemaining, run_max_usd: s.runMaxUsd }, next_actions };+ return { items: approved.map((entry, index) => item(entry, index, null, index === approved.length - 1, partial)), preview_hash: hash, residuals, listing,+ ...(warnings.length ? { warnings } : {}), details: details as unknown as Record<string, unknown>,+ llm: { usd: llmUsd, cap_remaining_usd: s.llmEnabled ? s.dayRemaining : 0 }, scan: { fresh_at: freshAt, partial } };+ },+ async apply(ctx, raw, opts): Promise<RepairItemOutcome> {+ if (ctx.remote !== false) throw trustedCliRequired('gbrain repair fences writes files and may call a paid model, so it runs only from the trusted local CLI or the maintenance job on the brain host.');+ const { entry, hash, last } = raw as FenceItem;+ try {+ return await applyFence(ctx, entry, { embed: opts?.embed === true, expect: hash, allowanceUsd: opts?.llmAllowanceUsd, deadline: opts?.deadline, noLlm: opts?.noLlm === true });+ } finally {+ if (hash && last) await clearApprovedSet(ctx.engine, { command: 'fences', hash });+ if (!hash) {+ const [brain] = await ctx.engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1').catch(() => []);+ await saveRotation(ctx.engine, brain?.brain_id ?? 'host', rotationKey(entry)).catch(() => undefined);+ }+ }+ },+ render(details, opts) {+ const d = details as unknown as FencesPreviewDetails;+ const lines = [` tiers: deterministic=${d.counts.deterministic}, resolver=${d.counts.resolver}, llm=${d.counts.llm}, held=${d.counts.held}`+ + `${d.llm_enabled ? `; model ${d.model}` : '; model repair off'}`];+ const capLine = ` model caps: $${d.caps.max_usd_per_page.toFixed(2)}/page, $${d.caps.max_usd_per_day.toFixed(2)}/day${d.caps.day_remaining_usd !== null ? ` ($${d.caps.day_remaining_usd.toFixed(4)} left today)` : ''}`+ + `${d.caps.run_max_usd !== null ? `; this run at most $${d.caps.run_max_usd.toFixed(4)}` : ''}`;+ if (d.counts.llm || d.held.some(h => h.tier === 'llm')) lines.push(capLine);+ const shown = opts.diff ? d.diffs : Object.values(d.samples);+ for (const diff of shown) lines.push(` ${diff.tier}: ${diff.item} (${diff.classes.join(', ')})`, ...diff.diff.split('\n').map(line => ` ${line}`));+ if (!opts.diff && d.diffs.length > shown.length) lines.push(` (one sample diff per tier; --diff or --json shows all ${d.diffs.length})`);+ for (const llm of d.llm_items) lines.push(` llm: ${llm.item} rows ${llm.rows.join(', ') || '?'} (${llm.reasons.join(', ')}): rewritten by ${d.model} at apply time, gated by (a)-(g); est. $${llm.estimate_usd.toFixed(4)}`);+ for (const h of d.held) lines.push(` held ${h.item} [${h.reason}${h.gate ? `, gate ${h.gate}` : ''}]: ${h.resolution}`);+ for (const action of d.next_actions) lines.push(` next: ${shellQuote(action.argv!)}`);+ return lines;},- async apply() {- return false;+ async report(ctx, scope, result, opts) {+ return reportFences(ctx, scope, result, opts);},};++function digestOf(selection: Selection): string {+ return sha256(JSON.stringify([selection.source_ids, selection.only, selection.skip, selection.slugs, selection.no_llm]));+}++interface ApplyOptions { embed: boolean; expect: string | null; allowanceUsd?: number; deadline?: number; noLlm: boolean }++async function applyFence(ctx: OperationContext, entry: ApprovedFence, opts: ApplyOptions): Promise<RepairItemOutcome> {+ const engine = ctx.engine;+ const where = { ...(entry.path ? { path: entry.path } : {}), slug: entry.slug, mode: entry.mode, tier: entry.tier };+ const moved = opts.expect ? 'changed_since_preview' : 'changed_since_read';+ const skipped = (reason: string, message: string): RepairItemOutcome => ({ applied: false, outcome: 'skipped', reason, detail: { ...where, message } });+ const src = await loadFenceSource(engine, entry.source_id);+ if (!src) return skipped(moved, `Source ${entry.source_id} is gone or archived.`);+ const heldOutcome = async (reason: string, message: string, extra: { gate?: GateLetter; rows?: number[]; next?: string | null; tier?: FenceTier } = {}): Promise<RepairItemOutcome> => {+ await recordHeld(engine, src, entry, { reason, ...extra });+ return { applied: false, outcome: 'held', reason, detail: { ...where, tier: extra.tier ?? heldTier(reason), message, ...(extra.gate ? { gate: extra.gate } : {}), ...(extra.rows?.length ? { rows: extra.rows } : {}) } };+ };+ if (src.ownerElsewhere) {+ await recordHeld(engine, src, entry, { reason: 'owner_unavailable' });+ return skipped('owner_unavailable', `This host is not the active owner of source ${src.id}; run gbrain repair fences there.`);+ }+ if (src.syncUnfinished || (entry.path && src.busy.paths.has(entry.path)) || src.busy.slugs.has(entry.slug)) {+ await recordHeld(engine, src, entry, { reason: 'sync_in_progress' });+ return skipped('sync_in_progress', `A sync or write of ${src.id} still names this candidate; the next run repairs it.`);+ }+ const read = await readFenceTarget(engine, src, { key: entry.key, path: entry.path });+ if (!read.ok) return skipped(moved, `The candidate is ${read.reason === 'gone' ? 'gone' : read.reason}.`);+ const target = read.target;+ if (target.before !== entry.before || (target.snapshot?.revision ?? null) !== entry.revision && target.mode !== 'managed' && target.mode !== 'legacy') {+ return skipped(moved, `${entry.path ?? entry.slug} changed since it was ${opts.expect ? 'previewed' : 'read'}; preview again with gbrain repair fences --source ${src.id}.`);+ }+ const analysis = await analyzeFences(engine, target, { pageId: target.snapshot?.page.id ?? null });+ if (analysis.status === 'clean') return skipped('already_clean', `${entry.path ?? entry.slug} no longer has a malformed fence.`);+ if (analysis.status === 'manual') return heldOutcome(analysis.reason, analysis.resolution, { ...(analysis.gate ? { gate: analysis.gate } : {}), ...(analysis.rows ? { rows: analysis.rows } : {}) });+ if (analysis.status === 'proposal') {+ const bytes = afterBytes(target, analysis.after);+ if (opts.expect && bytes?.sha !== entry.after) return skipped('changed_since_preview', `The repair of ${entry.path ?? entry.slug} differs from the preview; preview again.`);+ return write(ctx, src, target, analysis.after, { tier: analysis.tier, classes: classesOf(analysis.fixes), ...fixLocation(analysis.fixes, []), model: null, cost: 0 }, opts, heldOutcome);+ }+ return tier3(ctx, src, target, analysis, entry, opts, heldOutcome);+}++type HeldFn = (reason: string, message: string, extra?: { gate?: GateLetter; rows?: number[]; next?: string | null; tier?: FenceTier }) => Promise<RepairItemOutcome>;++async function write(ctx: OperationContext, src: FenceSource, target: FenceTarget, after: FencePage,+ r: { tier: RepairTier; classes: string[]; rows: number[]; columns: string[]; model: string | null; cost: number | null }, opts: ApplyOptions, held: HeldFn): Promise<RepairItemOutcome> {+ const outcome = await writeFenceRepair(ctx, src, target, after, { actor: FENCE_REPAIR_ACTOR, tier: r.tier, classes: r.classes, rows: r.rows, columns: r.columns, model: r.model, cost_usd: r.cost },+ { embed: opts.embed });+ if (!outcome.ok) {+ if (outcome.reason === 'changed_since_read') return { applied: false, outcome: 'skipped', reason: 'changed_since_read', detail: { path: target.path, slug: target.slug, mode: target.mode, message: outcome.message } };+ return held(outcome.reason, outcome.message, { tier: 'manual' });+ }+ return { applied: true, outcome: 'repaired', detail: { tier: r.tier, classes: r.classes.join(', '), slug: target.slug, ...outcome.detail }, ...(r.cost ? { llm_usd: r.cost } : {}) };+}++async function tier3(ctx: OperationContext, src: FenceSource, target: FenceTarget, analysis: Extract<FenceAnalysis, { status: 'llm' }>, entry: ApprovedFence, opts: ApplyOptions, held: HeldFn): Promise<RepairItemOutcome> {+ const engine = ctx.engine;+ const s = await settings(engine, { noLlm: opts.noLlm, ...(opts.allowanceUsd !== undefined ? { maxLlmUsd: opts.allowanceUsd } : {}) });+ const rows = fixLocation(analysis.fixes, analysis.residual).rows;+ if (!s.llmEnabled) return held('llm_disabled', `Model repair is off; row(s) ${rows.join(', ')} stay held.`, { rows, tier: 'llm' });+ if (s.perPageUsd === 0 || s.perDayUsd === 0) return held('budget_exhausted', 'Model repair spend is set to 0.', { rows, tier: 'llm' });+ const now = () => new Date();+ const timeoutMs = Math.max(5_000, Math.min(CALL_TIMEOUT_MS(), opts.deadline !== undefined ? opts.deadline - Date.now() : Infinity));+ const result = await runTier3(target, analysis, src.incarnation, { ledger: dailyLedger(engine, FENCE_REPAIR_LEDGER), store: attemptStore(engine), model: s.model, overrides: s.overrides,+ capSource: s.capSource, perPageUsd: s.perPageUsd, perDayUsd: s.perDayUsd, ...(opts.allowanceUsd !== undefined ? { allowanceUsd: opts.allowanceUsd } : {}), timeoutMs, now });+ if (!result.ok) {+ if (result.reason === 'claimed_elsewhere') return { applied: false, outcome: 'skipped', reason: 'claimed_elsewhere', detail: { path: target.path, slug: target.slug, message: result.message } };+ const next = result.reason === 'budget_exhausted' ? result.resetsAt ?? nextUtcMidnight(new Date()) : null;+ const out = await held(result.reason, result.message, { ...(result.gate ? { gate: result.gate } : {}), ...(result.rows ? { rows: result.rows } : {}), next, tier: FENCE_REASONS[result.reason]?.stage === 'gate' ? 'manual' : 'llm' });+ const withSpend = { ...out, ...(result.spentUsd ? { llm_usd: result.spentUsd } : {}), detail: { ...out.detail, ...(result.memoHit ? { memo: 'rejected_before' } : {}) } };+ if (!result.stop) return withSpend;+ const day = await dailyLedger(engine, FENCE_REPAIR_LEDGER).readDay().catch(() => null);+ const resets = result.resetsAt ?? nextUtcMidnight(new Date());+ const message = opts.allowanceUsd !== undefined && !result.resetsAt+ ? `Stopped: ${result.message} ${entry.llm_waiting} page(s) wait for the model. Rerun with a larger --max-usd, or leave them to the maintenance run.`+ : `Stopped: the daily fence-repair budget is spent ($${(day?.committedUsd ?? 0).toFixed(4)} of $${s.perDayUsd.toFixed(2)} today). It resets at ${resets}; `+ + `${entry.llm_waiting} page(s) wait for the model and the next run after that repairs them. Raising the cap is the user's call: gbrain config set fences.repair.max_usd_per_day <usd>.`;+ return { ...withSpend, stop: { reason: 'budget_exhausted', message, fix: { argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<usd>'], consent: ['paid'], actor: 'agent', requires_exclusive: false,+ why: `Model fence repair stopped at the daily cap; ${entry.llm_waiting} page(s) wait until ${resets} unless the cap is raised.`,+ user_message: `The daily model budget for fence repair ($${s.perDayUsd.toFixed(2)}) is spent and ${entry.llm_waiting} page(s) still wait. Raise it for today, or let them repair after ${resets}?`,+ inputs: [{ name: 'usd', how: 'The new daily cap in USD the user agrees to; it must exceed what is already spent today.' }],+ verify: { argv: ['gbrain', 'doctor', '--only', 'fence_integrity', '--json'] } } } };+ }+ const written = await write(ctx, src, target, result.after, { tier: 'llm', classes: classesOf(analysis.fixes, result.cleared), ...fixLocation(analysis.fixes, analysis.residual), model: s.model, cost: result.spentUsd },+ opts, held);+ const store = attemptStore(engine);+ if (written.applied) await store.publish(result.claim);+ else if (written.reason === 'changed_since_read') await store.transient(result.claim, 'changed_since_read');+ else await store.reject(result.claim, { reason: written.reason ?? 'still_invalid' });+ return { ...written, ...(result.spentUsd ? { llm_usd: result.spentUsd } : {}) };+}++/** 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) {+ 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;+ const repaired = result.mode === 'apply' ? result.outcomes?.repaired ?? 0 : 0;+ if (result.mode === 'apply') {+ for (const outcome of result.outcome_items ?? []) {+ if (outcome.outcome === 'repaired') { const tier = outcome.detail?.tier as RepairTier | undefined; if (tier) repairedByTier[tier]++; }+ else if (outcome.reason && outcome.reason !== 'already_clean') remaining[outcome.reason] = (remaining[outcome.reason] ?? 0) + 1;+ }+ const unattempted = result.affected - result.applied - result.skipped;+ if (unattempted > 0 && result.stopped) remaining[result.stopped.reason] = (remaining[result.stopped.reason] ?? 0) + unattempted;+ } 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 }]);+ const llmRepairs = repairedByTier.llm;+ const spent = typeof result.cost.llm_usd === 'number' ? result.cost.llm_usd : 0;+ const verification: FenceRepairVerification = { candidates: result.affected + Object.values(result.residuals).reduce((a, b) => a + b, 0) - (result.residuals.already_clean ?? 0),+ repaired_by_tier: repairedByTier, held_by_reason: Object.fromEntries(Object.entries(remaining).filter(([reason]) => reason !== 'pending_repair')),+ oldest_hold_at: oldest?.held_at ?? null, llm_repairs: llmRepairs, llm_usd_per_repair: llmRepairs ? spent / llmRepairs : null, partial: result.scan?.partial ?? false };+ return { repaired, remaining, verification: verification as unknown as Record<string, unknown> };+}+