Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(fence-repair): bring in the shared fence types, reasons, raw-row and schema modules (#6188)
garrytan4a96d66346ed
diff --git a/src/core/fence-repair/raw-rows.ts b/src/core/fence-repair/raw-rows.tsnew file mode 100644index 0000000000..b48651bb8d--- /dev/null+++ b/src/core/fence-repair/raw-rows.ts@@ -0,0 +1,380 @@+/**+ * Lenient raw-row extraction of facts/takes fences (#6188).+ *+ * The repair rules and the validator gates work on this view, never on the+ * strict parsers' output and never on their warning strings (which embed row+ * text). For each fence a section holds it returns the markers (located+ * outside markdown code, like every fence reader), the before-region (begin+ * marker to end marker, or to the end of the section when the end marker is+ * missing), the header and its canonical column map (positional when no+ * header is recognizable), rows before the header, and every row's cells+ * with their source spans. A row's identity is its ordinal among the fence's+ * data rows, so it survives renumbering and duplicate claims.+ *+ * `accepted` replays the strict parser on the same region, so a row is+ * accepted exactly when `parseFactsFence` / `parseTakesFence` would return it.+ */+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';+import { indexOfOutsideCode, scanMarkdownCode, type MarkdownCodeMap } from '../fence-scan.ts';+import { isSeparatorRow } from '../fence-shared.ts';+import { BASE_WIDTH, canonicalColumn, cellValid, COLUMNS, MIN_CELLS, NAMED_COLUMNS, parseRowNum, TOLERATED_TRAILING } from './schema.ts';+import type { FenceIssue, FenceKind, FenceReason, FenceSection } from './types.ts';++export const MARKERS: Record<FenceKind, { begin: string; end: string }> = {+ facts: { begin: FACTS_FENCE_BEGIN, end: FACTS_FENCE_END },+ takes: { begin: TAKES_FENCE_BEGIN, end: TAKES_FENCE_END },+};+/** The two-dash takes markers authors write from memory (#3769). */+const NEAR_MISS = { begin: /^<!--\s*gbrain:takes:begin\s*-->$/, end: /^<!--\s*gbrain:takes:end\s*-->$/ };++export interface RawCell {+ /** Cell text as `parseRowCells` reads it: trimmed, `\|` unescaped, `<br>` decoded. */+ text: string;+ /** Trimmed source text of the cell, escapes kept. */+ raw: string;+ /** Offsets of `raw` in the section. */+ start: number;+ end: number;+}++export interface RawRow {+ /** 1-based line in the section. */+ line: number;+ /** Offsets of the trimmed line in the section. */+ start: number;+ end: number;+ cells: RawCell[];+ /** The trimmed line ends with the pipe `parseRowCells` strips. */+ closed: boolean;+ /** Ordinal among the fence's data rows (rows before the header first); -1 for header and separator lines. */+ occurrence: number;+ /** Sits before the header (every row of a fence with no recognizable header). */+ beforeHeader: boolean;+ /** Cell for each canonical column the row fills. */+ byColumn: Map<string, RawCell>;+ /** Cells that map to no column. */+ extra: RawCell[];+ /** Row-shape problem that makes column positions untrustworthy. */+ shape: 'ok' | 'short_row' | 'extra_cells';+ /** The strict parser returns this row. */+ accepted: boolean;+}++export interface RawMarker {+ start: number;+ end: number;+ line: number;+ /** A two-dash takes marker rather than the canonical three-dash form. */+ nearMiss: boolean;+}++export interface RawFence {+ kind: FenceKind;+ section: FenceSection;+ /** The fence the strict parser reads (later ones are repeats). */+ primary: boolean;+ begin: RawMarker;+ end: RawMarker | null;+ /** The before-region: just after the begin marker to the end marker, or to the section end. */+ regionStart: number;+ regionEnd: number;+ header: RawRow | null;+ /** The strict parser recognizes `header` (its cells include `claim` and `kind`). */+ strictHeader: boolean;+ /** Canonical column per header cell; COLUMNS[kind] when there is no header. */+ columns: Array<string | null>;+ /** The header is not the strict canonical layout (alias-only, out of order, or missing whole columns), so a header rewrite is needed. */+ needsRewrite: boolean;+ separators: RawRow[];+ /** Data rows in order (header and separators excluded). */+ rows: RawRow[];+ issues: FenceIssue[];+}++export interface RawSection {+ section: FenceSection;+ text: string;+ fences: RawFence[];+ /** Marker problems that belong to no extractable fence. */+ issues: FenceIssue[];+}++/** Extract every facts and takes fence of one section. */+export function extractRawRows(text: string, section: FenceSection = 'body'): RawSection {+ const out: RawSection = { section, text, fences: [], issues: [] };+ if (!text.includes('gbrain:facts:') && !text.includes('gbrain:takes:')) return out;+ const code = scanMarkdownCode(text);+ const lines = new LineIndex(text);+ for (const kind of ['facts', 'takes'] as const) extractKind(out, kind, code, lines);+ return out;+}++/** The primary fence of a kind, or null. */+export function primaryFence(raw: RawSection, kind: FenceKind): RawFence | null {+ return raw.fences.find(f => f.kind === kind && f.primary) ?? null;+}++class LineIndex {+ private readonly starts: number[] = [0];+ constructor(readonly text: string) {+ for (let i = text.indexOf('\n'); i !== -1; i = text.indexOf('\n', i + 1)) this.starts.push(i + 1);+ }+ /** 1-based line holding offset `at`. */+ lineOf(at: number): number {+ let lo = 0;+ let hi = this.starts.length - 1;+ while (lo < hi) {+ const mid = (lo + hi + 1) >> 1;+ if (this.starts[mid]! <= at) lo = mid; else hi = mid - 1;+ }+ return lo + 1;+ }+ /** Trimmed bounds of the line holding `at`. */+ trimmedLine(at: number): { start: number; end: number } {+ const lineStart = this.starts[this.lineOf(at) - 1]!;+ const nl = this.text.indexOf('\n', at);+ const lineEnd = nl === -1 ? this.text.length : nl;+ const raw = this.text.slice(lineStart, lineEnd);+ const lead = raw.length - raw.trimStart().length;+ return { start: lineStart + lead, end: lineStart + raw.trimEnd().length };+ }+}++function issue(kind: FenceKind, section: FenceSection, reason: FenceReason, line: number | null, row: number | null = null, column: string | null = null): FenceIssue {+ return { fence: kind, section, row, column, line, reason };+}++function countOutsideCode(text: string, needle: string, code: MarkdownCodeMap): number[] {+ const at: number[] = [];+ for (let i = indexOfOutsideCode(text, needle, 0, code); i !== -1; i = indexOfOutsideCode(text, needle, i + needle.length, code)) at.push(i);+ return at;+}++function extractKind(out: RawSection, kind: FenceKind, code: MarkdownCodeMap, lines: LineIndex): void {+ const { text, section } = out;+ const { begin, end } = MARKERS[kind];+ const begins = countOutsideCode(text, begin, code);+ const ends = countOutsideCode(text, end, code);+ const first = begins.length ? marker(begins[0]!, begin.length, lines, false) : kind === 'takes' ? nearMissBegin(out, code, lines) : null;+ if (ends.length && (!first || ends[0]! < first.start)) {+ out.issues.push(issue(kind, section, 'missing_begin', lines.lineOf(ends[0]!)));+ }+ if (!first) return;+ let cursor: RawMarker | null = first;+ while (cursor) {+ const fence = buildFence(out, kind, cursor, code, lines, out.fences.every(f => f.kind !== kind));+ out.fences.push(fence);+ if (!fence.end) break;+ const next = indexOfOutsideCode(text, begin, fence.end.end, code);+ cursor = next === -1 ? null : marker(next, begin.length, lines, false);+ }+ const primary = out.fences.find(f => f.kind === kind && f.primary)!;+ const repeats = [begin, end].flatMap(m => countOutsideCode(text, m, code).slice(1));+ if (repeats.length) primary.issues.unshift(issue(kind, section, 'repeated_marker', lines.lineOf(Math.min(...repeats))));+}++function marker(at: number, length: number, lines: LineIndex, nearMiss: boolean): RawMarker {+ return { start: at, end: at + length, line: lines.lineOf(at), nearMiss };+}++/** A two-dash takes begin marker standing alone on its line, when no canonical begin exists. */+function nearMissBegin(out: RawSection, code: MarkdownCodeMap, lines: LineIndex): RawMarker | null {+ if (!out.text.includes('gbrain:takes:begin')) return null;+ const at = indexOfOutsideCode(out.text, 'gbrain:takes:begin', 0, code);+ if (at === -1) return null;+ const bounds = lines.trimmedLine(at);+ if (NEAR_MISS.begin.test(out.text.slice(bounds.start, bounds.end))) {+ return { ...bounds, line: lines.lineOf(at), nearMiss: true };+ }+ out.issues.push(issue('takes', out.section, 'marker_near_miss', lines.lineOf(at)));+ return null;+}++function findEnd(text: string, kind: FenceKind, from: number, code: MarkdownCodeMap, lines: LineIndex): RawMarker | null {+ const end = MARKERS[kind].end;+ const at = indexOfOutsideCode(text, end, from, code);+ if (at !== -1) return marker(at, end.length, lines, false);+ if (kind !== 'takes') return null;+ for (let i = indexOfOutsideCode(text, 'gbrain:takes:end', from, code); i !== -1; i = indexOfOutsideCode(text, 'gbrain:takes:end', i + 1, code)) {+ const bounds = lines.trimmedLine(i);+ if (NEAR_MISS.end.test(text.slice(bounds.start, bounds.end))) return { ...bounds, line: lines.lineOf(i), nearMiss: true };+ }+ return null;+}++function buildFence(out: RawSection, kind: FenceKind, begin: RawMarker, code: MarkdownCodeMap, lines: LineIndex, primary: boolean): RawFence {+ const end = findEnd(out.text, kind, begin.end, code, lines);+ const fence: RawFence = {+ kind, section: out.section, primary, begin, end,+ regionStart: begin.end, regionEnd: end ? end.start : out.text.length,+ header: null, strictHeader: false, columns: [...COLUMNS[kind]], needsRewrite: false,+ separators: [], rows: [], issues: [],+ };+ const pipeLines = regionRows(out.text, fence.regionStart, fence.regionEnd, lines);+ classifyLines(fence, pipeLines);+ markAccepted(fence, pipeLines);+ return fence;+}++/** Every pipe-table line of a region, parsed with source spans. */+function regionRows(text: string, start: number, end: number, lines: LineIndex): RawRow[] {+ const rows: RawRow[] = [];+ let lineNo = lines.lineOf(start);+ for (let at = start; at <= end; lineNo++) {+ const nl = text.indexOf('\n', at);+ const lineEnd = nl === -1 || nl > end ? end : nl;+ const row = parseRowSpans(text, at, lineEnd, lineNo);+ if (row) rows.push(row);+ if (lineEnd === end) break;+ at = lineEnd + 1;+ }+ return rows;+}++/** `parseRowCells` with offsets: null unless the trimmed line starts with `|` and has a second pipe. */+export function parseRowSpans(text: string, lineStart: number, lineEnd: number, line: number): RawRow | null {+ const rawLine = text.slice(lineStart, lineEnd);+ const trimmed = rawLine.trim();+ if (!trimmed.startsWith('|') || !trimmed.includes('|', 1)) return null;+ const start = lineStart + (rawLine.length - rawLine.trimStart().length);+ const end = start + trimmed.length;+ const closed = trimmed.length >= 2 && trimmed.endsWith('|');+ const cells: RawCell[] = [];+ const innerEnd = closed ? end - 1 : end;+ let cellStart = start + 1;+ for (let i = start + 1; i <= innerEnd; i++) {+ if (i < innerEnd && text[i] === '\\' && text[i + 1] === '|' && i + 1 < innerEnd) { i++; continue; }+ if (i < innerEnd && text[i] !== '|') continue;+ cells.push(cellAt(text, cellStart, i));+ cellStart = i + 1;+ }+ return { line, start, end, cells, closed, occurrence: -1, beforeHeader: false, byColumn: new Map(), extra: [], shape: 'ok', accepted: false };+}++function cellAt(text: string, from: number, to: number): RawCell {+ const slice = text.slice(from, to);+ const raw = slice.trim();+ const lead = slice.length - slice.trimStart().length;+ const start = raw ? from + lead : from + Math.min(1, slice.length);+ return { raw, start, end: start + raw.length, text: raw.replace(/\\\|/g, '|').replace(/<br\s*\/?>/gi, '\n') };+}++function strictHeaderCells(row: RawRow): boolean {+ const lower = row.cells.map(c => c.text.toLowerCase());+ return lower.includes('claim') && lower.includes('kind');+}++function aliasHeaderCells(kind: FenceKind, row: RawRow): boolean {+ const mapped = row.cells.map(c => canonicalColumn(kind, c.text));+ return mapped.every(c => c !== null) && mapped.includes('claim') && mapped.includes('kind');+}++function classifyLines(fence: RawFence, pipeLines: RawRow[]): void {+ const { kind } = fence;+ const headerAt = pipeLines.findIndex(r => !isSeparatorRow(r.cells.map(c => c.text)) && (strictHeaderCells(r) || aliasHeaderCells(kind, r)));+ if (headerAt !== -1) setHeader(fence, pipeLines[headerAt]!);+ pipeLines.forEach((row, i) => {+ if (i === headerAt) return;+ const separator = isSeparatorRow(row.cells.map(c => c.text));+ row.beforeHeader = headerAt === -1 || i < headerAt;+ if (row.beforeHeader && pipeLines.length && headerAt !== -1) {+ fence.issues.push(issue(kind, fence.section, 'row_before_header', row.line, rowNumOf(fence, row)));+ }+ if (separator) { fence.separators.push(row); return; }+ row.occurrence = fence.rows.length;+ mapRow(fence, row);+ fence.rows.push(row);+ });+ if (headerAt === -1 && fence.rows.length) fence.issues.push(issue(kind, fence.section, 'no_header', fence.begin.line));+}++function setHeader(fence: RawFence, header: RawRow): void {+ const { kind } = fence;+ fence.header = header;+ fence.strictHeader = strictHeaderCells(header);+ const seen = new Set<string>();+ fence.columns = header.cells.map(cell => {+ const column = canonicalColumn(kind, cell.text);+ if (!column || seen.has(column)) return null;+ seen.add(column);+ return column;+ });+ // A header shorter than the narrowest row the parser reads leaves whole columns absent.+ fence.needsRewrite = !fence.strictHeader || !canonicalOrder(kind, fence.columns) || fence.columns.length < MIN_CELLS[kind];+}++/** The header puts every column the strict parser reads by position at its canonical position. */+function canonicalOrder(kind: FenceKind, columns: Array<string | null>): boolean {+ const canonical = COLUMNS[kind];+ const named = NAMED_COLUMNS[kind];+ return columns.every((column, i) => {+ if (kind === 'takes' && i >= 7) return column === null || named.has(column);+ if (i >= canonical.length) return true;+ return column === canonical[i];+ });+}++/** Row number in the `#` column, or null. */+export function rowNumOf(fence: RawFence, row: RawRow): number | null {+ const at = fence.columns.indexOf('#');+ const cell = at === -1 ? undefined : row.cells[at];+ return cell ? parseRowNum(cell.text) : null;+}++function mapRow(fence: RawFence, row: RawRow): void {+ const { kind } = fence;+ const positional = !fence.header || !fence.needsRewrite;+ row.cells.forEach((cell, j) => {+ const column = positional ? positionalColumn(fence, j) : fence.columns[j] ?? null;+ if (column && !row.byColumn.has(column)) row.byColumn.set(column, cell);+ else row.extra.push(cell);+ });+ if (row.beforeHeader) return;+ row.shape = rowShape(fence, row);+ if (row.shape !== 'ok') fence.issues.push(issue(kind, fence.section, row.shape, row.line, rowNumOf(fence, row)));+}++/** The column the strict parser reads at index `j` (takes resolution columns by header name). */+function positionalColumn(fence: RawFence, j: number): string | null {+ const canonical = COLUMNS[fence.kind];+ if (fence.kind === 'takes' && j >= 7) return fence.header ? (fence.columns[j] ?? null) : null;+ return canonical[j] ?? null;+}++function rowShape(fence: RawFence, row: RawRow): RawRow['shape'] {+ const { kind } = fence;+ const headerLen = fence.columns.length;+ if (!fence.needsRewrite) {+ if (row.cells.length < MIN_CELLS[kind]) return 'short_row';+ // Facts rows of 14 cells are the typed layout even under a narrow header.+ const layoutMax = kind === 'facts' && row.cells.length === 14 ? 14 : Math.max(headerLen, BASE_WIDTH[kind]);+ const allValid = [...row.byColumn].every(([column, cell]) => cellValid(kind, column, cell.text));+ return row.cells.length > layoutMax && !allValid ? 'extra_cells' : 'ok';+ }+ if (row.cells.length > headerLen) return 'extra_cells';+ const missing = fence.columns.slice(row.cells.length).filter((c): c is string => c !== null);+ return missing.every(c => TOLERATED_TRAILING[kind].has(c)) ? 'ok' : 'short_row';+}++/** Cells the strict parsers reject a row for, with their positions (takes holders only warn). */+const FACTS_CHECKED: ReadonlyArray<[string, number]> = [['kind', 2], ['visibility', 4], ['notability', 5], ['confidence', 3], ['claim_value', 11]];+const TAKES_CHECKED: ReadonlyArray<[string, number]> = [['kind', 2], ['weight', 4]];++/** Replay the strict parser over the region: which rows it returns. */+function markAccepted(fence: RawFence, pipeLines: RawRow[]): void {+ if (!fence.primary || !fence.end || fence.begin.nearMiss || fence.end.nearMiss) return;+ const { kind } = fence;+ const seen = new Set<number>();+ let sawHeader = false;+ for (const row of pipeLines) {+ if (!sawHeader) { sawHeader = strictHeaderCells(row); continue; }+ const texts = row.cells.map(c => c.text);+ if (isSeparatorRow(texts) || texts.length < MIN_CELLS[kind]) continue;+ const rowNum = parseRowNum(texts[0]!);+ if (rowNum === null || seen.has(rowNum)) continue;+ seen.add(rowNum);+ const checked = kind === 'facts' ? FACTS_CHECKED : TAKES_CHECKED;+ row.accepted = checked.every(([column, at]) => cellValid(kind, column, texts[at] ?? ''));+ }+}diff --git a/src/core/fence-repair/reasons.ts b/src/core/fence-repair/reasons.tsnew file mode 100644index 0000000000..11bd71661c--- /dev/null+++ b/src/core/fence-repair/reasons.ts@@ -0,0 +1,153 @@+/**+ * The canonical fence reason table (#6188, D13). One entry per reason that a+ * fence refusal, hold or repair outcome can carry: where it arises, which+ * tier clears it, whether the maintenance pass retries it without a person,+ * who acts, the docs anchor and a location-only fix template. The error+ * registry's `invalid_fence.reasons` and the write-refusals anchors are+ * generated from this table.+ *+ * Fix templates take only location placeholders: `{fence}`, `{section}`,+ * `{rows}`, `{columns}`, `{line}` and `{allowed}` (schema vocabulary). They+ * never quote a cell.+ */+import type { Actor } from '../agent-output.ts';+import type { FenceIssue, FenceKind, FenceReason, FenceSection, FenceTier, GateLetter } from './types.ts';++export interface FenceReasonSpec {+ /** Where the reason arises. */+ stage: 'screen' | 'prepare' | 'repair' | 'gate';+ /** The tier that clears it; null when that depends on the page (re-screened). */+ tier: FenceTier | null;+ /** Never sent to the model tier; the fix names the exact edit. */+ manualOnly: boolean;+ /** The maintenance pass clears or retries it with no one acting. */+ autoRetry: boolean;+ actor: Actor;+ /** Raising spend or enabling the model is the user's call. */+ paid: boolean;+ gate?: GateLetter;+ docs: string;+ fix: string;+}++const DOCS = 'docs/guides/write-refusals.md#fence-';+const REPAIR = 'Preview the repair with `gbrain repair fences`.';++type Base = Pick<FenceReasonSpec, 'stage' | 'tier' | 'manualOnly' | 'autoRetry'>;+const tier3: Base = { stage: 'screen', tier: 'llm', manualOnly: false, autoRetry: true };+const manual: Base = { stage: 'screen', tier: 'manual', manualOnly: true, autoRetry: false };+const prepared: Base = { stage: 'prepare', tier: null, manualOnly: false, autoRetry: true };+const run = (autoRetry: boolean, tier: FenceTier | null = 'llm'): Base => ({ stage: 'repair', tier, manualOnly: false, autoRetry });++function entry(base: Base, fix: string, extra: Partial<FenceReasonSpec> = {}): Omit<FenceReasonSpec, 'docs'> {+ return { ...base, actor: 'agent', paid: false, fix, ...extra };+}++function gate(letter: GateLetter, fix: string): Omit<FenceReasonSpec, 'docs'> {+ return entry({ stage: 'gate', tier: null, manualOnly: false, autoRetry: false }, fix, { gate: letter });+}++const SPECS: Record<FenceReason, Omit<FenceReasonSpec, 'docs'>> = {+ header_unmapped: entry(tier3, 'The {fence} fence header in the {section} at line {line} has a column with no canonical name. Rename each column to one of {allowed}. ' + REPAIR),+ no_header: entry(tier3, 'The {fence} fence in the {section} at line {line} has rows but no header row. Add the canonical header as the first table line. ' + REPAIR),+ row_before_header: entry(tier3, 'Row(s) {rows} of the {fence} fence in the {section} sit above the header (line {line}). Move them below the header. ' + REPAIR),+ short_row: entry(tier3, 'Row(s) {rows} of the {fence} fence in the {section} (line {line}) are missing a cell in the middle of the row, so its columns are ambiguous. Add the missing cell so every column lines up. ' + REPAIR),+ extra_cells: entry(tier3, 'Row(s) {rows} of the {fence} fence in the {section} (line {line}) have more cells than the header, often an unescaped `|` in a cell. Escape it as `\\|` or remove the extra cell. ' + REPAIR),+ holder_unresolved: entry({ stage: 'screen', tier: 'resolver', manualOnly: false, autoRetry: true },+ 'Column `who` of row(s) {rows} in the {fence} fence ({section}, line {line}) is not a holder gbrain recognizes. Write `world`, `brain`, `people/<slug>` or `companies/<slug>`; the repair pass resolves it only when exactly one existing page matches.'),+ missing_begin: entry(manual, 'The {fence} fence in the {section} has an end marker at line {line} with no begin marker before it. Add the begin marker above the table, or delete the stray end marker.'),+ split_rows: entry(manual, 'The {fence} fence that begins at line {line} in the {section} has no end marker and its rows are split by blank lines or text. Join the rows into one table and add the end marker after the last row.'),+ unclosed_trailing_content: entry(manual, 'The {fence} fence that begins at line {line} in the {section} has no end marker and other text follows its table. Add the end marker directly after the last table row, or wrap the marker in backticks if the text only mentions it; gbrain does not guess where the fence ends.'),+ marker_near_miss: entry(manual, 'Line {line} of the {section} mentions the takes begin marker but is not a fence followed by a table. Wrap the mention in backticks, or use the exact three-dash marker above a takes table.'),+ repeated_marker: entry(manual, 'The {section} repeats a {fence} fence marker (line {line}); a section holds at most one facts fence and one takes fence. Merge the fences into one or delete the extra marker.'),+ takes_in_facts: entry(manual, 'The {fence} fence in the {section} at line {line} holds a takes table. Move the rows into a takes fence (or use `takes_add`), or rewrite them as facts rows.'),+ superseded_ambiguous: entry(manual, 'Row number(s) {rows} appear more than once in the {fence} fence and a `superseded by` reference names them. Decide which row keeps each number, renumber the other and fix the reference.'),+ enum_unmapped: entry(manual, 'Column(s) {columns} of row(s) {rows} in the {fence} fence ({section}, line {line}) hold a value gbrain cannot map. Use one of {allowed}.'),+ weight_missing: entry(manual, 'The {fence} fence ({section}, line {line}) has no weight for row(s) {rows}. Add a weight from 0 to 1; takes have no default weight.'),+ holder_missing: entry(manual, 'The {fence} fence ({section}, line {line}) has no holder for row(s) {rows}. Add a `who` column with `world`, `brain`, `people/<slug>` or `companies/<slug>`.'),+ confidence_out_of_range: entry(manual, 'Column(s) {columns} of row(s) {rows} in the {fence} fence ({section}, line {line}) are not a number from 0 to 1. Write the intended value as a decimal such as 0.8.'),+ claim_value_invalid: entry(manual, 'Column `claim_value` of row(s) {rows} in the {fence} fence ({section}, line {line}) is not a number. Write a number (1,234 separators and a k/M/B suffix are allowed) or leave it empty.'),+ takes_kind_unsupported: entry(manual, 'Column `kind` of row(s) {rows} in the {fence} fence ({section}, line {line}) is not a takes kind. Use one of {allowed}; gbrain does not choose a takes kind for you.'),+ unparseable: entry(prepared, 'The {fence} fence in the {section} does not parse cleanly. ' + REPAIR),+ row_collision: entry(prepared, 'Row number(s) {rows} are used by two {fence} rows on this page. Give one row a new number above every number used on the page.'),+ quoted_fence_rows: entry({ ...prepared, autoRetry: false, manualOnly: true }, 'A {fence} fence in the {section} sits inside markdown code, so this write would remove the rows it holds. Move the fence out of the code block, or delete it to remove its rows.'),+ stored_row_collision: entry({ ...prepared, autoRetry: false, manualOnly: true }, 'Row number(s) {rows} of the {fence} fence are already used by a different stored take that is not in the fence. Renumber the new row, or add the stored take back to the fence.'),+ withdrawn_claim_in_malformed_fence: entry(prepared, 'The {fence} fence in the {section} does not parse and holds a withdrawn claim. Fix the fence first. ' + REPAIR),+ target_fence_malformed: entry(prepared, 'The page this write appends to has a {fence} fence that does not parse ({section}, line {line}). ' + REPAIR),+ prepare_time: entry(prepared, 'The {fence} fence passed the screen but its rows were refused while the write was prepared. ' + REPAIR),+ normalizer_failed: entry({ ...prepared, autoRetry: false, tier: 'manual' }, 'The fence normalizer failed on the {fence} fence in the {section}; the page is held as it was. Run `gbrain doctor --json` and report it; a gbrain upgrade re-screens it.'),+ llm_unavailable: entry(run(true), 'The repair model was unavailable (timeout, rate limit or server error). The next repair run retries.'),+ llm_empty: entry(run(false), 'The repair model returned nothing for the {fence} fence. Fix row(s) {rows} by hand. ' + REPAIR),+ llm_refused: entry(run(false), 'The repair model declined to repair the {fence} fence. Fix row(s) {rows} by hand. ' + REPAIR),+ llm_malformed: entry(run(false), 'The repair model did not return a single table for the {fence} fence. Fix row(s) {rows} by hand. ' + REPAIR),+ llm_truncated: entry(run(false), 'The repair model stopped before finishing the {fence} fence. Fix row(s) {rows} by hand. ' + REPAIR),+ llm_disabled: entry(run(false), 'Model repair is off (`fences.repair.llm`). Fix row(s) {rows} by hand, or ask the user before running `gbrain config set fences.repair.llm true`.', { paid: true }),+ budget_exhausted: entry(run(true), 'The daily fence-repair budget is spent; repairs resume after 00:00 UTC. Raising it is the user\'s call: `gbrain config set fences.repair.max_usd_per_day <usd>`.', { paid: true }),+ no_pricing: entry(run(false), 'A spend cap is set but gbrain has no price for the repair model. Look up its price and run `gbrain pricing set <model> --input <usd> --output <usd>` on the brain host.', { paid: true }),+ ledger_unavailable: entry(run(true), 'The spend ledger could not be read, so no model call was made. The next repair run retries.'),+ owner_unavailable: entry(run(true, null), 'Fence repairs run on the brain\'s owner host. Run `gbrain repair fences` there.', { actor: 'host_admin' }),+ owner_cli_required: entry(run(false, null), 'This repair must be applied from the owner host CLI. Run `gbrain repair fences --apply` there.', { actor: 'host_admin' }),+ sync_in_progress: entry(run(true, null), 'A sync of this source is still running; the repair waits for it and retries on the next run.'),+ time_budget: entry(run(true, null), 'The repair run reached its time budget; the next run resumes where it stopped.'),+ changed_since_read: entry(run(true, null), 'The file changed after the repair read it, so nothing was written. The next repair run reads it again.'),+ changed_since_preview: entry(run(false, null), 'The page changed after the preview, so it was not applied. Preview again with `gbrain repair fences` and apply the new plan.'),+ still_invalid: gate('a', 'The proposed repair of the {fence} fence still does not parse cleanly (gate a). Fix row(s) {rows} by hand.'),+ claim_changed: gate('b', 'The proposed repair of the {fence} fence changed claim text (gate b), so it was rejected. Fix row(s) {rows} by hand.'),+ row_number_changed: gate('c', 'The proposed repair of the {fence} fence changed an existing row number (gate c), so it was rejected. Fix row(s) {rows} by hand.'),+ visibility_loosened: gate('d', 'The proposed repair of the {fence} fence made a row more visible (gate d), so it was rejected. Fix row(s) {rows} by hand.'),+ row_count_changed: gate('e', 'The proposed repair of the {fence} fence added, dropped or left rows outside the fence (gate e), so it was rejected. Fix row(s) {rows} by hand.'),+ cell_changed: gate('f', 'The proposed repair of the {fence} fence changed a cell no rule allows (gate f), so it was rejected. Fix column(s) {columns} of row(s) {rows} by hand.'),+ protection_loosened: gate('g', 'The proposed repair of the {fence} fence would show text the privacy boundary hid (gate g), so it was rejected. Add the end marker where the fence really ends.'),+};++export const FENCE_REASONS: Readonly<Record<FenceReason, FenceReasonSpec>> = Object.fromEntries(+ Object.entries(SPECS).map(([reason, spec]) => [reason, { ...spec, docs: `${DOCS}${reason}` }]),+) as Record<FenceReason, FenceReasonSpec>;++/** Every reason code, in table order (the registry's `invalid_fence.reasons`). */+export const FENCE_REASON_CODES = Object.keys(FENCE_REASONS) as FenceReason[];++/** Gate letter to reason. */+export const GATE_REASONS: Readonly<Record<GateLetter, FenceReason>> = {+ a: 'still_invalid', b: 'claim_changed', c: 'row_number_changed', d: 'visibility_loosened',+ e: 'row_count_changed', f: 'cell_changed', g: 'protection_loosened',+};++/** A location for messages: one reason in one fence and section. */+export interface FenceMessageLocation {+ reason: FenceReason;+ fence: FenceKind;+ section: FenceSection;+ rows: readonly number[];+ columns: readonly string[];+ line: number | null;+ allowed?: readonly string[];+}++/** The reason's fix with its placeholders filled; a placeholder with no value reads as `?`. */+export function renderFenceFix(at: FenceMessageLocation): string {+ const values: Record<string, string> = {+ fence: at.fence, section: at.section, line: at.line === null ? '?' : String(at.line),+ rows: at.rows.length ? at.rows.join(', ') : '?', columns: at.columns.length ? at.columns.map(c => `\`${c}\``).join(', ') : '?',+ allowed: at.allowed?.length ? at.allowed.map(a => `\`${a}\``).join(', ') : 'the canonical values',+ };+ return FENCE_REASONS[at.reason].fix.replace(/\{(\w+)\}/g, (_, key: string) => values[key] ?? '?');+}++/** `Fence <reason>: in the <fence> fence (<section>), row(s) N, column(s) C, at line L.` plus the fix. */+export function fenceMessage(at: FenceMessageLocation): string {+ const parts = [`in the ${at.fence} fence (${at.section})`];+ if (at.rows.length) parts.push(`${at.rows.length > 1 ? 'rows' : 'row'} ${at.rows.join(', ')}`);+ if (at.columns.length) parts.push(`${at.columns.length > 1 ? 'columns' : 'column'} ${at.columns.join(', ')}`);+ if (at.line !== null) parts.push(`at line ${at.line}`);+ return `Fence ${at.reason}: ${parts.join(', ')}. ${renderFenceFix(at)}`;+}++/** Message location for one issue. */+export function issueLocation(issue: FenceIssue): FenceMessageLocation {+ const at: FenceMessageLocation = {+ reason: issue.reason, fence: issue.fence, section: issue.section,+ rows: issue.row === null ? [] : [issue.row], columns: issue.column === null ? [] : [issue.column], line: issue.line,+ };+ return issue.allowed ? { ...at, allowed: issue.allowed } : at;+}diff --git a/src/core/fence-repair/schema.ts b/src/core/fence-repair/schema.tsnew file mode 100644index 0000000000..2f755dc34d--- /dev/null+++ b/src/core/fence-repair/schema.ts@@ -0,0 +1,266 @@+/**+ * Fence schema for repair (#6188): canonical columns, header aliases, the+ * strict parsers' per-cell checks and the Tier 1 value rules.+ *+ * The cell checks mirror `parseFactsFence` / `parseTakesFence` exactly (the+ * numeric patterns are private there, so they are restated here);+ * `test/fence-repair-raw-rows.test.ts` proves the mirror over every fence+ * fixture in the test suite. The rules map one written value to one+ * canonical value and never look at other cells, so the validator can+ * recompute what a rule may output for a given before value.+ */+import { isValidHolder, TAKE_KIND_VALUES } from '../takes-fence.ts';+import type { FenceKind } from './types.ts';++export const FACTS_COLUMNS = [+ '#', 'claim', 'kind', 'confidence', 'visibility', 'notability', 'valid_from', 'valid_until', 'source', 'context',+ 'claim_metric', 'claim_value', 'claim_unit', 'claim_period',+] as const;+export const TAKES_COLUMNS = [+ '#', 'claim', 'kind', 'who', 'weight', 'since', 'source', 'resolved', 'quality', 'evidence', 'value', 'unit', 'by',+] as const;++/** Columns per kind, in canonical order. */+export const COLUMNS: Record<FenceKind, readonly string[]> = { facts: FACTS_COLUMNS, takes: TAKES_COLUMNS };+/** The narrow canonical layout (facts 10, takes 7); the wide one adds the remaining columns. */+export const BASE_WIDTH: Record<FenceKind, number> = { facts: 10, takes: 7 };+/** Fewest cells the strict parser reads (facts 9 = no context, takes 6 = no source). */+export const MIN_CELLS: Record<FenceKind, number> = { facts: 9, takes: 6 };+/** Columns read by header name rather than position (takes resolution columns). */+export const NAMED_COLUMNS: Record<FenceKind, ReadonlySet<string>> = {+ facts: new Set(),+ takes: new Set(['resolved', 'quality', 'evidence', 'value', 'unit', 'by']),+};+/** Columns a row may omit at its end and still parse. */+export const TOLERATED_TRAILING: Record<FenceKind, ReadonlySet<string>> = {+ facts: new Set(['context', 'claim_metric', 'claim_value', 'claim_unit', 'claim_period']),+ takes: new Set(['source', 'resolved', 'quality', 'evidence', 'value', 'unit', 'by']),+};+/** Write defaults for a required facts column absent from the whole header (`column_default`, T6). */+export const COLUMN_DEFAULTS: Record<FenceKind, Readonly<Record<string, string>>> = {+ facts: { confidence: '1.0', notability: 'medium', visibility: 'private' },+ takes: {},+};++/** Header and separator text exactly as `renderFactsTable` / `renderTakesFence` emit them. */+export const CANONICAL_HEADER: Record<FenceKind, { narrow: string; wide: string; narrowSep: string; wideSep: string }> = {+ facts: {+ narrow: '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',+ wide: '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |',+ narrowSep: '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',+ wideSep: '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|',+ },+ takes: {+ narrow: '| # | claim | kind | who | weight | since | source |',+ wide: '| # | claim | kind | who | weight | since | source | resolved | quality | evidence | value | unit | by |',+ narrowSep: '|---|-------|------|-----|--------|-------|--------|',+ wideSep: '|---|-------|------|-----|--------|-------|--------|----------|---------|----------|-------|------|----|',+ },+};++const ROW_NUM_ALIASES = ['#', 'row', 'row #', 'row num', 'row number', 'no', 'no.', 'num'];+const HEADER_ALIASES: Record<FenceKind, Readonly<Record<string, readonly string[]>>> = {+ facts: {+ '#': ROW_NUM_ALIASES,+ claim: ['claim', 'fact', 'statement'],+ kind: ['kind', 'type', 'category'],+ confidence: ['confidence', 'conf', 'weight'],+ visibility: ['visibility', 'vis'],+ notability: ['notability', 'importance'],+ valid_from: ['valid from', 'since', 'date', 'from'],+ valid_until: ['valid until', 'until', 'to'],+ source: ['source', 'src'],+ context: ['context', 'notes', 'note'],+ claim_metric: ['claim metric', 'metric'],+ claim_value: ['claim value', 'value'],+ claim_unit: ['claim unit', 'unit'],+ claim_period: ['claim period', 'period'],+ },+ takes: {+ '#': ROW_NUM_ALIASES,+ claim: ['claim', 'take', 'statement'],+ kind: ['kind', 'type'],+ who: ['who', 'holder'],+ weight: ['weight', 'confidence', 'conf'],+ since: ['since', 'date', 'as of'],+ source: ['source', 'src'],+ resolved: ['resolved'],+ quality: ['quality'],+ evidence: ['evidence'],+ value: ['value'],+ unit: ['unit'],+ by: ['by'],+ },+};++/** Lowercase, trim, and fold runs of whitespace, `_` and `-` to one space. */+export function lookupKey(text: string): string {+ return text.trim().toLowerCase().replace(/[\s_-]+/g, ' ');+}++const ALIAS_INDEX: Record<FenceKind, Map<string, string>> = {+ facts: aliasIndex('facts'),+ takes: aliasIndex('takes'),+};++function aliasIndex(kind: FenceKind): Map<string, string> {+ const index = new Map<string, string>();+ for (const [column, aliases] of Object.entries(HEADER_ALIASES[kind])) {+ index.set(lookupKey(column), column);+ for (const alias of aliases) index.set(lookupKey(alias), column);+ }+ return index;+}++/** The canonical column a header cell names, or null when it maps to none. */+export function canonicalColumn(kind: FenceKind, headerCell: string): string | null {+ return ALIAS_INDEX[kind].get(lookupKey(headerCell)) ?? null;+}++const FACT_KINDS: ReadonlySet<string> = new Set(['event', 'preference', 'commitment', 'belief', 'fact', 'idea']);+const VISIBILITIES: ReadonlySet<string> = new Set(['private', 'world']);+const NOTABILITIES: ReadonlySet<string> = new Set(['high', 'medium', 'low']);+const PLAIN_NUMBER_RE = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;+const NUMERIC_CELL_RE = /^([+-]?)[$€£]?((?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\.\d+)((?:[eE][+-]?\d+)?)\s*([kmb]?)$/i;++/** Schema vocabulary per column, for `FenceIssue.allowed`. */+export const ALLOWED: Record<FenceKind, Readonly<Record<string, readonly string[]>>> = {+ facts: {+ kind: [...FACT_KINDS],+ visibility: [...VISIBILITIES],+ notability: [...NOTABILITIES],+ confidence: ['a number from 0 to 1'],+ claim_value: ['a number, optionally with 1,234 separators or a k/M/B suffix'],+ '#': ['a positive whole number'],+ },+ takes: {+ kind: [...TAKE_KIND_VALUES],+ who: ['world', 'brain', 'people/<slug>', 'companies/<slug>'],+ weight: ['a number from 0 to 1'],+ '#': ['a positive whole number'],+ },+};++/** The strict parser's row-number read (`parseInt`, positive). */+export function parseRowNum(text: string): number | null {+ const n = parseInt(text, 10);+ return Number.isFinite(n) && n > 0 ? n : null;+}++/** True when the strict parser accepts `text` in `column`; free-text columns always pass. */+export function cellValid(kind: FenceKind, column: string, text: string): boolean {+ const lower = text.trim().toLowerCase();+ switch (kind === 'facts' ? column : `takes:${column}`) {+ case '#': case 'takes:#': return parseRowNum(text) !== null;+ case 'kind': return FACT_KINDS.has(lower);+ case 'visibility': return VISIBILITIES.has(lower);+ case 'notability': return NOTABILITIES.has(lower);+ case 'confidence': return confidenceValid(text);+ case 'claim_value': return !text.trim() || NUMERIC_CELL_RE.test(text.trim());+ case 'takes:kind': return TAKE_KIND_VALUES.has(lower);+ case 'takes:who': return isValidHolder(text.trim());+ case 'takes:weight': return Number.isFinite(parseFloat(text));+ default: return true;+ }+}++function confidenceValid(text: string): boolean {+ const trimmed = text.trim();+ if (!PLAIN_NUMBER_RE.test(trimmed)) return false;+ const n = Number(trimmed);+ return Number.isFinite(n) && n >= 0 && n <= 1;+}++const FACT_KIND_SYNONYMS: Readonly<Record<string, string>> = {+ proposal: 'idea', suggestion: 'idea', hypothesis: 'idea',+ opinion: 'belief', view: 'belief', insight: 'belief', assessment: 'belief', frame: 'belief',+ promise: 'commitment', pledge: 'commitment',+ meeting: 'event', launch: 'event', announcement: 'event', milestone: 'event',+};+const TAKE_KIND_SYNONYMS: Readonly<Record<string, string>> = {+ assessment: 'take', recommendation: 'take', 'strategic position': 'take', opinion: 'take', view: 'take',+ prediction: 'bet', forecast: 'bet',+ guess: 'hunch', intuition: 'hunch',+};+const PRIVATE_SYNONYMS: ReadonlySet<string> = new Set(['internal', 'team', 'confidential', 'restricted', 'secret', 'shared']);+const NOTABILITY_SYNONYMS: Readonly<Record<string, string>> = {+ critical: 'high', 'very high': 'high', highest: 'high', 'very low': 'low', minor: 'low',+};+const BRAIN_ALIASES: ReadonlySet<string> = new Set(['system', 'assistant', 'ai', 'agent', 'gbrain', 'model', 'brain']);++/** `kind_map` for facts: any word maps (unknown words to `fact`). */+export function factsKindMap(word: string): string {+ const key = lookupKey(word);+ if (FACT_KINDS.has(key)) return key;+ return FACT_KIND_SYNONYMS[key] ?? 'fact';+}++/** `kind_map` for takes: only the explicit synonym table; a pack-declared kind never maps. */+export function takesKindMap(word: string, packKinds: readonly string[] = []): string | null {+ const key = lookupKey(word);+ if (packKinds.some(kind => lookupKey(kind) === key)) return null;+ return TAKE_KIND_SYNONYMS[key] ?? null;+}++/** `enum_synonym` for visibility and notability; null when the word has no mapping. */+export function enumSynonym(column: string, word: string, pageVisibility: 'private' | 'world'): string | null {+ const key = lookupKey(word);+ if (column === 'visibility') {+ if (VISIBILITIES.has(key)) return key;+ if (PRIVATE_SYNONYMS.has(key)) return 'private';+ if (key === 'public') return pageVisibility === 'world' ? 'world' : 'private';+ return null;+ }+ if (column === 'notability') return NOTABILITIES.has(key) ? key : NOTABILITY_SYNONYMS[key] ?? null;+ return null;+}++/** `holder_alias`: assistant-style holders to `brain`; case variants of `brain`/`world`. */+export function holderAlias(holder: string): 'brain' | 'world' | null {+ const key = lookupKey(holder);+ if (key === 'world') return 'world';+ return BRAIN_ALIASES.has(key) ? 'brain' : null;+}++/**+ * `confidence_format`: the number a confidence/weight cell means (`85%` is+ * 0.85; stray inner whitespace dropped), or null when it is not numeric.+ */+export function confidenceNumber(text: string): number | null {+ const compact = text.replace(/\s+/g, '');+ const percent = /^([+-]?(?:\d+(?:\.\d+)?|\.\d+))%$/.exec(compact);+ if (percent) return Number(percent[1]) / 100;+ return PLAIN_NUMBER_RE.test(compact) ? Number(compact) : null;+}++/** Canonical text for a 0..1 number (the renderers' `1.0` / `0.85` form). */+export function formatConfidence(n: number): string {+ if (Number.isInteger(n)) return n.toFixed(1);+ return String(parseFloat(n.toFixed(6)));+}++/** The `confidence_format` output for a cell, or null when the rule does not apply. */+export function confidenceFormat(text: string): string | null {+ const n = confidenceNumber(text);+ return n !== null && n >= 0 && n <= 1 ? formatConfidence(n) : null;+}++/** The facts context after `kind_map` keeps the original word (after any existing text); an empty word adds nothing. */+export function appendOriginalKind(context: string, word: string): string {+ if (!word.trim()) return context;+ const note = `original kind: ${word.trim()}`;+ return context.trim() ? `${context.trim()}; ${note}` : note;+}++/** The `superseded by #N` reference a facts context or takes source cell carries. */+export function supersededRef(text: string): number | null {+ const m = /superseded by #(\d+)/i.exec(text);+ if (!m) return null;+ const n = parseInt(m[1]!, 10);+ return n > 0 ? n : null;+}++/** Whitespace-collapsed text for comparisons. */+export function collapse(text: string): string {+ return text.replace(/\s+/g, ' ').trim();+}diff --git a/src/core/fence-repair/types.ts b/src/core/fence-repair/types.tsnew file mode 100644index 0000000000..9513eecb59--- /dev/null+++ b/src/core/fence-repair/types.ts@@ -0,0 +1,104 @@+/**+ * Shared types for malformed facts/takes fence repair (#6188).+ *+ * Every issue, fix and gate failure is location-only: fence, section, row+ * number, column name and section line. None carries claim text, holder+ * names or any other cell value, so they are safe in holds, receipts,+ * refusals, notices and commit messages.+ */++export type FenceKind = 'facts' | 'takes';+export type FenceSection = 'body' | 'timeline';++/**+ * The tier that clears an issue: Tier 1 rules (`deterministic`), Tier 2+ * verified holders (`resolver`), Tier 3 model rewrite (`llm`), or a person+ * (`manual`).+ */+export type FenceTier = 'deterministic' | 'resolver' | 'llm' | 'manual';++/** Validator gate letters (a)-(g). */+export type GateLetter = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g';++/** The class each applied fix carries in receipts, holds and previews. */+export type FixClass =+ | 'close_fence'+ | 'marker_form'+ | 'renumber'+ | 'column_default'+ | 'header_alias'+ | 'enum_synonym'+ | 'kind_map'+ | 'holder_alias'+ | 'confidence_format'+ | 'holder_verified';++/** Every fence reason; `FENCE_REASONS` (reasons.ts) holds one entry per code. */+export type FenceReason =+ // Screen residual, Tier 3.+ | 'header_unmapped' | 'no_header' | 'row_before_header' | 'short_row' | 'extra_cells'+ // Screen residual, Tier 2 then manual.+ | 'holder_unresolved'+ // Screen residual, manual only.+ | 'missing_begin' | 'split_rows' | 'unclosed_trailing_content' | 'marker_near_miss' | 'repeated_marker'+ | 'takes_in_facts' | 'superseded_ambiguous' | 'enum_unmapped' | 'weight_missing' | 'holder_missing'+ | 'confidence_out_of_range' | 'claim_value_invalid' | 'takes_kind_unsupported'+ // Preparation and publication.+ | 'unparseable' | 'row_collision' | 'quoted_fence_rows' | 'stored_row_collision'+ | 'withdrawn_claim_in_malformed_fence' | 'target_fence_malformed' | 'prepare_time' | 'normalizer_failed'+ // Repair runs.+ | 'llm_unavailable' | 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_truncated' | 'llm_disabled'+ | 'budget_exhausted' | 'no_pricing' | 'ledger_unavailable' | 'owner_unavailable' | 'owner_cli_required'+ | 'sync_in_progress' | 'time_budget' | 'changed_since_read' | 'changed_since_preview'+ // Validator gates.+ | 'still_invalid' | 'claim_changed' | 'row_number_changed' | 'visibility_loosened'+ | 'row_count_changed' | 'cell_changed' | 'protection_loosened';++/** Where an issue or fix sits. Location only: never a cell value. */+export interface FenceLocation {+ fence: FenceKind;+ section: FenceSection;+ /** Row number (for a fix, the number after renumbering); null for a fence-level location or a row without a valid number. */+ row: number | null;+ /** Canonical column (`#`, `claim`, `kind`, `who`, ...); null for a whole row or fence. */+ column: string | null;+ /** 1-based line within the section of the before page; null when unknown. */+ line: number | null;+}++export interface FenceIssue extends FenceLocation {+ reason: FenceReason;+ /** Schema vocabulary for the column (never a cell value). */+ allowed?: readonly string[];+}++export interface FenceFix extends FenceLocation {+ class: FixClass;+ /** `renumber` only: the row's number before the fix (null when it had none). */+ from?: number | null;+}++/** Stored canonical rows for a page: row number to claim text (strikethrough stripped). */+export interface StoredRowMap {+ facts: ReadonlyMap<number, string>;+ takes: ReadonlyMap<number, string>;+}++export interface FenceCtx {+ /** `effectiveVisibility(page)`. */+ pageVisibility: 'private' | 'world';+ /** Stored facts/takes rows; needed only when a `renumber` fix is planned. */+ storedRows?: StoredRowMap;+ /** Tier 2: before-holder text to a verified `people/` or `companies/` slug. */+ verifiedHolders?: ReadonlyMap<string, string>;+ /** Takes kinds the active schema pack declares (`takes_kinds`). */+ takesPackKinds?: readonly string[];+ /** Row numbers of rows hidden from a remote caller; never renumbered or reallocated. */+ hiddenRows?: ReadonlySet<number>;+}++/** The two canonical body sections. Callers pass their full page type and get it back. */+export interface FencePage {+ compiled_truth: string;+ timeline: string;+}