Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(fence-repair): pure Tier 1 normalizer, raw-row extraction, validator gates and reason table (#6188)

garrytan6d2c83171102
diff --git a/src/core/fence-repair/content.ts b/src/core/fence-repair/content.ts
new file mode 100644
index 0000000000..8ab1b2d3eb
--- /dev/null
+++ b/src/core/fence-repair/content.ts
@@ -0,0 +1,240 @@
+/**
+ * Content Tier 1 rules over both sections of a page (#6188): `header_alias`
+ * and `column_default` (header level), the cell rules in rules.ts, and
+ * prior-aware `renumber` across body and timeline. Of two rows sharing a
+ * number, the one matching the stored row keeps it; otherwise a row in a
+ * fence that parses clean keeps it (Invariant 0), and the first occurrence
+ * only breaks the remaining tie.
+ *
+ * Cells are edited in place by source span; a row is re-rendered only when
+ * its header is rewritten, and then every cell keeps its source text and only
+ * moves into canonical order. Nothing is re-rendered through
+ * `renderFactsTable` / `renderTakesFence`.
+ */
+import { parseFactsFence } from '../facts-fence.ts';
+import { stripStrikethrough } from '../fence-shared.ts';
+import { parseTakesFence } from '../takes-fence.ts';
+import { planRowRules, type CellText, type RowPlan } from './rules.ts';
+import { extractRawRows, rowNumOf, type RawFence, type RawRow, type RawSection } from './raw-rows.ts';
+import { BASE_WIDTH, canonicalColumn, CANONICAL_HEADER, collapse, COLUMN_DEFAULTS, COLUMNS, supersededRef } from './schema.ts';
+import { applyEdits, fenceBlocked, type Edit } from './structure.ts';
+import type { FenceCtx, FenceFix, FenceIssue, FenceKind, FenceReason, FenceSection } from './types.ts';
+
+export interface ContentResult {
+ texts: Record<FenceSection, string>;
+ fixes: FenceFix[];
+ residual: FenceIssue[];
+}
+
+/** Header rewrite plan for a fence whose header is out of canonical order. */
+interface Rewrite {
+ target: readonly string[];
+ defaults: string[];
+}
+
+interface RowWork {
+ fence: RawFence;
+ row: RawRow;
+ num: number | null;
+ plan: RowPlan | null;
+ /** May take a new number (aligned, in a workable fence, not hidden). */
+ eligible: boolean;
+ needsNumber: boolean;
+ /** The row's fence parses with no warning (Invariant 0 prefers to leave it alone). */
+ clean: boolean;
+ newNum?: number;
+}
+
+interface FenceWork {
+ fence: RawFence;
+ rewrite: Rewrite | null;
+ rows: RowWork[];
+}
+
+interface Pass {
+ ctx: FenceCtx;
+ fixes: FenceFix[];
+ residual: FenceIssue[];
+ edits: Record<FenceSection, Edit[]>;
+ works: FenceWork[];
+ /** All rows of each kind in page order (body first), workable or not. */
+ rows: Record<FenceKind, RowWork[]>;
+ /** Next number to hand out; one counter for both kinds, so no new number repeats on the page. */
+ next: number | null;
+ nextNumber: () => number;
+}
+
+const REPORTED: ReadonlySet<FenceReason> = new Set(['row_before_header', 'no_header', 'short_row', 'extra_cells']);
+
+/** Plan and apply the content rules; `nextNumber` is called only when a row needs a new number. */
+export function contentPass(texts: Record<FenceSection, string>, ctx: FenceCtx, nextNumber: () => number): ContentResult {
+ const pass: Pass = { ctx, fixes: [], residual: [], edits: { body: [], timeline: [] }, works: [], rows: { facts: [], takes: [] }, next: null, nextNumber };
+ for (const section of ['body', 'timeline'] as const) planSection(pass, extractRawRows(texts[section], section));
+ for (const kind of ['facts', 'takes'] as const) renumber(pass, kind);
+ for (const work of pass.works) emitFence(pass, work);
+ return {
+ texts: { body: applyEdits(texts.body, pass.edits.body), timeline: applyEdits(texts.timeline, pass.edits.timeline) },
+ fixes: pass.fixes,
+ residual: pass.residual,
+ };
+}
+
+function issueAt(fence: RawFence, reason: FenceReason, line: number | null, row: number | null = null, column: string | null = null, allowed?: readonly string[]): FenceIssue {
+ const out: FenceIssue = { fence: fence.kind, section: fence.section, row, column, line, reason };
+ return allowed ? { ...out, allowed } : out;
+}
+
+function planSection(pass: Pass, raw: RawSection): void {
+ pass.residual.push(...raw.issues);
+ for (const fence of raw.fences) {
+ if (!fence.primary) continue;
+ pass.residual.push(...fence.issues.filter(i => i.reason === 'repeated_marker'));
+ const balanced = fence.end !== null && !fence.begin.nearMiss && !fence.end.nearMiss;
+ const workable = balanced && !fenceBlocked(raw, fence) && fenceWorkable(pass, fence);
+ if (balanced) pass.residual.push(...fence.issues.filter(i => REPORTED.has(i.reason)));
+ const rewrite = workable && fence.needsRewrite ? planRewrite(fence) : null;
+ const clean = (fence.kind === 'facts' ? parseFactsFence(raw.text) : parseTakesFence(raw.text)).warnings.length === 0;
+ const rows = fence.rows.map(row => rowWork(pass, fence, row, workable, clean));
+ pass.rows[fence.kind].push(...rows);
+ if (workable) pass.works.push({ fence, rewrite, rows });
+ }
+}
+
+/** A balanced fence the content rules may edit; reports why not otherwise. */
+function fenceWorkable(pass: Pass, fence: RawFence): boolean {
+ if (!fence.header) return false;
+ const headerLine = fence.header.line;
+ if (fence.kind === 'facts' && takesShaped(fence)) {
+ pass.residual.push(issueAt(fence, 'takes_in_facts', headerLine));
+ return false;
+ }
+ if (!fence.needsRewrite) return true;
+ if (fence.columns.some(c => c === null)) {
+ pass.residual.push(issueAt(fence, 'header_unmapped', headerLine, null, null, COLUMNS[fence.kind]));
+ return false;
+ }
+ const missing = fence.kind === 'takes' ? (['who', 'weight'] as const).filter(c => !fence.columns.includes(c)) : [];
+ for (const column of missing) pass.residual.push(issueAt(fence, column === 'who' ? 'holder_missing' : 'weight_missing', headerLine, null, column));
+ return !missing.length && fence.rows.every(r => r.beforeHeader || r.shape === 'ok');
+}
+
+/** A takes table (a holder column, no facts-only columns) inside a facts fence. */
+function takesShaped(fence: RawFence): boolean {
+ const cells = fence.header!.cells.map(c => c.text);
+ const facts = cells.map(c => canonicalColumn('facts', c));
+ return cells.some(c => canonicalColumn('takes', c) === 'who') && !facts.includes('visibility') && !facts.includes('notability');
+}
+
+function planRewrite(fence: RawFence): Rewrite {
+ const { kind } = fence;
+ const wide = fence.columns.some(c => c !== null && COLUMNS[kind].indexOf(c) >= BASE_WIDTH[kind]);
+ const target = COLUMNS[kind].slice(0, wide ? COLUMNS[kind].length : BASE_WIDTH[kind]);
+ const defaults = Object.keys(COLUMN_DEFAULTS[kind]).filter(c => !fence.columns.includes(c));
+ return { target, defaults };
+}
+
+function rowWork(pass: Pass, fence: RawFence, row: RawRow, workable: boolean, clean: boolean): RowWork {
+ const num = rowNumOf(fence, row);
+ const aligned = workable && !row.beforeHeader && row.shape === 'ok';
+ const plan = aligned ? planRowRules(fence.kind, cellTexts(row), pass.ctx) : null;
+ const hidden = num !== null && (pass.ctx.hiddenRows?.has(num) ?? false);
+ const minted = aligned && !fence.columns.includes('#') && fence.needsRewrite;
+ return { fence, row, num, plan, eligible: aligned && !hidden, needsNumber: minted || (plan?.badNumber ?? false), clean };
+}
+
+function cellTexts(row: RawRow): Map<string, CellText> {
+ return new Map([...row.byColumn].map(([column, cell]) => [column, { raw: cell.raw, text: cell.text }]));
+}
+
+/** Claim text the stored map is keyed by: strikethrough stripped, whitespace collapsed. */
+function claimKey(row: RawRow): string {
+ return collapse(stripStrikethrough(row.byColumn.get('claim')?.text ?? '').text);
+}
+
+function renumber(pass: Pass, kind: FenceKind): void {
+ const rows = pass.rows[kind];
+ const refColumn = kind === 'facts' ? 'context' : 'source';
+ const refs = new Set(rows.map(w => supersededRef(w.row.byColumn.get(refColumn)?.text ?? '')).filter(n => n !== null));
+ const groups = new Map<number, RowWork[]>();
+ for (const w of rows) if (w.num !== null) groups.set(w.num, [...(groups.get(w.num) ?? []), w]);
+ for (const [num, group] of groups) {
+ if (group.length < 2) continue;
+ if (refs.has(num)) {
+ for (const w of group) pass.residual.push(issueAt(w.fence, 'superseded_ambiguous', w.row.line, num, '#'));
+ continue;
+ }
+ const stored = pass.ctx.storedRows?.[kind].get(num);
+ const keeper = group.find(w => stored !== undefined && claimKey(w.row) === collapse(stored))
+ ?? group.find(w => w.clean) ?? group[0]!;
+ for (const w of group) {
+ if (w === keeper) continue;
+ if (w.eligible) w.needsNumber = true;
+ else if (pass.ctx.hiddenRows?.has(num)) pass.residual.push(issueAt(w.fence, 'row_collision', w.row.line, num, '#'));
+ }
+ }
+ for (const w of rows) {
+ if (!w.needsNumber || !w.eligible) continue;
+ pass.next ??= pass.nextNumber();
+ w.newNum = pass.next++;
+ }
+}
+
+function finalNum(w: RowWork): number | null {
+ return w.newNum ?? w.num;
+}
+
+function emitFence(pass: Pass, work: FenceWork): void {
+ const { fence } = work;
+ if (work.rewrite) emitRewrite(pass, fence, work.rewrite);
+ for (const w of work.rows) {
+ if (!w.plan) continue;
+ const row = finalNum(w);
+ if (w.newNum !== undefined) {
+ pass.fixes.push({ fence: fence.kind, section: fence.section, row, column: '#', line: w.row.line, class: 'renumber', from: w.num });
+ }
+ for (const change of w.plan.changes) {
+ if (change.column === 'context' && change.class === 'kind_map') continue;
+ pass.fixes.push({ fence: fence.kind, section: fence.section, row, column: change.column, line: w.row.line, class: change.class });
+ }
+ for (const i of w.plan.issues) pass.residual.push(issueAt(fence, i.reason, w.row.line, row, i.column, i.allowed));
+ if (work.rewrite) pass.edits[fence.section].push(renderRow(w, work.rewrite));
+ else pass.edits[fence.section].push(...cellEdits(w));
+ }
+}
+
+function emitRewrite(pass: Pass, fence: RawFence, rewrite: Rewrite): void {
+ const header = fence.header!;
+ const wide = rewrite.target.length > BASE_WIDTH[fence.kind];
+ const text = CANONICAL_HEADER[fence.kind];
+ pass.edits[fence.section].push({ start: header.start, end: header.end, text: wide ? text.wide : text.narrow });
+ const sep = fence.separators.find(s => s.line === header.line + 1);
+ if (sep) pass.edits[fence.section].push({ start: sep.start, end: sep.end, text: wide ? text.wideSep : text.narrowSep });
+ const at = { fence: fence.kind, section: fence.section, row: null, line: header.line };
+ pass.fixes.push({ ...at, column: null, class: 'header_alias' });
+ for (const column of rewrite.defaults) pass.fixes.push({ ...at, column, class: 'column_default' });
+}
+
+/** The row re-rendered in canonical column order from its own source cells. */
+function renderRow(w: RowWork, rewrite: Rewrite): Edit {
+ const changes = new Map(w.plan!.changes.map(c => [c.column, c.raw]));
+ const defaults = COLUMN_DEFAULTS[w.fence.kind];
+ const cells = rewrite.target.map(column => {
+ if (column === '#' && w.newNum !== undefined) return String(w.newNum);
+ return changes.get(column) ?? w.row.byColumn.get(column)?.raw ?? defaults[column] ?? '';
+ });
+ return { start: w.row.start, end: w.row.end, text: `| ${cells.join(' | ')} |` };
+}
+
+/** In-place cell edits; a facts context the row lacks is appended as its last cell. */
+function cellEdits(w: RowWork): Edit[] {
+ const edits: Edit[] = [];
+ const { row } = w;
+ const num = row.byColumn.get('#');
+ if (w.newNum !== undefined && num) edits.push({ start: num.start, end: num.end, text: String(w.newNum) });
+ for (const change of w.plan!.changes) {
+ const cell = row.byColumn.get(change.column);
+ if (cell) edits.push({ start: cell.start, end: cell.end, text: change.raw });
+ else edits.push({ start: row.end, end: row.end, text: row.closed ? ` ${change.raw} |` : ` | ${change.raw}` });
+ }
+ return edits;
+}
diff --git a/src/core/fence-repair/normalize.ts b/src/core/fence-repair/normalize.ts
new file mode 100644
index 0000000000..21880d2493
--- /dev/null
+++ b/src/core/fence-repair/normalize.ts
@@ -0,0 +1,120 @@
+/**
+ * Tier 1 fence normalizer (#6188): pure, deterministic, free.
+ *
+ * `normalizeFences(page, ctx)` fixes what has one obvious meaning (a missing
+ * end marker with nothing after the table, two-dash takes markers, row-number
+ * repairs, header aliases and order, header-level write defaults, enum,
+ * kind and holder synonyms, percent confidences) and reports the rest as
+ * location-only residual issues. A page whose fences already compile is
+ * returned unchanged (the same object), and every other byte outside the
+ * edited cells, markers and headers is kept verbatim. The result is a fixed
+ * point: normalizing it again changes nothing.
+ *
+ * Callers that must never fail on a normalizer bug use `safeNormalizeFences`,
+ * which turns a throw into the residual reason `normalizer_failed`.
+ */
+import { contentPass } from './content.ts';
+import { sectionsOf, strictFailures, strictPageClean } from './page-checks.ts';
+import { extractRawRows, rowNumOf } from './raw-rows.ts';
+import { structuralPass } from './structure.ts';
+import type { FenceCtx, FenceFix, FenceIssue, FencePage, FenceSection, StoredRowMap } from './types.ts';
+
+/** Rule-set version, stored on fence holds as `fence_version`; bump when a rule widens so older holds are re-screened. */
+export const FENCE_RULES_VERSION = 1;
+
+export interface NormalizeResult<T extends FencePage> {
+ page: T;
+ fixes: FenceFix[];
+ residual: FenceIssue[];
+}
+
+/** The section mentions a facts or takes marker (cheap pre-check; no fence work without it). */
+export function hasFenceText(text: string | null | undefined): boolean {
+ return !!text && (text.includes('gbrain:facts:') || text.includes('gbrain:takes:'));
+}
+
+export function normalizeFences<T extends FencePage>(page: T, ctx: FenceCtx): NormalizeResult<T> {
+ if (!sectionsOf(page).some(([, text]) => hasFenceText(text)) || strictPageClean(page)) return { page, fixes: [], residual: [] };
+ const fixes: FenceFix[] = [];
+ const residual: FenceIssue[] = [];
+ const texts: Record<FenceSection, string> = { body: '', timeline: '' };
+ for (const [section, text] of sectionsOf(page)) {
+ const pass = structuralPass(text, section);
+ texts[section] = pass.text;
+ fixes.push(...pass.fixes);
+ residual.push(...pass.residual);
+ }
+ const content = contentPass(texts, ctx, () => Math.max(nextFreeRowNum(page, ctx.storedRows), maxHidden(ctx) + 1));
+ fixes.push(...content.fixes);
+ residual.push(...content.residual);
+ const out = withSections(page, content.texts);
+ if (!residual.length) residual.push(...unparseable(out));
+ return { page: out, fixes, residual };
+}
+
+/** Like `normalizeFences`, but a thrown error becomes residual `normalizer_failed` and the page is returned unchanged. */
+export function safeNormalizeFences<T extends FencePage>(page: T, ctx: FenceCtx): NormalizeResult<T> {
+ try {
+ return normalizeFences(page, ctx);
+ } catch {
+ return { page, fixes: [], residual: failedIssues(page) };
+ }
+}
+
+function failedIssues(page: FencePage): FenceIssue[] {
+ const issues: FenceIssue[] = [];
+ try {
+ for (const [section, text] of sectionsOf(page)) {
+ for (const fence of ['facts', 'takes'] as const) {
+ if (text.includes(`gbrain:${fence}:`)) issues.push({ fence, section, row: null, column: null, line: null, reason: 'normalizer_failed' });
+ }
+ }
+ } catch {
+ // The page itself cannot be read; report one location-free failure below.
+ }
+ return issues.length ? issues : [{ fence: 'facts', section: 'body', row: null, column: null, line: null, reason: 'normalizer_failed' }];
+}
+
+function withSections<T extends FencePage>(page: T, texts: Record<FenceSection, string>): T {
+ const sameBody = texts.body === (page.compiled_truth ?? '');
+ const sameTimeline = texts.timeline === (page.timeline ?? '');
+ if (sameBody && sameTimeline) return page;
+ return {
+ ...page,
+ compiled_truth: sameBody ? page.compiled_truth : texts.body,
+ timeline: sameTimeline ? page.timeline : texts.timeline,
+ };
+}
+
+/** Safety net: a page the rules report clean must compile; anything else is residual `unparseable`. */
+function unparseable(page: FencePage): FenceIssue[] {
+ return strictFailures(page).map(f => ({
+ fence: f.fence, section: f.section ?? 'body', row: f.rows[0] ?? null, column: null, line: null,
+ reason: f.check === 'repeated_marker' ? 'repeated_marker' : f.check === 'row_collision' ? 'row_collision' : 'unparseable',
+ }));
+}
+
+function maxHidden(ctx: FenceCtx): number {
+ return ctx.hiddenRows?.size ? Math.max(...ctx.hiddenRows) : 0;
+}
+
+/**
+ * The number for a new fence row on this page.
+ *
+ * Contract: must never return a number already used on this page. It is one
+ * more than the largest of every fence row number (live and struck, facts and
+ * takes, body and timeline, including rows a strict parse rejects) and every
+ * stored facts/takes row number the caller passes. A number whose only
+ * evidence was deleted before stored rows existed cannot be seen here.
+ */
+export function nextFreeRowNum(page: FencePage, storedRows?: StoredRowMap): number {
+ let max = 0;
+ for (const [section, text] of sectionsOf(page)) {
+ for (const fence of extractRawRows(text, section).fences) {
+ for (const row of fence.rows) max = Math.max(max, rowNumOf(fence, row) ?? 0);
+ }
+ }
+ for (const n of storedRows?.facts.keys() ?? []) max = Math.max(max, n);
+ for (const n of storedRows?.takes.keys() ?? []) max = Math.max(max, n);
+ return max + 1;
+}
diff --git a/src/core/fence-repair/page-checks.ts b/src/core/fence-repair/page-checks.ts
new file mode 100644
index 0000000000..f6b4e3b0c8
--- /dev/null
+++ b/src/core/fence-repair/page-checks.ts
@@ -0,0 +1,100 @@
+/**
+ * Page-level checks shared by the normalizer and the validator (#6188).
+ *
+ * `strictFailures` is gate (a): the same three checks
+ * `compileCanonicalProjections` refuses on (a repeated marker outside code,
+ * any strict-parser warning, a row number used twice across the page), so a
+ * page with none of them compiles. `exposedLines` is gate (g): text that the
+ * privacy boundary (`protectedRegions`, which `sanitizeRemoteBody`, the
+ * chunker and the strip functions share) hid before a repair and shows after
+ * it.
+ */
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../facts-fence.ts';
+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';
+import { indexOfOutsideCode, protectedRegions, scanMarkdownCode } from '../fence-scan.ts';
+import type { FenceKind, FencePage, FenceSection } from './types.ts';
+
+export interface StrictFailure {
+ section: FenceSection | null;
+ fence: FenceKind;
+ check: 'repeated_marker' | 'warnings' | 'row_collision';
+ /** Row numbers involved (collisions only). */
+ rows: number[];
+}
+
+const MARKER_KIND: ReadonlyArray<[string, FenceKind]> = [
+ [FACTS_FENCE_BEGIN, 'facts'], [FACTS_FENCE_END, 'facts'], [TAKES_FENCE_BEGIN, 'takes'], [TAKES_FENCE_END, 'takes'],
+];
+const PROTECTED_PAIRS = [
+ { begin: FACTS_FENCE_BEGIN, end: FACTS_FENCE_END },
+ { begin: TAKES_FENCE_BEGIN, end: TAKES_FENCE_END },
+];
+
+/** The page's two sections, labelled. */
+export function sectionsOf(page: FencePage): Array<[FenceSection, string]> {
+ return [['body', page.compiled_truth ?? ''], ['timeline', page.timeline ?? '']];
+}
+
+/** Why `compileCanonicalProjections` would refuse this page's fences; empty when it compiles. */
+export function strictFailures(page: FencePage): StrictFailure[] {
+ const failures: StrictFailure[] = [];
+ const numbers: Record<FenceKind, number[]> = { facts: [], takes: [] };
+ for (const [section, text] of sectionsOf(page)) {
+ for (const kind of repeatedMarkerKinds(text)) failures.push({ section, fence: kind, check: 'repeated_marker', rows: [] });
+ const facts = parseFactsFence(text);
+ const takes = parseTakesFence(text);
+ if (facts.warnings.length) failures.push({ section, fence: 'facts', check: 'warnings', rows: [] });
+ if (takes.warnings.length) failures.push({ section, fence: 'takes', check: 'warnings', rows: [] });
+ numbers.facts.push(...facts.facts.map(f => f.rowNum));
+ numbers.takes.push(...takes.takes.map(t => t.rowNum));
+ }
+ for (const kind of ['facts', 'takes'] as const) {
+ const dup = numbers[kind].filter((n, i, all) => all.indexOf(n) !== i);
+ if (dup.length) failures.push({ section: null, fence: kind, check: 'row_collision', rows: [...new Set(dup)] });
+ }
+ return failures;
+}
+
+export function strictPageClean(page: FencePage): boolean {
+ return strictFailures(page).length === 0;
+}
+
+function repeatedMarkerKinds(text: string): Set<FenceKind> {
+ const kinds = new Set<FenceKind>();
+ if (!MARKER_KIND.some(([marker]) => text.includes(marker))) return kinds;
+ const code = scanMarkdownCode(text);
+ for (const [marker, kind] of MARKER_KIND) {
+ const first = indexOfOutsideCode(text, marker, 0, code);
+ if (first !== -1 && indexOfOutsideCode(text, marker, first + marker.length, code) !== -1) kinds.add(kind);
+ }
+ return kinds;
+}
+
+/** Lines the privacy boundary shows: text outside every protected region and before an ambiguous tail. */
+export function visibleLines(text: string): string[] {
+ const { regions, truncatedAt } = protectedRegions(text, PROTECTED_PAIRS);
+ const segments: string[] = [];
+ let cursor = 0;
+ for (const region of regions) {
+ segments.push(text.slice(cursor, region.start));
+ cursor = region.end;
+ }
+ segments.push(truncatedAt === -1 ? text.slice(cursor) : text.slice(cursor, truncatedAt));
+ return segments.flatMap(s => s.split(/\r\n|\r|\n/)).map(l => l.trim()).filter(Boolean);
+}
+
+/**
+ * Lines visible in `after` that were not visible in `before` (as a multiset).
+ * Rows that move into a fence are hidden, so they never count.
+ */
+export function exposedLines(before: string, after: string): string[] {
+ const seen = new Map<string, number>();
+ for (const line of visibleLines(before)) seen.set(line, (seen.get(line) ?? 0) + 1);
+ const exposed: string[] = [];
+ for (const line of visibleLines(after)) {
+ const left = seen.get(line) ?? 0;
+ if (left > 0) seen.set(line, left - 1);
+ else exposed.push(line);
+ }
+ return exposed;
+}
diff --git a/src/core/fence-repair/rules.ts b/src/core/fence-repair/rules.ts
new file mode 100644
index 0000000000..80ed48cc13
--- /dev/null
+++ b/src/core/fence-repair/rules.ts
@@ -0,0 +1,132 @@
+/**
+ * Tier 1 cell rules for one fence row (#6188), plus the outputs a rule may
+ * produce for a given before value (the validator's gate (f) uses those to
+ * accept a changed cell). Rules read only the cell they rewrite (`kind_map`
+ * also appends the original word to the facts `context` cell), so a row's
+ * plan never depends on other rows.
+ */
+import { escapeFenceCell } from '../fence-shared.ts';
+import { isValidHolder } from '../takes-fence.ts';
+import {
+ ALLOWED, appendOriginalKind, cellValid, confidenceFormat, enumSynonym, factsKindMap, holderAlias, supersededRef, takesKindMap,
+} from './schema.ts';
+import type { FenceCtx, FenceKind, FenceReason, FixClass } from './types.ts';
+
+/** A cell's source text and its parsed text. */
+export interface CellText {
+ raw: string;
+ text: string;
+}
+
+export interface CellChange {
+ column: string;
+ /** New source text for the cell (escaped for the table). */
+ raw: string;
+ class: FixClass;
+}
+
+export interface RuleIssue {
+ column: string;
+ reason: FenceReason;
+ allowed?: readonly string[];
+}
+
+export interface RowPlan {
+ changes: CellChange[];
+ issues: RuleIssue[];
+ /** The `#` cell is not a positive whole number. */
+ badNumber: boolean;
+}
+
+const RULE_COLUMNS: Record<FenceKind, readonly string[]> = {
+ facts: ['kind', 'confidence', 'visibility', 'notability', 'claim_value'],
+ takes: ['kind', 'who', 'weight'],
+};
+
+/** Plan Tier 1 changes and residual issues for one aligned row. */
+export function planRowRules(kind: FenceKind, cells: ReadonlyMap<string, CellText>, ctx: FenceCtx): RowPlan {
+ const plan: RowPlan = { changes: [], issues: [], badNumber: false };
+ const num = cells.get('#');
+ if (num && !cellValid(kind, '#', num.text)) plan.badNumber = true;
+ for (const column of RULE_COLUMNS[kind]) {
+ const cell = cells.get(column);
+ if (!cell || cellValid(kind, column, cell.text)) continue;
+ if (kind === 'facts' && column === 'kind') planFactsKind(plan, cell, cells.get('context'));
+ else planCell(plan, kind, column, cell, ctx);
+ }
+ return plan;
+}
+
+function residual(plan: RowPlan, kind: FenceKind, column: string, reason: FenceReason): void {
+ const allowed = ALLOWED[kind][column];
+ plan.issues.push(allowed ? { column, reason, allowed } : { column, reason });
+}
+
+function planFactsKind(plan: RowPlan, kindCell: CellText, contextCell: CellText | undefined): void {
+ const before = contextCell?.text ?? '';
+ const after = appendOriginalKind(before, kindCell.text);
+ if (supersededRef(before) !== supersededRef(after) || forgotten(before) !== forgotten(after)) {
+ residual(plan, 'facts', 'kind', 'enum_unmapped');
+ return;
+ }
+ plan.changes.push({ column: 'kind', raw: factsKindMap(kindCell.text), class: 'kind_map' });
+ if (after !== before) plan.changes.push({ column: 'context', raw: appendOriginalKind(contextCell?.raw ?? '', kindCell.raw), class: 'kind_map' });
+}
+
+function forgotten(context: string): boolean {
+ return /^forgotten\s*:/i.test(context.trim());
+}
+
+function planCell(plan: RowPlan, kind: FenceKind, column: string, cell: CellText, ctx: FenceCtx): void {
+ const out = ruleOutputs(kind, column, cell.text, ctx)[0];
+ if (out) {
+ plan.changes.push({ column, raw: escapeFenceCell(out.text), class: out.class });
+ return;
+ }
+ residual(plan, kind, column, residualReason(kind, column, cell.text));
+}
+
+function residualReason(kind: FenceKind, column: string, text: string): FenceReason {
+ if (column === 'kind') return 'takes_kind_unsupported';
+ if (column === 'claim_value') return 'claim_value_invalid';
+ if (column === 'visibility' || column === 'notability') return 'enum_unmapped';
+ if (column === 'who') return text.trim() ? 'holder_unresolved' : 'holder_missing';
+ if (column === 'weight' && !text.trim()) return 'weight_missing';
+ return 'confidence_out_of_range';
+}
+
+/**
+ * Every value a named rule may write in `column` for the before text, with
+ * its class. Empty when no rule applies.
+ */
+export function ruleOutputs(kind: FenceKind, column: string, text: string, ctx: FenceCtx): Array<{ text: string; class: FixClass }> {
+ switch (column) {
+ case 'kind': {
+ const mapped = kind === 'facts' ? factsKindMap(text) : takesKindMap(text, ctx.takesPackKinds);
+ return mapped ? [{ text: mapped, class: 'kind_map' }] : [];
+ }
+ case 'visibility':
+ case 'notability': {
+ const mapped = kind === 'facts' ? enumSynonym(column, text, ctx.pageVisibility) : null;
+ return mapped ? [{ text: mapped, class: 'enum_synonym' }] : [];
+ }
+ case 'confidence':
+ case 'weight': {
+ const formatted = confidenceFormat(text);
+ return formatted ? [{ text: formatted, class: 'confidence_format' }] : [];
+ }
+ case 'who':
+ return kind === 'takes' ? holderOutputs(text, ctx) : [];
+ default:
+ return [];
+ }
+}
+
+function holderOutputs(text: string, ctx: FenceCtx): Array<{ text: string; class: FixClass }> {
+ const out: Array<{ text: string; class: FixClass }> = [];
+ const alias = holderAlias(text);
+ if (alias) out.push({ text: alias, class: 'holder_alias' });
+ const verified = ctx.verifiedHolders?.get(text.trim());
+ if (verified && isValidHolder(verified) && verified !== alias) out.push({ text: verified, class: 'holder_verified' });
+ return out;
+}
diff --git a/src/core/fence-repair/structure.ts b/src/core/fence-repair/structure.ts
new file mode 100644
index 0000000000..e89cbf3e5d
--- /dev/null
+++ b/src/core/fence-repair/structure.ts
@@ -0,0 +1,137 @@
+/**
+ * Structural Tier 1 rules for one section (#6188): `marker_form` (takes
+ * two-dash markers) and `close_fence` (a missing end marker).
+ *
+ * `close_fence` inserts the end marker after the last table row only when
+ * every row of the before-region is one contiguous block and nothing but
+ * blank lines follows it to the end of the section: the privacy boundary
+ * hides everything after an unpaired begin marker, so closing the fence
+ * early would publish whatever trails it (gate (g)). Every structural edit
+ * is also checked against `exposedLines` before it is kept.
+ */
+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';
+import { exposedLines } from './page-checks.ts';
+import { extractRawRows, MARKERS, parseRowSpans, primaryFence, type RawFence, type RawSection } from './raw-rows.ts';
+import type { FenceFix, FenceIssue, FenceReason, FenceSection, FixClass } from './types.ts';
+
+export interface Edit {
+ start: number;
+ end: number;
+ text: string;
+}
+
+export interface PassResult {
+ text: string;
+ fixes: FenceFix[];
+ residual: FenceIssue[];
+}
+
+interface Step {
+ edits: Edit[];
+ fixes: FenceFix[];
+ residual: FenceIssue[];
+}
+
+/** Apply non-overlapping edits (any order) to `text`. */
+export function applyEdits(text: string, edits: readonly Edit[]): string {
+ let out = text;
+ for (const edit of [...edits].sort((a, b) => b.start - a.start)) out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
+ return out;
+}
+
+/** Run the structural rules until they settle (a converted marker may then need closing). */
+export function structuralPass(text: string, section: FenceSection): PassResult {
+ let current = text;
+ const fixes: FenceFix[] = [];
+ for (let round = 0; round < 3; round++) {
+ const step = structuralStep(current, section);
+ if (!step.edits.length) return { text: current, fixes, residual: step.residual };
+ current = applyEdits(current, step.edits);
+ fixes.push(...step.fixes);
+ }
+ throw new Error('fence structure rules did not settle');
+}
+
+/** A fence whose markers need a person: repeated, or an end marker with no begin before it. */
+export function fenceBlocked(raw: RawSection, fence: RawFence): boolean {
+ return fence.issues.some(i => i.reason === 'repeated_marker')
+ || raw.issues.some(i => i.fence === fence.kind && i.reason === 'missing_begin');
+}
+
+function structuralStep(text: string, section: FenceSection): Step {
+ const raw = extractRawRows(text, section);
+ const step: Step = { edits: [], fixes: [], residual: [] };
+ for (const kind of ['facts', 'takes'] as const) {
+ const fence = primaryFence(raw, kind);
+ if (!fence || fenceBlocked(raw, fence)) continue;
+ const edits = markerEdits(text, fence);
+ if (edits === null) {
+ step.residual.push(fenceIssue(fence, 'marker_near_miss', fence.begin.line));
+ continue;
+ }
+ if (edits.length) keep(step, text, fence, edits, 'marker_form', 'marker_near_miss');
+ else if (!fence.end) planClose(step, text, fence);
+ }
+ return step;
+}
+
+function fenceIssue(fence: RawFence, reason: FenceReason, line: number | null): FenceIssue {
+ return { fence: fence.kind, section: fence.section, row: null, column: null, line, reason };
+}
+
+/** Keep a fence's edits unless they would show text the privacy boundary hid. */
+function keep(step: Step, text: string, fence: RawFence, edits: Edit[], cls: FixClass, otherwise: FenceReason): void {
+ if (exposedLines(text, applyEdits(text, edits)).length) {
+ step.residual.push(fenceIssue(fence, otherwise, fence.begin.line));
+ return;
+ }
+ step.edits.push(...edits);
+ step.fixes.push({ fence: fence.kind, section: fence.section, row: null, column: null, line: fence.begin.line, class: cls });
+}
+
+/** `marker_form` edits for two-dash takes markers; null when a near-miss begin has no table after it. */
+function markerEdits(text: string, fence: RawFence): Edit[] | null {
+ const edits: Edit[] = [];
+ if (fence.begin.nearMiss) {
+ if (!tableFollows(text, fence.begin.end)) return null;
+ edits.push({ start: fence.begin.start, end: fence.begin.end, text: TAKES_FENCE_BEGIN });
+ }
+ if (fence.end?.nearMiss) edits.push({ start: fence.end.start, end: fence.end.end, text: TAKES_FENCE_END });
+ return edits;
+}
+
+/** The first non-blank line after `from` is a pipe-table row. */
+function tableFollows(text: string, from: number): boolean {
+ let at = text.indexOf('\n', from);
+ while (at !== -1) {
+ const next = text.indexOf('\n', at + 1);
+ const end = next === -1 ? text.length : next;
+ if (text.slice(at + 1, end).trim()) return parseRowSpans(text, at + 1, end, 0) !== null;
+ at = next;
+ }
+ return false;
+}
+
+function planClose(step: Step, text: string, fence: RawFence): void {
+ const lines = [fence.header, ...fence.separators, ...fence.rows].filter(r => r !== null).sort((a, b) => a.line - b.line);
+ const last = lines[lines.length - 1];
+ if (lines.some((row, i) => i > 0 && row.line !== lines[i - 1]!.line + 1)) {
+ step.residual.push(fenceIssue(fence, 'split_rows', fence.begin.line));
+ return;
+ }
+ const after = last ? last.end : fence.begin.end;
+ if (text.slice(after, fence.regionEnd).trim()) {
+ step.residual.push(fenceIssue(fence, 'unclosed_trailing_content', fence.begin.line));
+ return;
+ }
+ keep(step, text, fence, [closeEdit(text, after, MARKERS[fence.kind].end)], 'close_fence', 'unclosed_trailing_content');
+}
+
+/** Insert `marker` on its own line after the line that ends at or after `at`, keeping that line's ending. */
+function closeEdit(text: string, at: number, marker: string): Edit {
+ const nl = text.indexOf('\n', at);
+ if (nl === -1) return { start: text.length, end: text.length, text: `\n${marker}` };
+ const crlf = nl > 0 && text[nl - 1] === '\r';
+ const pos = crlf ? nl - 1 : nl;
+ return { start: pos, end: pos, text: `${crlf ? '\r\n' : '\n'}${marker}` };
+}
diff --git a/src/core/fence-repair/validate-cells.ts b/src/core/fence-repair/validate-cells.ts
new file mode 100644
index 0000000000..dffff968d3
--- /dev/null
+++ b/src/core/fence-repair/validate-cells.ts
@@ -0,0 +1,139 @@
+/**
+ * Gate (f), per-cell preservation (#6188, TE2), for one before row and the
+ * after row at the same position.
+ *
+ * Aligned before rows (under a header, no shape problem): a cell valid in
+ * its column keeps its column and text (whitespace collapsed); a changed cell
+ * must be named by an issue on that row and column (or a fence-level issue)
+ * and equal what a named rule writes for the before text; a cell invalid in
+ * its column may instead move to another column with its text unchanged.
+ * A column absent from the before header may only take its write default
+ * (`column_default`) or stay empty. Misaligned before rows (rows before the
+ * header, short rows, extra cells) may have every cell moved, with text
+ * unchanged or rewritten by a named rule. In both cases no before text may
+ * vanish, and a facts kind rewritten by `kind_map` must leave its original
+ * word in `context`.
+ */
+import type { RawFence, RawRow } from './raw-rows.ts';
+import { ruleOutputs } from './rules.ts';
+import { appendOriginalKind, cellValid, collapse, COLUMN_DEFAULTS, factsKindMap } from './schema.ts';
+import type { FenceKind, FenceSection } from './types.ts';
+import type { ValidateCtx } from './validate.ts';
+
+interface PairLike {
+ section: FenceSection;
+ kind: FenceKind;
+ before: RawFence | null;
+}
+
+interface Source {
+ column: string | null;
+ text: string;
+ /** Free to move: invalid in its column, unmapped, or from a misaligned row. */
+ movable: boolean;
+ used: boolean;
+}
+
+interface RowCheck {
+ pair: PairLike;
+ kind: FenceKind;
+ ctx: ValidateCtx;
+ aligned: boolean;
+ sources: Source[];
+ byColumn: Map<string, Source>;
+ named: (column: string) => boolean;
+ /** Before word `kind_map` rewrote (facts), for the `context` check. */
+ kindWord: string | null;
+ failed: string[];
+}
+
+const SKIP = new Set(['claim', '#']);
+
+/** Columns of `after` that gate (f) rejects for this before row (empty when the row passes). */
+export function cellsChanged(pair: PairLike, before: RawRow, after: RawRow, ctx: ValidateCtx): string[] {
+ const check = rowCheck(pair, before, ctx);
+ const columns = [...after.byColumn.keys()].filter(c => !SKIP.has(c));
+ const ordered = [...columns.filter(c => c !== 'context'), ...columns.filter(c => c === 'context')];
+ for (const column of ordered) {
+ const text = collapse(after.byColumn.get(column)!.text);
+ const ok = column === 'context' && check.kind === 'facts' ? contextOk(check, text) : cellOk(check, column, text);
+ if (!ok) check.failed.push(column);
+ }
+ for (const s of check.sources) if (!s.used && s.text) check.failed.push(s.column ?? 'extra');
+ return check.failed;
+}
+
+function rowCheck(pair: PairLike, row: RawRow, ctx: ValidateCtx): RowCheck {
+ const aligned = !row.beforeHeader && row.shape === 'ok';
+ const byColumn = new Map<string, Source>();
+ const sources: Source[] = [];
+ for (const [column, cell] of row.byColumn) {
+ if (SKIP.has(column)) continue;
+ const source = { column, text: collapse(cell.text), movable: !aligned || !cellValid(pair.kind, column, cell.text), used: false };
+ sources.push(source);
+ byColumn.set(column, source);
+ }
+ for (const cell of row.extra) sources.push({ column: null, text: collapse(cell.text), movable: true, used: false });
+ return { pair, kind: pair.kind, ctx, aligned, sources, byColumn, named: namer(pair, row, ctx), kindWord: null, failed: [] };
+}
+
+/** An issue names this row and column: same line, or a fence-level issue (begin or header line). */
+function namer(pair: PairLike, row: RawRow, ctx: ValidateCtx): (column: string) => boolean {
+ const fenceLines = new Set([pair.before?.begin.line, pair.before?.header?.line].filter(n => n !== undefined));
+ const issues = ctx.issues.filter(i => i.fence === pair.kind && i.section === pair.section && i.line !== null
+ && (i.line === row.line || (i.row === null && fenceLines.has(i.line))));
+ return column => issues.some(i => i.column === null || i.column === column);
+}
+
+function cellOk(check: RowCheck, column: string, text: string): boolean {
+ const own = check.byColumn.get(column);
+ if (check.aligned && own && !own.movable && own.text !== text) return ruleChange(check, column, own, text);
+ if (own && !own.used && own.text === text) return use(own);
+ if (own && !own.used && ruleChange(check, column, own, text)) return true;
+ const moved = check.sources.find(s => !s.used && s.movable && s !== own
+ && (s.text === text || (!check.aligned && check.named(column) && ruleFits(check, column, s, text))));
+ if (moved) return noteKind(check, column, moved, text) && use(moved);
+ if (!text) return true;
+ return absentFromHeader(check, column) && COLUMN_DEFAULTS[check.kind][column] === text;
+}
+
+/** A named rule rewrote `source` into `text` in its own column. */
+function ruleChange(check: RowCheck, column: string, source: Source, text: string): boolean {
+ if (source.used || !check.named(column) || !ruleFits(check, column, source, text)) return false;
+ return noteKind(check, column, source, text) && use(source);
+}
+
+function ruleFits(check: RowCheck, column: string, source: Source, text: string): boolean {
+ return ruleOutputs(check.kind, column, source.text, check.ctx).some(o => collapse(o.text) === text);
+}
+
+function noteKind(check: RowCheck, column: string, source: Source, text: string): boolean {
+ if (check.kind === 'facts' && column === 'kind' && factsKindMap(source.text) === text && !cellValid('facts', 'kind', source.text)) {
+ check.kindWord = source.text;
+ }
+ return true;
+}
+
+function use(source: Source): true {
+ source.used = true;
+ return true;
+}
+
+/** The before layout has no such column (so its write default may appear). */
+function absentFromHeader(check: RowCheck, column: string): boolean {
+ const fence = check.pair.before;
+ return !fence?.header || !fence.columns.includes(column);
+}
+
+/** Facts `context`: unchanged, or the before context with `kind_map`'s original word appended (required when it ran). */
+function contextOk(check: RowCheck, text: string): boolean {
+ const own = check.byColumn.get('context');
+ const candidates = own && !own.used ? [own] : [];
+ if (!check.aligned) candidates.push(...check.sources.filter(s => !s.used && s !== own));
+ const empty: Source = { column: 'context', text: '', movable: false, used: false };
+ for (const source of [...candidates, empty]) {
+ const expected = collapse(check.kindWord === null ? source.text : appendOriginalKind(source.text, check.kindWord));
+ if (expected === text) return source === empty || use(source);
+ }
+ return false;
+}
diff --git a/src/core/fence-repair/validate.ts b/src/core/fence-repair/validate.ts
new file mode 100644
index 0000000000..f393fb0729
--- /dev/null
+++ b/src/core/fence-repair/validate.ts
@@ -0,0 +1,183 @@
+/**
+ * The fence repair validator (#6188): the one gate every tier's output
+ * passes before anything is written.
+ *
+ * (a) still_invalid the after page compiles (strict parse, markers, unique rows)
+ * (e) row_count_changed same data-row count; every before row sits in the after fence
+ * (b) claim_changed claim cells identical, in order (strikethrough kept, whitespace collapsed)
+ * (c) row_number_changed every valid, page-unique row number keeps its claim
+ * (d) visibility_loosened a private row never becomes world; invalid becomes world only via `public` on a world page
+ * (f) cell_changed per row, a valid non-claim cell keeps its column and text; a misaligned cell may move
+ * with its text unchanged; text changes only where an issue names the row and column
+ * and a named rule produced it (TE2)
+ * (g) protection_loosened nothing the privacy boundary hid is shown after
+ *
+ * Gates (b), (c), (e) and (f) read the raw-row extraction of the
+ * before-region, never strict-parser output. (e) runs before (b) so a dropped
+ * or stranded row reports the row-count gate. Failures carry the reason, the
+ * gate letter and row numbers only.
+ */
+import { normalizeFences } from './normalize.ts';
+import { exposedLines, sectionsOf, strictFailures } from './page-checks.ts';
+import { extractRawRows, primaryFence, rowNumOf, type RawFence, type RawRow } from './raw-rows.ts';
+import { cellsChanged } from './validate-cells.ts';
+import { GATE_REASONS } from './reasons.ts';
+import { cellValid, collapse, enumSynonym } from './schema.ts';
+import type { FenceCtx, FenceKind, FenceLocation, FencePage, FenceReason, FenceSection, FenceTier, GateLetter } from './types.ts';
+
+export interface ValidateCtx extends FenceCtx {
+ /** The tier whose output is checked. */
+ tier: Exclude<FenceTier, 'manual'>;
+ /** Issues and fixes found on the before page; a cell may change only where one names it. */
+ issues: readonly FenceLocation[];
+}
+
+export type ValidateResult =
+ | { ok: true }
+ | {
+ ok: false;
+ reason: FenceReason;
+ gate: GateLetter;
+ tier: Exclude<FenceTier, 'manual'>;
+ fence: FenceKind | null;
+ section: FenceSection | null;
+ rows: number[];
+ };
+
+/** One fence kind in one section, before and after. */
+export interface FencePair {
+ section: FenceSection;
+ kind: FenceKind;
+ before: RawFence | null;
+ after: RawFence | null;
+}
+
+type Failure = { gate: GateLetter; fence: FenceKind | null; section: FenceSection | null; rows: number[] };
+
+const at = (pair: FencePair, gate: GateLetter, rows: number[]): Failure => ({ gate, fence: pair.kind, section: pair.section, rows });
+
+export function validateFenceRepair(before: FencePage, after: FencePage, ctx: ValidateCtx): ValidateResult {
+ const failure = firstFailure(before, after, ctx);
+ if (!failure) return { ok: true };
+ return {
+ ok: false, reason: GATE_REASONS[failure.gate], gate: failure.gate, tier: ctx.tier,
+ fence: failure.fence, section: failure.section, rows: [...new Set(failure.rows)],
+ };
+}
+
+/** The page is a Tier 1 fixed point: normalizing it applies no fix. */
+export function isFenceFixedPoint(page: FencePage, ctx: FenceCtx): boolean {
+ return normalizeFences(page, ctx).fixes.length === 0;
+}
+
+function firstFailure(before: FencePage, after: FencePage, ctx: ValidateCtx): Failure | null {
+ const strict = strictFailures(after);
+ if (strict.length) {
+ const f = strict[0]!;
+ return { gate: 'a', fence: f.fence, section: f.section, rows: f.rows };
+ }
+ const pairs = fencePairs(before, after);
+ for (const check of [rowCount, claims, rowNumbers, visibility, cells]) {
+ const failed = check(pairs, ctx);
+ if (failed) return failed;
+ }
+ return protection(before, after);
+}
+
+function fencePairs(before: FencePage, after: FencePage): FencePair[] {
+ const afterSections = new Map(sectionsOf(after));
+ return sectionsOf(before).flatMap(([section, text]) => {
+ const b = extractRawRows(text, section);
+ const a = extractRawRows(afterSections.get(section) ?? '', section);
+ return (['facts', 'takes'] as const).map(kind => ({ section, kind, before: primaryFence(b, kind), after: primaryFence(a, kind) }));
+ });
+}
+
+const rowsOf = (fence: RawFence | null): RawRow[] => fence?.rows ?? [];
+const numOf = (fence: RawFence | null, row: RawRow | undefined): number | null => (fence && row ? rowNumOf(fence, row) : null);
+const claimOf = (row: RawRow): string => collapse(row.byColumn.get('claim')?.text ?? '');
+
+function numbers(fence: RawFence | null, rows: readonly RawRow[]): number[] {
+ return rows.map(r => numOf(fence, r)).filter((n): n is number => n !== null);
+}
+
+/** (e) */
+function rowCount(pairs: FencePair[]): Failure | null {
+ for (const pair of pairs) {
+ const b = rowsOf(pair.before);
+ const a = rowsOf(pair.after);
+ if (b.length === a.length) continue;
+ const longer = b.length > a.length ? { fence: pair.before, rows: b } : { fence: pair.after, rows: a };
+ return at(pair, 'e', numbers(longer.fence, longer.rows.slice(Math.min(a.length, b.length))));
+ }
+ return null;
+}
+
+/** (b) */
+function claims(pairs: FencePair[]): Failure | null {
+ for (const pair of pairs) {
+ const a = rowsOf(pair.after);
+ const changed = rowsOf(pair.before).filter((row, k) => claimOf(row) !== claimOf(a[k]!));
+ if (changed.length) return at(pair, 'b', numbers(pair.after, changed.map(r => a[r.occurrence]!)));
+ }
+ return null;
+}
+
+/** (c) */
+function rowNumbers(pairs: FencePair[]): Failure | null {
+ for (const kind of ['facts', 'takes'] as const) {
+ const of = pairs.filter(p => p.kind === kind);
+ const before = of.flatMap(p => rowsOf(p.before).map(row => ({ num: numOf(p.before, row), claim: claimOf(row), pair: p })));
+ const after = new Set(of.flatMap(p => rowsOf(p.after).map(row => `${numOf(p.after, row)}\u0000${claimOf(row)}`)));
+ for (const row of before) {
+ if (row.num === null || before.filter(r => r.num === row.num).length > 1) continue;
+ if (!after.has(`${row.num}\u0000${row.claim}`)) return at(row.pair, 'c', [row.num]);
+ }
+ }
+ return null;
+}
+
+/** (d) */
+function visibility(pairs: FencePair[], ctx: ValidateCtx): Failure | null {
+ for (const pair of pairs.filter(p => p.kind === 'facts')) {
+ const a = rowsOf(pair.after);
+ for (const row of rowsOf(pair.before)) {
+ const after = a[row.occurrence]!;
+ if (after.byColumn.get('visibility')?.text.trim().toLowerCase() !== 'world') continue;
+ if (!mayBecomeWorld(row, ctx)) return at(pair, 'd', numbers(pair.after, [after]));
+ }
+ }
+ return null;
+}
+
+function mayBecomeWorld(row: RawRow, ctx: ValidateCtx): boolean {
+ const toWorld = (text: string) => enumSynonym('visibility', text, ctx.pageVisibility) === 'world';
+ const aligned = !row.beforeHeader && row.shape === 'ok';
+ if (!aligned) return [...row.byColumn.values(), ...row.extra].some(c => toWorld(c.text));
+ const vis = row.byColumn.get('visibility');
+ if (!vis) return false;
+ return cellValid('facts', 'visibility', vis.text) ? vis.text.trim().toLowerCase() === 'world' : toWorld(vis.text);
+}
+
+/** (f) */
+function cells(pairs: FencePair[], ctx: ValidateCtx): Failure | null {
+ for (const pair of pairs) {
+ const a = rowsOf(pair.after);
+ for (const row of rowsOf(pair.before)) {
+ const after = a[row.occurrence]!;
+ if (cellsChanged(pair, row, after, ctx).length) return at(pair, 'f', numbers(pair.after, [after]));
+ }
+ }
+ return null;
+}
+
+/** (g) */
+function protection(before: FencePage, after: FencePage): Failure | null {
+ const afterSections = new Map(sectionsOf(after));
+ for (const [section, text] of sectionsOf(before)) {
+ if (exposedLines(text, afterSections.get(section) ?? '').length) {
+ return { gate: 'g', fence: null, section, rows: [] };
+ }
+ }
+ return null;
+}