Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(fence-repair): failure classes, gates (a)-(g), reasons, raw-row differential and fixture fuzz (#6188)
garrytanbc0d9fe49ee5
diff --git a/src/core/fence-repair/content.ts b/src/core/fence-repair/content.tsindex 8ab1b2d3eb..d55725c953 100644--- a/src/core/fence-repair/content.ts+++ b/src/core/fence-repair/content.ts@@ -179,6 +179,12 @@ function renumber(pass: Pass, kind: FenceKind): void {}}+/** The number the row was written with (`0` and negatives included), or null when the cell is not numeric or absent. */+function writtenNum(row: RawRow): number | null {+ const n = parseInt(row.byColumn.get('#')?.text ?? '', 10);+ return Number.isFinite(n) ? n : null;+}+function finalNum(w: RowWork): number | null {return w.newNum ?? w.num;}@@ -190,7 +196,7 @@ function emitFence(pass: Pass, work: FenceWork): void {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 });+ pass.fixes.push({ fence: fence.kind, section: fence.section, row, column: '#', line: w.row.line, class: 'renumber', from: writtenNum(w.row) });}for (const change of w.plan.changes) {if (change.column === 'context' && change.class === 'kind_map') continue;diff --git a/src/core/fence-repair/validate-cells.ts b/src/core/fence-repair/validate-cells.tsindex dffff968d3..541cfca17b 100644--- a/src/core/fence-repair/validate-cells.ts+++ b/src/core/fence-repair/validate-cells.ts@@ -59,6 +59,12 @@ export function cellsChanged(pair: PairLike, before: RawRow, after: RawRow, ctx:const ok = column === 'context' && check.kind === 'facts' ? contextOk(check, text) : cellOk(check, column, text);if (!ok) check.failed.push(column);}+ for (const cell of after.extra) {+ const text = collapse(cell.text);+ const kept = check.sources.find(s => !s.used && s.text === text);+ if (kept) use(kept);+ else if (text) check.failed.push('extra');+ }for (const s of check.sources) if (!s.used && s.text) check.failed.push(s.column ?? 'extra');return check.failed;}diff --git a/test/fence-repair-fixtures.test.ts b/test/fence-repair-fixtures.test.tsnew file mode 100644index 0000000000..77cb231733--- /dev/null+++ b/test/fence-repair-fixtures.test.ts@@ -0,0 +1,201 @@+/**+ * Fence repair over every facts/takes fence fixture in the test suite+ * (#6188, E21 + E30): the raw extractor accepts exactly the rows the strict+ * parsers return; Invariant 0 (a page that compiles comes back as the same+ * object); and a seeded mutation fuzz over those fixtures for idempotence,+ * claim preservation, the validator gates and location-only output.+ *+ * Fixtures are harvested by statically evaluating string expressions (string+ * and template literals, `+`, `[...].join(sep)`, the marker constants) in+ * test/**\/*.ts, so new fence fixtures join this sweep automatically.+ */+import { describe, expect, test } from 'bun:test';+import ts from 'typescript';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../src/core/takes-fence.ts';+import { stripStrikethrough } from '../src/core/fence-shared.ts';+import { extractRawRows, primaryFence } from '../src/core/fence-repair/raw-rows.ts';+import { normalizeFences } from '../src/core/fence-repair/normalize.ts';+import { sectionsOf, strictPageClean } from '../src/core/fence-repair/page-checks.ts';+import { validateFenceRepair } from '../src/core/fence-repair/validate.ts';+import type { FenceCtx, FencePage } from '../src/core/fence-repair/types.ts';++const MARKERS: Record<string, string> = { FACTS_FENCE_BEGIN, FACTS_FENCE_END, TAKES_FENCE_BEGIN, TAKES_FENCE_END };+const FENCE_TEXT = /gbrain:(facts|takes):/;++function evaluate(node: ts.Node): string | null {+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;+ if (ts.isIdentifier(node)) return MARKERS[node.text] ?? null;+ if (ts.isParenthesizedExpression(node)) return evaluate(node.expression);+ if (ts.isTemplateExpression(node)) {+ return node.templateSpans.reduce((out, span) => out + (evaluate(span.expression) ?? 'x') + span.literal.text, node.head.text);+ }+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {+ const left = evaluate(node.left);+ const right = evaluate(node.right);+ return left !== null && right !== null ? left + right : null;+ }+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'join'+ && ts.isArrayLiteralExpression(node.expression.expression)) {+ const sep = node.arguments[0] ? evaluate(node.arguments[0]) : ',';+ const parts = node.expression.expression.elements.map(evaluate);+ return sep !== null && parts.every(p => p !== null) ? parts.join(sep) : null;+ }+ return null;+}++function harvestFixtures(dir: string): string[] {+ const found = new Set<string>();+ const visit = (node: ts.Node) => {+ const value = evaluate(node);+ if (value !== null && FENCE_TEXT.test(value)) found.add(value);+ else ts.forEachChild(node, visit);+ };+ const walk = (path: string) => {+ for (const name of readdirSync(path).sort()) {+ const child = join(path, name);+ if (statSync(child).isDirectory()) walk(child);+ else if (child.endsWith('.ts')) {+ const text = readFileSync(child, 'utf8');+ if (FENCE_TEXT.test(text) || text.includes('_FENCE_BEGIN')) visit(ts.createSourceFile(child, text, ts.ScriptTarget.Latest, true));+ }+ }+ };+ walk(dir);+ return [...found];+}++const FIXTURES = harvestFixtures(import.meta.dir);+const PRIVATE: FenceCtx = { pageVisibility: 'private' };++/** Claims per section and kind, in row order, from the raw extraction. */+function rawClaims(page: FencePage): string[] {+ return sectionsOf(page).flatMap(([section, text]) => {+ const raw = extractRawRows(text, section);+ return (['facts', 'takes'] as const).map(kind => `${section}:${kind}:` + (primaryFence(raw, kind)?.rows ?? [])+ .map(r => r.byColumn.get('claim')?.text.replace(/\s+/g, ' ').trim() ?? '').join('\u0001'));+ });+}++describe('fence fixtures in the test suite', () => {+ test('the sweep finds a meaningful corpus', () => {+ expect(FIXTURES.length).toBeGreaterThanOrEqual(120);+ expect(FIXTURES.filter(f => strictPageClean({ compiled_truth: f, timeline: '' })).length).toBeGreaterThanOrEqual(80);+ });++ test('raw-row differential (E21): accepted rows equal the strict parsers\' rows', () => {+ let compared = 0;+ for (const fixture of FIXTURES) {+ const raw = extractRawRows(fixture);+ const parsed = {+ facts: parseFactsFence(fixture).facts.map(f => [f.rowNum, f.claim]),+ takes: parseTakesFence(fixture).takes.map(t => [t.rowNum, t.claim]),+ };+ for (const kind of ['facts', 'takes'] as const) {+ const accepted = (primaryFence(raw, kind)?.rows ?? []).filter(r => r.accepted)+ .map(r => [parseInt(r.cells[0]!.text, 10), stripStrikethrough(r.cells[1]!.text).text]);+ expect(accepted).toEqual(parsed[kind]);+ compared += accepted.length;+ }+ }+ expect(compared).toBeGreaterThanOrEqual(80);+ });++ test('Invariant 0: every fixture page that compiles is returned unchanged; the rest normalize idempotently', () => {+ for (const fixture of FIXTURES) {+ for (const before of [{ compiled_truth: fixture, timeline: '' }, { compiled_truth: '', timeline: fixture }]) {+ const r = normalizeFences(before, PRIVATE);+ if (strictPageClean(before)) {+ expect(r.page).toBe(before);+ continue;+ }+ expect(normalizeFences(r.page, PRIVATE).fixes).toEqual([]);+ expect(rawClaims(r.page)).toEqual(rawClaims(before));+ if (r.residual.length) continue;+ expect(strictPageClean(r.page)).toBe(true);+ expect(validateFenceRepair(before, r.page, { ...PRIVATE, tier: 'deterministic', issues: [...r.fixes, ...r.residual] })).toEqual({ ok: true });+ }+ }+ });+});++/** Deterministic PRNG (mulberry32) so a failing case reproduces. */+function prng(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++const WORDS = ['partnership', 'Critical', 'very_high', 'public', 'internal', 'shared', '85%', '0', '-2', 'System', 'Alice Example',+ 'assessment', 'strategic position', 'wibble', '', 'x', '1.5', 'opinion', 'team', 'minor'];++type Mutation = (lines: string[], rand: () => number) => string[];+const pick = <T>(items: readonly T[], rand: () => number): T => items[Math.floor(rand() * items.length)]!;+const rowLines = (lines: string[]) => lines.map((l, i) => [l, i] as const).filter(([l]) => /^\s*\|/.test(l) && !/^\s*\|[-:\s|]+\|?\s*$/.test(l)).map(([, i]) => i);++const MUTATIONS: Mutation[] = [+ (lines, rand) => { // rewrite one cell+ const rows = rowLines(lines);+ if (!rows.length) return lines;+ const i = pick(rows, rand);+ const cells = lines[i]!.split('|');+ if (cells.length > 3) cells[1 + Math.floor(rand() * (cells.length - 2))] = ` ${pick(WORDS, rand)} `;+ return lines.map((l, k) => (k === i ? cells.join('|') : l));+ },+ (lines, rand) => { // duplicate a row+ const rows = rowLines(lines);+ if (!rows.length) return lines;+ const i = pick(rows, rand);+ return [...lines.slice(0, i + 1), lines[i]!.replace(/(\|\s*)[^|]*/, '$1 copy of a row '), ...lines.slice(i + 1)];+ },+ (lines, rand) => lines.filter(l => !(l.includes('gbrain:facts:end') || l.includes('gbrain:takes:end')) || rand() < 0.3), // drop end markers+ lines => lines.map(l => l.replace('<!--- gbrain:takes:', '<!-- gbrain:takes:')), // two-dash takes markers+ (lines, rand) => { // delete a middle cell+ const rows = rowLines(lines);+ if (!rows.length) return lines;+ const i = pick(rows, rand);+ const cells = lines[i]!.split('|');+ if (cells.length > 5) cells.splice(2 + Math.floor(rand() * (cells.length - 4)), 1);+ return lines.map((l, k) => (k === i ? cells.join('|') : l));+ },+ (lines, rand) => [...lines, '', pick(['Trailing prose line.', '| stray | row |', ''], rand)], // trailing content+];++describe('mutation fuzz over the fixtures', () => {+ test('never throws; idempotent; claims kept; clean outputs pass every gate; output is location-only', () => {+ const rand = prng(6188);+ let repaired = 0;+ let held = 0;+ const clean = FIXTURES.filter(f => strictPageClean({ compiled_truth: f, timeline: '' }));+ for (const fixture of clean) {+ for (let round = 0; round < 10; round++) {+ let lines = fixture.split('\n');+ for (let k = 0; k < 1 + Math.floor(rand() * 3); k++) lines = pick(MUTATIONS, rand)(lines, rand);+ const text = rand() < 0.15 ? lines.join('\r\n') : lines.join('\n');+ const before: FencePage = rand() < 0.3 ? { compiled_truth: 'Intro.\n', timeline: text } : { compiled_truth: text, timeline: '' };+ const ctx: FenceCtx = { pageVisibility: rand() < 0.5 ? 'private' : 'world' };+ const r = normalizeFences(before, ctx);+ if (strictPageClean(before)) expect(validateFenceRepair(before, before, { ...ctx, tier: 'llm', issues: [] })).toEqual({ ok: true });+ expect(normalizeFences(r.page, ctx).fixes).toEqual([]);+ expect(rawClaims(r.page)).toEqual(rawClaims(before));+ const surface = JSON.stringify([r.fixes, r.residual]);+ for (const claim of rawClaims(before).join('\u0001').split('\u0001')) {+ if (claim.length >= 12 && claim.includes(' ')) expect(surface).not.toContain(claim);+ }+ if (r.residual.length) { held++; continue; }+ expect(strictPageClean(r.page)).toBe(true);+ expect(validateFenceRepair(before, r.page, { ...ctx, tier: 'deterministic', issues: [...r.fixes, ...r.residual] })).toEqual({ ok: true });+ if (r.fixes.length) repaired++;+ }+ }+ expect(repaired).toBeGreaterThanOrEqual(50);+ expect(held).toBeGreaterThanOrEqual(50);+ });+});diff --git a/test/fence-repair-normalize.test.ts b/test/fence-repair-normalize.test.tsnew file mode 100644index 0000000000..64c33f3c8e--- /dev/null+++ b/test/fence-repair-normalize.test.ts@@ -0,0 +1,434 @@+/**+ * Tier 1 fence normalizer (#6188): one fixture per failure class in the+ * issue's table, every rule and residual class, prior-aware renumbering,+ * Invariant 0, idempotence and the location-only privacy rule. All content+ * is synthetic.+ */+import { describe, expect, test } from 'bun:test';+import { FACTS_FENCE_BEGIN as FB, FACTS_FENCE_END as FE, parseFactsFence } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN as TB, TAKES_FENCE_END as TE, parseTakesFence } from '../src/core/takes-fence.ts';+import { sanitizeRemoteBody } from '../src/core/remote-body.ts';+import {+ FENCE_RULES_VERSION, nextFreeRowNum, normalizeFences, safeNormalizeFences,+} from '../src/core/fence-repair/normalize.ts';+import { strictPageClean } from '../src/core/fence-repair/page-checks.ts';+import { validateFenceRepair } from '../src/core/fence-repair/validate.ts';+import { FENCE_REASONS, fenceMessage, issueLocation } from '../src/core/fence-repair/reasons.ts';+import type { FenceCtx, FencePage, FenceReason, StoredRowMap } from '../src/core/fence-repair/types.ts';++const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';+const FS = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';+const TH = '| # | claim | kind | who | weight | since | source |';+const TS = '|---|-------|------|-----|--------|-------|--------|';+const PRIVATE: FenceCtx = { pageVisibility: 'private' };+const WORLD: FenceCtx = { pageVisibility: 'world' };++const factsRow = (n: string | number, claim: string, o: Partial<Record<'kind' | 'conf' | 'vis' | 'not' | 'from' | 'src' | 'ctx', string>> = {}) =>+ `| ${n} | ${claim} | ${o.kind ?? 'fact'} | ${o.conf ?? '1.0'} | ${o.vis ?? 'private'} | ${o.not ?? 'medium'} | ${o.from ?? '2026-01-01'} | | ${o.src ?? 'call'} | ${o.ctx ?? ''} |`;+const takesRow = (n: string | number, claim: string, o: Partial<Record<'kind' | 'who' | 'w' | 'since' | 'src', string>> = {}) =>+ `| ${n} | ${claim} | ${o.kind ?? 'take'} | ${o.who ?? 'brain'} | ${o.w ?? '0.5'} | ${o.since ?? '2026-01'} | ${o.src ?? 'notes'} |`;+const facts = (...rows: string[]) => ['## Facts', '', FB, '', FH, FS, ...rows, FE, ''].join('\n');+const takes = (...rows: string[]) => ['## Takes', '', TB, TH, TS, ...rows, TE, ''].join('\n');+const page = (compiled_truth: string, timeline = ''): FencePage => ({ compiled_truth, timeline });++function run(body: string, ctx: FenceCtx = PRIVATE, timeline = '') {+ const before = page(body, timeline);+ return { before, ...normalizeFences(before, ctx) };+}++/** A clean repair: compiles, passes every gate, and is a fixed point. */+function expectRepaired(r: ReturnType<typeof run>, ctx: FenceCtx = PRIVATE) {+ expect(r.residual).toEqual([]);+ expect(strictPageClean(r.page)).toBe(true);+ expect(validateFenceRepair(r.before, r.page, { ...ctx, tier: 'deterministic', issues: [...r.fixes, ...r.residual] })).toEqual({ ok: true });+ expect(normalizeFences(r.page, ctx).fixes).toEqual([]);+}++const classes = (r: { fixes: Array<{ class: string }> }) => [...new Set(r.fixes.map(f => f.class))].sort();+const reasons = (r: { residual: Array<{ reason: FenceReason }> }) => [...new Set(r.residual.map(i => i.reason))].sort();++describe('issue #6188 failure classes', () => {+ test('FACTS_FENCE_UNBALANCED: a missing end marker with only blank lines after the table is closed', () => {+ const body = ['## Facts', '', FB, '', FH, FS, factsRow(1, 'Alpha claim'), factsRow(2, 'Beta claim'), '', ''].join('\n');+ const r = run(body);+ expect(classes(r)).toEqual(['close_fence']);+ expect(r.page.compiled_truth).toBe(['## Facts', '', FB, '', FH, FS, factsRow(1, 'Alpha claim'), factsRow(2, 'Beta claim'), FE, '', ''].join('\n'));+ expectRepaired(r);+ });++ test('TAKES_FENCE_UNBALANCED: a takes fence at the end of the section is closed', () => {+ const r = run(['## Takes', '', TB, TH, TS, takesRow(1, 'Gamma take')].join('\n'));+ expect(r.page.compiled_truth.endsWith(`${takesRow(1, 'Gamma take')}\n${TE}`)).toBe(true);+ expectRepaired(r);+ });++ test('TABLE_MALFORMED short rows from a non-canonical takes table are realigned under the canonical header', () => {+ const body = ['## Takes', '', TB, '| Holder | Claim | Kind | Confidence | Source |', '|---|---|---|---|---|',+ '| brain | Delta take | take | 0.7 | standup |', '| world | Epsilon take | fact | 1.0 | report |', TE].join('\n');+ const r = run(body);+ expect(classes(r)).toEqual(['header_alias', 'renumber']);+ const parsed = parseTakesFence(r.page.compiled_truth);+ expect(parsed.warnings).toEqual([]);+ expect(parsed.takes.map(t => [t.rowNum, t.claim, t.holder, t.weight, t.source])).toEqual([+ [1, 'Delta take', 'brain', 0.7, 'standup'], [2, 'Epsilon take', 'world', 1, 'report']]);+ expectRepaired(r);+ });++ test('TABLE_MALFORMED short row with a middle gap stays residual and the row is untouched', () => {+ const gap = '| 2 | Zeta claim | fact | 0.9 | private | medium | 2026-02-02 | call |';+ const r = run(facts(factsRow(1, 'Eta claim'), gap));+ expect(reasons(r)).toEqual(['short_row']);+ expect(r.page.compiled_truth).toContain(gap);+ expect(FENCE_REASONS.short_row.tier).toBe('llm');+ });++ test.each([+ ['partnership', 'fact'], ['signal', 'fact'], ['funding', 'fact'], ['investment', 'fact'], ['role', 'fact'],+ ['claim', 'fact'], ['observation', 'fact'], ['[kind]', 'fact'], ['insight', 'belief'], ['frame', 'belief'],+ ['proposal', 'idea'], ['promise', 'commitment'], ['milestone', 'event'],+ ])('FACTS unknown kind %s maps to %s and keeps the word in context', (word, kind) => {+ const r = run(facts(factsRow(1, 'Theta claim', { kind: word, ctx: 'from a call' })));+ expect(classes(r)).toEqual(['kind_map']);+ const [fact] = parseFactsFence(r.page.compiled_truth).facts;+ expect(fact!.kind).toBe(kind as never);+ expect(fact!.context).toBe(`from a call; original kind: ${word}`);+ expectRepaired(r);+ });++ test.each([['assessment', 'take'], ['strategic position', 'take'], ['recommendation', 'take'], ['forecast', 'bet'], ['intuition', 'hunch']])(+ 'TAKES unknown kind %s maps to %s through the explicit synonym table', (word, kind) => {+ const r = run(takes(takesRow(1, 'Iota take', { kind: word })));+ expect(parseTakesFence(r.page.compiled_truth).takes[0]!.kind).toBe(kind);+ expectRepaired(r);+ });++ test('unknown notability critical / very_high maps to high', () => {+ const r = run(facts(factsRow(1, 'Kappa claim', { not: 'critical' }), factsRow(2, 'Lambda claim', { not: 'very_high' })));+ expect(parseFactsFence(r.page.compiled_truth).facts.map(f => f.notability)).toEqual(['high', 'high']);+ expect(classes(r)).toEqual(['enum_synonym']);+ expectRepaired(r);+ });++ test('unknown visibility: public and internal tighten to private on a private page; public is world only on a world page', () => {+ const body = facts(factsRow(1, 'Mu claim', { vis: 'public' }), factsRow(2, 'Nu claim', { vis: 'internal' }), factsRow(3, 'Xi claim', { vis: 'shared' }));+ expect(parseFactsFence(run(body, PRIVATE).page.compiled_truth).facts.map(f => f.visibility)).toEqual(['private', 'private', 'private']);+ const world = run(body, WORLD);+ expect(parseFactsFence(world.page.compiled_truth).facts.map(f => f.visibility)).toEqual(['world', 'private', 'private']);+ expectRepaired(world, WORLD);+ });++ test('invalid row_num 0 and TAKES_ROW_NUM_COLLISION are renumbered above every used number', () => {+ const r = run(takes(takesRow(0, 'Omicron take'), takesRow(2, 'Pi take'), takesRow(2, 'Rho take')));+ expect(parseTakesFence(r.page.compiled_truth).takes.map(t => [t.rowNum, t.claim])).toEqual([[3, 'Omicron take'], [2, 'Pi take'], [4, 'Rho take']]);+ expect(r.fixes.filter(f => f.class === 'renumber').map(f => [f.from, f.row])).toEqual([[0, 3], [2, 4]]);+ expectRepaired(r);+ });++ test('TAKES_HOLDER_INVALID: an assistant-style holder maps to brain; a display name waits for Tier 2', () => {+ const r = run(takes(takesRow(1, 'Sigma take', { who: 'System' }), takesRow(2, 'Tau take', { who: 'Alice Example' })));+ expect(r.fixes.map(f => f.class)).toEqual(['holder_alias']);+ expect(r.residual.map(i => [i.reason, i.row, i.column])).toEqual([['holder_unresolved', 2, 'who']]);+ expect(parseTakesFence(r.page.compiled_truth).takes[0]!.holder).toBe('brain');+ });+});++describe('Tier 2 verified holders', () => {+ test('a holder the resolver verified is written; anything else stays residual', () => {+ const ctx: FenceCtx = { ...PRIVATE, verifiedHolders: new Map([['Alice Example', 'people/alice-example']]) };+ const r = run(takes(takesRow(1, 'Upsilon take', { who: 'Alice Example' })), ctx);+ expect(classes(r)).toEqual(['holder_verified']);+ expect(parseTakesFence(r.page.compiled_truth).takes[0]!.holder).toBe('people/alice-example');+ expectRepaired(r, ctx);+ });+});++describe('close_fence and the protection boundary', () => {+ test('two row blocks separated by a blank line are residual split_rows and nothing changes', () => {+ const body = [FB, FH, FS, factsRow(1, 'Phi claim'), '', factsRow(2, 'Chi claim'), ''].join('\n');+ const r = run(body);+ expect(reasons(r)).toEqual(['split_rows']);+ expect(r.page.compiled_truth).toBe(body);+ });++ test('prose after the table keeps the fence open (manual) so the boundary never shows it', () => {+ const body = [FB, FH, FS, factsRow(1, 'Psi claim'), '', 'TRAILING-PROSE-CANARY stays hidden'].join('\n');+ const r = run(body);+ expect(reasons(r)).toEqual(['unclosed_trailing_content']);+ expect(r.page.compiled_truth).toBe(body);+ expect(sanitizeRemoteBody(r.page.compiled_truth)).not.toContain('TRAILING-PROSE-CANARY');+ expect(FENCE_REASONS.unclosed_trailing_content.manualOnly).toBe(true);+ });++ test('an end marker with no begin is never guessed', () => {+ const body = ['## Facts', '', FH, factsRow(1, 'Omega claim'), FE].join('\n');+ const r = run(body);+ expect(reasons(r)).toEqual(['missing_begin']);+ expect(r.page.compiled_truth).toBe(body);+ });++ test('a repeated marker is manual and nothing changes', () => {+ const body = [facts(factsRow(1, 'Alpha two', { kind: 'signal' })), facts(factsRow(2, 'Beta two'))].join('\n');+ const r = run(body);+ expect(reasons(r)).toContain('repeated_marker');+ expect(r.page.compiled_truth).toBe(body);+ });+});++describe('marker_form', () => {+ test('two-dash takes markers above a table become the canonical form', () => {+ const body = ['## Takes', '', '<!-- gbrain:takes:begin -->', '', TH, TS, takesRow(1, 'Gamma two'), '<!-- gbrain:takes:end -->', ''].join('\n');+ const r = run(body);+ expect(classes(r)).toEqual(['marker_form']);+ expect(r.page.compiled_truth).toBe(['## Takes', '', TB, '', TH, TS, takesRow(1, 'Gamma two'), TE, ''].join('\n'));+ expectRepaired(r);+ });++ test('a page that mentions the two-dash form in prose is not rewritten', () => {+ const body = 'Authors sometimes write\n<!-- gbrain:takes:begin -->\nfrom memory; that is not a fence.\n';+ const r = run(body);+ expect(reasons(r)).toEqual(['marker_near_miss']);+ expect(r.page).toBe(r.before);+ });++ test('a two-dash facts fence with a table parses clean today and stays byte-identical', () => {+ const body = ['## Facts', '', '<!-- gbrain:facts:begin -->', FH, FS, factsRow(1, 'Delta two', { kind: 'partnership' }), '<!-- gbrain:facts:end -->'].join('\n');+ const r = run(body);+ expect(r.page).toBe(r.before);+ expect(r.fixes).toEqual([]);+ });+});++describe('renumber (prior-aware)', () => {+ const stored = (factsRows: Array<[number, string]>, takesRows: Array<[number, string]> = []): StoredRowMap =>+ ({ facts: new Map(factsRows), takes: new Map(takesRows) });++ test('the stored second occurrence keeps its number; the first is renumbered', () => {+ const ctx = { ...PRIVATE, storedRows: stored([[1, 'Stored claim']]) };+ const r = run(facts(factsRow(1, 'New claim'), factsRow(1, 'Stored claim')), ctx);+ expect(parseFactsFence(r.page.compiled_truth).facts.map(f => [f.rowNum, f.claim])).toEqual([[2, 'New claim'], [1, 'Stored claim']]);+ expectRepaired(r, ctx);+ });++ test('a freed highest number (stored, gone from the fence) is never reused', () => {+ const ctx = { ...PRIVATE, storedRows: stored([[1, 'Kept claim'], [9, 'Deleted claim']]) };+ const r = run(facts(factsRow(1, 'Kept claim'), factsRow(1, 'Another claim')), ctx);+ expect(parseFactsFence(r.page.compiled_truth).facts.map(f => f.rowNum)).toEqual([1, 10]);+ });++ test('struck rows in the other section count as used numbers', () => {+ const timeline = facts(factsRow(7, '~~Struck claim~~', { ctx: 'forgotten: asked' }));+ const r = run(facts(factsRow(0, 'Fresh claim')), PRIVATE, timeline);+ expect(parseFactsFence(r.page.compiled_truth).facts[0]!.rowNum).toBe(8);+ expect(r.page.timeline).toBe(timeline);+ });++ test('a duplicate across body and timeline is renumbered once, in the fence that was already malformed', () => {+ const body = facts(factsRow(1, 'Body claim', { kind: 'signal' }));+ const timeline = facts(factsRow(1, 'Timeline claim'));+ const r = run(body, PRIVATE, timeline);+ expect(r.page.timeline).toBe(timeline);+ expect(parseFactsFence(r.page.compiled_truth).facts.map(f => f.rowNum)).toEqual([2]);+ expectRepaired(r);+ });++ test('a duplicate across two clean sections renumbers the later occurrence', () => {+ const r = run(facts(factsRow(1, 'Body only')), PRIVATE, facts(factsRow(1, 'Timeline only')));+ expect(r.page.compiled_truth).toBe(r.before.compiled_truth);+ expect(parseFactsFence(r.page.timeline).facts.map(f => f.rowNum)).toEqual([2]);+ expectRepaired(r);+ });++ test('superseded by #N naming a duplicated N is residual (facts context)', () => {+ const r = run(facts(factsRow(2, 'One'), factsRow(2, 'Two'), factsRow(3, '~~Three~~', { ctx: 'superseded by #2' })));+ expect(reasons(r)).toEqual(['superseded_ambiguous']);+ expect(r.residual.map(i => [i.row, i.line])).toEqual([[2, 7], [2, 8]]);+ expect(FENCE_REASONS.superseded_ambiguous.manualOnly).toBe(true);+ });++ test('superseded by #N naming a duplicated N is residual (takes source)', () => {+ const r = run(takes(takesRow(4, 'Old take'), takesRow(4, 'Other take'), takesRow(5, '~~Older take~~', { src: 'call; superseded by #4' })));+ expect(reasons(r)).toEqual(['superseded_ambiguous']);+ });++ test('hidden rows are never renumbered and their numbers are never handed out', () => {+ const ctx = { ...PRIVATE, hiddenRows: new Set([5, 12]) };+ const r = run(facts(factsRow(5, 'Caller row'), factsRow(0, 'Needs a number')), ctx);+ expect(parseFactsFence(r.page.compiled_truth).facts.map(f => f.rowNum)).toEqual([5, 13]);+ });++ test('a header without a # column mints numbers the same way', () => {+ const body = [FB, '| claim | kind | confidence | visibility | notability |', factsRow(0, 'x').replace(/.*/, '| Minted one | fact | 0.9 | private | low |'), FE].join('\n');+ const ctx = { ...PRIVATE, storedRows: stored([[3, 'Old stored']]) };+ const r = run(body, ctx);+ expect(parseFactsFence(r.page.compiled_truth).facts.map(f => [f.rowNum, f.claim, f.confidence])).toEqual([[4, 'Minted one', 0.9]]);+ expectRepaired(r, ctx);+ });+});++describe('header rules', () => {+ test('header_alias moves raw cells into canonical order and keeps their exact text', () => {+ const body = [FB, '| # | claim | type | visibility | confidence | notability | date | valid_until | source | context |',+ '| 1 | Kappa two | fact | private | 0.9 | high | 2026-04-29T18:30:00Z | | call | |', FE].join('\n');+ const r = run(body);+ expect(classes(r)).toEqual(['header_alias']);+ expect(r.page.compiled_truth).toContain('| 1 | Kappa two | fact | 0.9 | private | high | 2026-04-29T18:30:00Z | | call | |');+ expectRepaired(r);+ });++ test('column_default fills required facts columns absent from the whole header', () => {+ const body = [FB, '| # | claim | kind | source |', '|---|---|---|---|', '| 1 | Lambda two | fact | call |', FE].join('\n');+ const r = run(body);+ expect(classes(r)).toEqual(['column_default', 'header_alias']);+ expect(r.fixes.filter(f => f.class === 'column_default').map(f => f.column).sort()).toEqual(['confidence', 'notability', 'visibility']);+ const [fact] = parseFactsFence(r.page.compiled_truth).facts;+ expect([fact!.confidence, fact!.notability, fact!.visibility, fact!.source]).toEqual([1, 'medium', 'private', 'call']);+ expectRepaired(r);+ });++ test('an unmappable column is residual header_unmapped (Tier 3)', () => {+ const r = run([FB, '| # | claim | kind | mood |', '| 1 | Mu two | fact | calm |', FE].join('\n'));+ expect(reasons(r)).toEqual(['header_unmapped']);+ expect(FENCE_REASONS.header_unmapped.tier).toBe('llm');+ });++ test('a takes table inside a facts fence is manual', () => {+ const r = run([FB, TH, TS, takesRow(1, 'Nu two'), FE].join('\n'));+ expect(reasons(r)).toEqual(['takes_in_facts']);+ });++ test('takes with no weight column, or no holder column, are manual', () => {+ expect(reasons(run([TB, '| # | claim | kind | who |', '| 1 | Xi two | take | brain |', TE].join('\n')))).toEqual(['weight_missing']);+ expect(reasons(run([TB, '| # | claim | kind | weight |', '| 1 | Pi two | take | 0.5 |', TE].join('\n')))).toEqual(['holder_missing']);+ });++ test('a fence with rows and no header is Tier 3', () => {+ expect(reasons(run([FB, factsRow(1, 'Rho two'), FE].join('\n')))).toEqual(['no_header']);+ });+});++describe('cell rules', () => {+ test('confidence_format: percent and stray inner whitespace; out of range is manual', () => {+ const r = run(facts(factsRow(1, 'Sigma two', { conf: '85%' }), factsRow(2, 'Tau two', { conf: '0. 9' }), factsRow(3, 'Upsilon two', { conf: '1.5' })));+ expect(parseFactsFence(r.page.compiled_truth).facts.map(f => f.confidence)).toEqual([0.85, 0.9]);+ expect(r.residual.map(i => [i.reason, i.row, i.column])).toEqual([['confidence_out_of_range', 3, 'confidence']]);+ });++ test('unmapped enum words and invalid claim values are manual and name the allowed vocabulary', () => {+ const r = run(facts(factsRow(1, 'Phi two', { vis: 'everyone' })));+ expect(r.residual).toEqual([{ fence: 'facts', section: 'body', row: 1, column: 'visibility', line: 7, reason: 'enum_unmapped', allowed: ['private', 'world'] }]);+ const wide = [FB, `${FH} claim_metric | claim_value | claim_unit | claim_period |`,+ '| 1 | Chi two | fact | 1.0 | private | medium | | | | | arr | lots | USD | annual |', FE].join('\n');+ expect(reasons(run(wide))).toEqual(['claim_value_invalid']);+ });++ test('takes kinds outside the synonym table and pack-declared kinds are never coerced', () => {+ const ctx: FenceCtx = { ...PRIVATE, takesPackKinds: ['thesis', 'view'] };+ const r = run(takes(takesRow(1, 'Psi two', { kind: 'wibble' }), takesRow(2, 'Omega three', { kind: 'thesis' }), takesRow(3, 'Alpha three', { kind: 'view' })), ctx);+ expect(r.residual.map(i => [i.reason, i.row])).toEqual([['takes_kind_unsupported', 1], ['takes_kind_unsupported', 2], ['takes_kind_unsupported', 3]]);+ expect(r.fixes).toEqual([]);+ expect(FENCE_REASONS.takes_kind_unsupported.manualOnly).toBe(true);+ });++ test('an empty takes weight is weight_missing; a word is out of range', () => {+ const r = run(takes(takesRow(1, 'Beta three', { w: '' }), takesRow(2, 'Gamma three', { w: 'high' })));+ expect(r.residual.map(i => i.reason)).toEqual(['weight_missing', 'confidence_out_of_range']);+ });++ test('a 9-cell facts row gains a context cell only when kind_map needs one', () => {+ const body = [FB, FH, '| 1 | Delta three | opinion | 1.0 | private | medium | | | call |', FE].join('\n');+ const r = run(body);+ expect(r.page.compiled_truth).toContain('| 1 | Delta three | belief | 1.0 | private | medium | | | call | original kind: opinion |');+ expectRepaired(r);+ });+});++describe('Invariant 0', () => {+ test('a page that compiles is returned unchanged (same object), including 9-cell facts and 6-cell takes rows', () => {+ const body = [FB, FH, '| 1 | Epsilon three | fact | 1.0 | private | medium | | | call |', FE, '', TB, TH, '| 1 | Zeta three | take | brain | 0.5 | 2026-01 |', TE].join('\n');+ const r = run(body);+ expect(r.page).toBe(r.before);+ expect([r.fixes, r.residual]).toEqual([[], []]);+ });++ test('a marker-free page does no work', () => {+ const before = page('Just prose | with a pipe |\n');+ expect(normalizeFences(before, PRIVATE).page).toBe(before);+ });++ test('a clean section stays byte-identical when the other section is repaired', () => {+ const body = takes(takesRow(1, 'Eta three'));+ const r = run(body, PRIVATE, facts(factsRow(1, 'Theta three', { kind: 'funding' })));+ expect(r.page.compiled_truth).toBe(body);+ expectRepaired(r);+ });++ test('markers quoted in code are examples: never closed, renumbered or rewritten', () => {+ const example = ['```markdown', FB, FH, factsRow(0, 'Example row', { kind: 'partnership' }), '```'].join('\n');+ const body = `${example}\n\n${facts(factsRow(1, 'Iota three', { kind: 'pledge' }))}`;+ const r = run(body);+ expect(r.page.compiled_truth.startsWith(example)).toBe(true);+ expect(r.fixes.map(f => [f.class, f.line])).toEqual([['kind_map', 13]]);+ expectRepaired(r);+ });++ test('normalize is idempotent and its output is a fixed point', () => {+ const r = run(facts(factsRow(0, 'Kappa three', { kind: 'signal', vis: 'team', not: 'minor', conf: '70%' })));+ const again = normalizeFences(r.page, PRIVATE);+ expect(again.page).toBe(r.page);+ expect(again.fixes).toEqual([]);+ });+});++describe('location-only privacy', () => {+ test('unique claim, holder, kind and context strings never appear in fixes, residual or messages', () => {+ const sentinels = ['CLAIMSENTINEL7781', 'HOLDERSENTINEL7781', 'KINDSENTINEL7781', 'CONTEXTSENTINEL7781'];+ const body = [+ facts(factsRow(0, `${sentinels[0]} one`, { kind: sentinels[2]!, ctx: sentinels[3]!, vis: 'nowhere' })),+ takes(takesRow(1, `${sentinels[0]} two`, { who: `Mr ${sentinels[1]}`, kind: sentinels[2]! }), takesRow(1, 'other', { kind: 'wibble' })),+ ].join('\n');+ const r = run(body);+ const messages = r.residual.map(i => fenceMessage(issueLocation(i)));+ const surface = JSON.stringify([r.fixes, r.residual, messages]);+ for (const s of sentinels) expect(surface).not.toContain(s);+ expect(r.residual.length).toBeGreaterThan(0);+ });++ test('every manual-only residual names the exact place to edit', () => {+ const r = run(facts(factsRow(1, 'Lambda three', { vis: 'everyone' })));+ const message = fenceMessage(issueLocation(r.residual[0]!));+ expect(message).toBe('Fence enum_unmapped: in the facts fence (body), row 1, column visibility, at line 7. '+ + 'Column(s) `visibility` of row(s) 1 in the facts fence (body, line 7) hold a value gbrain cannot map. Use one of `private`, `world`.');+ });+});++describe('containment and the allocator', () => {+ test('safeNormalizeFences turns a throw into residual normalizer_failed and returns the page unchanged', () => {+ const body = facts(factsRow(1, 'Mu three', { kind: 'signal' }));+ let reads = 0;+ const exploding = { timeline: '', get compiled_truth() { if (++reads > 1) throw new Error('boom'); return body; } } as FencePage;+ expect(() => normalizeFences(exploding, PRIVATE)).toThrow('boom');+ reads = 0;+ const r = safeNormalizeFences(exploding, PRIVATE);+ expect(r.page).toBe(exploding);+ expect(r.fixes).toEqual([]);+ expect(r.residual.map(i => i.reason)).toEqual(['normalizer_failed']);+ expect(FENCE_REASONS.normalizer_failed.autoRetry).toBe(false);+ });++ test('safeNormalizeFences returns what normalizeFences returns when nothing throws', () => {+ const before = page(facts(factsRow(1, 'Nu three', { kind: 'signal' })));+ expect(safeNormalizeFences(before, PRIVATE)).toEqual(normalizeFences(before, PRIVATE));+ });++ test('nextFreeRowNum never returns a number used on the page or in stored rows', () => {+ const body = [facts(factsRow(3, 'Xi three'), factsRow(11, '~~Struck~~', { kind: 'bogus' })), takes(takesRow(20, 'Omicron three'))].join('\n');+ const timeline = facts(factsRow(15, 'Pi three'));+ expect(nextFreeRowNum(page(body, timeline))).toBe(21);+ expect(nextFreeRowNum(page(body, timeline), { facts: new Map([[40, 'gone']]), takes: new Map() })).toBe(41);+ expect(nextFreeRowNum(page(''))).toBe(1);+ });++ test('FENCE_RULES_VERSION is a positive integer', () => {+ expect(Number.isInteger(FENCE_RULES_VERSION) && FENCE_RULES_VERSION > 0).toBe(true);+ });+});diff --git a/test/fence-repair-raw-rows.test.ts b/test/fence-repair-raw-rows.test.tsnew file mode 100644index 0000000000..2667e5ffb4--- /dev/null+++ b/test/fence-repair-raw-rows.test.ts@@ -0,0 +1,143 @@+/**+ * Raw-row extraction for fence repair (#6188): layouts, the positional+ * fallback, escapes and source spans, rows before the header, before-regions+ * of unclosed fences, code-quoted markers, near-miss takes markers and row+ * identity. The strict-parser differential over every suite fixture lives in+ * fence-repair-fixtures.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { FACTS_FENCE_BEGIN as FB, FACTS_FENCE_END as FE } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN as TB, TAKES_FENCE_END as TE } from '../src/core/takes-fence.ts';+import { extractRawRows, primaryFence, rowNumOf, type RawFence } from '../src/core/fence-repair/raw-rows.ts';+import { CANONICAL_HEADER } from '../src/core/fence-repair/schema.ts';+import { renderFactsTable } from '../src/core/facts-fence.ts';+import { renderTakesFence } from '../src/core/takes-fence.ts';++const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';+const TH = '| # | claim | kind | who | weight | since | source |';++function only(text: string, kind: 'facts' | 'takes'): RawFence {+ const fence = primaryFence(extractRawRows(text), kind);+ if (!fence) throw new Error(`no ${kind} fence`);+ return fence;+}+const columnsOf = (fence: RawFence, k = 0) => Object.fromEntries([...fence.rows[k]!.byColumn].map(([c, cell]) => [c, cell.text]));++describe('layouts', () => {+ test('facts rows of 9, 10 and 14 cells map to canonical columns and are accepted', () => {+ const text = [FB, FH,+ '| 1 | Nine cells | fact | 1.0 | private | medium | | | call |',+ '| 2 | Ten cells | fact | 0.9 | world | low | 2026-01-01 | | call | ctx |',+ '| 3 | Fourteen cells | fact | 0.8 | private | high | | | | | arr | 2.5M | USD | annual |', FE].join('\n');+ const fence = only(text, 'facts');+ expect(fence.rows.map(r => [r.cells.length, r.accepted, r.shape])).toEqual([[9, true, 'ok'], [10, true, 'ok'], [14, true, 'ok']]);+ expect(columnsOf(fence, 2)).toMatchObject({ claim: 'Fourteen cells', claim_value: '2.5M', claim_period: 'annual' });+ expect(fence.needsRewrite).toBe(false);+ });++ test('takes rows of 6, 7 and 13 cells; resolution columns are read by header name', () => {+ const wide = `${TH} resolved | quality | evidence | value | unit | by |`;+ const text = [TB, wide,+ '| 1 | Six cells | take | brain | 0.5 | 2026-01 |',+ '| 2 | Seven cells | bet | world | 0.7 | 2026-02 | notes |',+ '| 3 | Thirteen cells | bet | brain | 0.6 | 2026-03 | notes | 2026-06 | correct | memo | 12 | usd | brain |', TE].join('\n');+ const fence = only(text, 'takes');+ expect(fence.rows.map(r => r.accepted)).toEqual([true, true, true]);+ expect(columnsOf(fence, 2)).toMatchObject({ who: 'brain', quality: 'correct', by: 'brain' });+ });++ test('the canonical header text matches what the renderers emit', () => {+ const fact = { rowNum: 1, claim: 'c', kind: 'fact' as const, confidence: 1, visibility: 'private' as const, notability: 'low' as const, active: true };+ expect(renderFactsTable([fact])).toContain(`${CANONICAL_HEADER.facts.narrow}\n${CANONICAL_HEADER.facts.narrowSep}`);+ expect(renderFactsTable([{ ...fact, claimMetric: 'arr' }])).toContain(`${CANONICAL_HEADER.facts.wide}\n${CANONICAL_HEADER.facts.wideSep}`);+ const take = { rowNum: 1, claim: 'c', kind: 'take', holder: 'brain', weight: 0.5, active: true };+ expect(renderTakesFence([take])).toContain(`${CANONICAL_HEADER.takes.narrow}\n${CANONICAL_HEADER.takes.narrowSep}`);+ expect(renderTakesFence([{ ...take, resolvedQuality: 'correct' as const }])).toContain(`${CANONICAL_HEADER.takes.wide}\n${CANONICAL_HEADER.takes.wideSep}`);+ });++ test('an alias header (no `kind` token) is recognized and maps through aliases', () => {+ const fence = only([TB, '| Holder | Claim | Type | Confidence | Source |', '| brain | Aliased | take | 0.4 | notes |', TE].join('\n'), 'takes');+ expect(fence.strictHeader).toBe(false);+ expect(fence.columns).toEqual(['who', 'claim', 'kind', 'weight', 'source']);+ expect(fence.needsRewrite).toBe(true);+ expect(columnsOf(fence)).toEqual({ who: 'brain', claim: 'Aliased', kind: 'take', weight: '0.4', source: 'notes' });+ expect(fence.rows[0]!.accepted).toBe(false);+ });++ test('with no recognizable header, rows read positionally and the fence reports no_header', () => {+ const fence = only([FB, '| 7 | Headless | fact | 1.0 | private | low | | | call |', FE].join('\n'), 'facts');+ expect(fence.header).toBeNull();+ expect(fence.rows[0]!.beforeHeader).toBe(true);+ expect(columnsOf(fence)).toMatchObject({ '#': '7', claim: 'Headless', kind: 'fact' });+ expect(fence.issues.map(i => i.reason)).toEqual(['no_header']);+ });+});++describe('cells, spans and identity', () => {+ test('an escaped pipe stays in its cell, <br> decodes, and spans point at the source text', () => {+ const text = [FB, FH, '| 1 | A \\| B<br>C | fact | 1.0 | private | medium | | | call | |', FE].join('\n');+ const fence = only(text, 'facts');+ const claim = fence.rows[0]!.byColumn.get('claim')!;+ expect(claim.text).toBe('A | B\nC');+ expect(claim.raw).toBe('A \\| B<br>C');+ expect(text.slice(claim.start, claim.end)).toBe(claim.raw);+ for (const cell of fence.rows[0]!.cells) expect(text.slice(cell.start, cell.end)).toBe(cell.raw);+ });++ test('row identity is the ordinal among data rows, independent of row number and claim', () => {+ const fence = only([FB, '| 3 | Early | fact |', FH, '|---|---|', '| 3 | Same | fact | 1.0 | private | low | | | x |', '| 3 | Same | fact | 1.0 | private | low | | | x |', FE].join('\n'), 'facts');+ expect(fence.rows.map(r => [r.occurrence, r.beforeHeader, rowNumOf(fence, r)])).toEqual([[0, true, 3], [1, false, 3], [2, false, 3]]);+ expect(fence.separators).toHaveLength(1);+ expect(fence.issues.map(i => [i.reason, i.line])).toEqual([['row_before_header', 2]]);+ });++ test('rows that miss a middle cell or carry extra cells are flagged', () => {+ const fence = only([FB, FH, '| 1 | Short | fact | 1.0 | private | medium | | x |', '| 2 | Extra | partner | ship | 1.0 | private | medium | | | x | | y |', FE].join('\n'), 'facts');+ expect(fence.rows.map(r => r.shape)).toEqual(['short_row', 'extra_cells']);+ });+});++describe('markers and regions', () => {+ test('an unclosed fence\'s before-region runs to the end of the section', () => {+ const text = [FB, FH, '| 1 | Open | fact | 1.0 | private | low | | | x | |', '', 'trailing'].join('\n');+ const fence = only(text, 'facts');+ expect(fence.end).toBeNull();+ expect(fence.regionEnd).toBe(text.length);+ });++ test('markers quoted in code are not fences', () => {+ const text = ['```markdown', FB, FH, '| 1 | Example | fact |', FE, '```', 'Inline `' + TB + '` mention.'].join('\n');+ expect(extractRawRows(text).fences).toEqual([]);+ });++ test('a stray end marker before any begin reports missing_begin', () => {+ const raw = extractRawRows([FH, '| 1 | Orphan | fact |', FE].join('\n'));+ expect(raw.issues.map(i => [i.fence, i.reason, i.line])).toEqual([['facts', 'missing_begin', 3]]);+ });++ test('a second fence of the same kind is a repeat on the primary fence', () => {+ const block = [FB, FH, FE].join('\n');+ const raw = extractRawRows(`${block}\n${block}`);+ expect(raw.fences.map(f => f.primary)).toEqual([true, false]);+ expect(primaryFence(raw, 'facts')!.issues.map(i => i.reason)).toEqual(['repeated_marker']);+ });++ test('a two-dash takes marker alone on its line is a near-miss fence; in prose it is reported, not a fence', () => {+ const fence = only(['<!-- gbrain:takes:begin -->', TH, '| 1 | Near | take | brain | 0.5 | 2026 | x |', '<!--gbrain:takes:end-->'].join('\n'), 'takes');+ expect([fence.begin.nearMiss, fence.end?.nearMiss, fence.rows.length, fence.rows[0]!.accepted]).toEqual([true, true, 1, false]);+ const prose = extractRawRows('See the gbrain:takes:begin marker docs.');+ expect([prose.fences.length, prose.issues.map(i => i.reason)]).toEqual([0, ['marker_near_miss']]);+ });++ test('a two-dash facts marker is not a fence (it parses clean today)', () => {+ expect(extractRawRows(['<!-- gbrain:facts:begin -->', FH, '<!-- gbrain:facts:end -->'].join('\n')).fences).toEqual([]);+ });++ test('CRLF line endings: spans exclude the carriage return and lines are numbered', () => {+ const text = [FB, FH, '| 1 | Windows | fact | 1.0 | private | low | | | x | |', FE].join('\r\n');+ const fence = only(text, 'facts');+ expect(fence.rows[0]!.line).toBe(3);+ expect(text.slice(fence.rows[0]!.start, fence.rows[0]!.end).endsWith('|')).toBe(true);+ expect(fence.rows[0]!.accepted).toBe(true);+ });+});diff --git a/test/fence-repair-reasons.test.ts b/test/fence-repair-reasons.test.tsnew file mode 100644index 0000000000..785523acb9--- /dev/null+++ b/test/fence-repair-reasons.test.ts@@ -0,0 +1,76 @@+/**+ * The fence reason table (#6188, D13): every reason the spec names has one+ * entry with a docs anchor, tier, manual-only flag and a location-only fix+ * template; the message grammar renders locations, never values.+ */+import { describe, expect, test } from 'bun:test';+import {+ FENCE_REASON_CODES, FENCE_REASONS, GATE_REASONS, fenceMessage, renderFenceFix,+} from '../src/core/fence-repair/reasons.ts';+import type { FenceReason } from '../src/core/fence-repair/types.ts';++const SPEC_MANUAL: FenceReason[] = [+ 'missing_begin', 'split_rows', 'repeated_marker', 'takes_in_facts', 'superseded_ambiguous', 'enum_unmapped',+ 'weight_missing', 'confidence_out_of_range', 'claim_value_invalid', 'takes_kind_unsupported',+];+/** Manual-only residuals this module adds where the spec says "residual" without naming one. */+const ADDED_MANUAL: FenceReason[] = ['unclosed_trailing_content', 'marker_near_miss', 'holder_missing'];+const SPEC_TIER3: FenceReason[] = ['header_unmapped', 'no_header', 'row_before_header', 'short_row', 'extra_cells'];+const SPEC_OTHERS: FenceReason[] = [+ 'holder_unresolved',+ 'unparseable', 'row_collision', 'quoted_fence_rows', 'stored_row_collision', 'withdrawn_claim_in_malformed_fence',+ 'target_fence_malformed', 'prepare_time', 'normalizer_failed',+ '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',+ 'still_invalid', 'claim_changed', 'row_number_changed', 'visibility_loosened', 'row_count_changed', 'cell_changed', 'protection_loosened',+];++describe('FENCE_REASONS', () => {+ test('holds exactly the reasons the spec names (plus the documented additions)', () => {+ expect([...FENCE_REASON_CODES].sort()).toEqual([...SPEC_MANUAL, ...ADDED_MANUAL, ...SPEC_TIER3, ...SPEC_OTHERS].sort());+ });++ test('screen residual classes carry the spec\'s tier and manual-only flag', () => {+ for (const reason of [...SPEC_MANUAL, ...ADDED_MANUAL]) {+ expect([reason, FENCE_REASONS[reason].tier, FENCE_REASONS[reason].manualOnly, FENCE_REASONS[reason].autoRetry]).toEqual([reason, 'manual', true, false]);+ }+ for (const reason of SPEC_TIER3) expect([reason, FENCE_REASONS[reason].tier, FENCE_REASONS[reason].manualOnly]).toEqual([reason, 'llm', false]);+ expect(FENCE_REASONS.holder_unresolved.tier).toBe('resolver');+ expect(FENCE_REASONS.stored_row_collision.manualOnly).toBe(true);+ });++ test('gate reasons map to their letters', () => {+ expect(Object.entries(GATE_REASONS).map(([letter, reason]) => [letter, FENCE_REASONS[reason].gate])).toEqual(+ [['a', 'a'], ['b', 'b'], ['c', 'c'], ['d', 'd'], ['e', 'e'], ['f', 'f'], ['g', 'g']]);+ });++ test('each reason has its own write-refusals anchor', () => {+ const anchors = FENCE_REASON_CODES.map(r => FENCE_REASONS[r].docs);+ expect(new Set(anchors).size).toBe(anchors.length);+ for (const reason of FENCE_REASON_CODES) expect(FENCE_REASONS[reason].docs).toBe(`docs/guides/write-refusals.md#fence-${reason}`);+ });++ test('fix templates use only location placeholders and every rendered fix is complete', () => {+ for (const reason of FENCE_REASON_CODES) {+ const placeholders = FENCE_REASONS[reason].fix.match(/\{\w+\}/g) ?? [];+ for (const p of placeholders) expect(['{fence}', '{section}', '{rows}', '{columns}', '{line}', '{allowed}']).toContain(p);+ const rendered = renderFenceFix({ reason, fence: 'facts', section: 'body', rows: [3], columns: ['kind'], line: 12 });+ expect(rendered).not.toMatch(/\{\w+\}/);+ expect(rendered.length).toBeGreaterThan(20);+ }+ });++ test('paid reasons are exactly the ones whose fix raises spend or enables the model', () => {+ expect(FENCE_REASON_CODES.filter(r => FENCE_REASONS[r].paid).sort()).toEqual(['budget_exhausted', 'llm_disabled', 'no_pricing']);+ });+});++describe('message grammar', () => {+ test('Fence <reason>: in the <fence> fence (<section>), rows, columns, line, then the fix', () => {+ const message = fenceMessage({ reason: 'short_row', fence: 'takes', section: 'timeline', rows: [4, 9], columns: [], line: 30 });+ expect(message.startsWith('Fence short_row: in the takes fence (timeline), rows 4, 9, at line 30. Row(s) 4, 9 of the takes fence in the timeline')).toBe(true);+ expect(fenceMessage({ reason: 'enum_unmapped', fence: 'facts', section: 'body', rows: [2], columns: ['notability'], line: 8, allowed: ['high', 'medium', 'low'] }))+ .toContain('row 2, column notability, at line 8. ');+ });+});diff --git a/test/fence-repair-validate.test.ts b/test/fence-repair-validate.test.tsnew file mode 100644index 0000000000..064e777260--- /dev/null+++ b/test/fence-repair-validate.test.ts@@ -0,0 +1,185 @@+/**+ * Fence repair validator (#6188): one adversarial repair per gate (a)-(g),+ * rejected with its letter; Tier 3-style stubs against gate (f) (TE2);+ * verified holders; the Tier 1 fixed point. All content is synthetic.+ */+import { describe, expect, test } from 'bun:test';+import { FACTS_FENCE_BEGIN as FB, FACTS_FENCE_END as FE } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN as TB, TAKES_FENCE_END as TE } from '../src/core/takes-fence.ts';+import { sanitizeRemoteBody } from '../src/core/remote-body.ts';+import { normalizeFences } from '../src/core/fence-repair/normalize.ts';+import { isFenceFixedPoint, validateFenceRepair, type ValidateCtx } from '../src/core/fence-repair/validate.ts';+import type { FenceCtx, FenceLocation, FencePage } from '../src/core/fence-repair/types.ts';++const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';+const TH = '| # | claim | kind | who | weight | since | source |';+const PRIVATE: FenceCtx = { pageVisibility: 'private' };+const page = (compiled_truth: string, timeline = ''): FencePage => ({ compiled_truth, timeline });+const facts = (...rows: string[]) => [FB, FH, ...rows, FE, ''].join('\n');+const takes = (...rows: string[]) => [TB, TH, ...rows, TE, ''].join('\n');++const ROW1 = '| 1 | Alpha claim | partnership | 0.9 | private | medium | 2026-01-01 | | call | note |';+const ROW1_FIXED = '| 1 | Alpha claim | fact | 0.9 | private | medium | 2026-01-01 | | call | note; original kind: partnership |';+const ROW2 = '| 2 | Beta claim | fact | 0.8 | private | high | 2026-02-02 | | call | |';+const BEFORE = page(facts(ROW1, ROW2));++/** Validate `after` against `before` with the issues Tier 1 found on `before`. */+function check(before: FencePage, after: FencePage, ctx: FenceCtx = PRIVATE, tier: ValidateCtx['tier'] = 'llm') {+ const found = normalizeFences(before, ctx);+ const issues: FenceLocation[] = [...found.fixes, ...found.residual];+ return validateFenceRepair(before, after, { ...ctx, tier, issues });+}+const gateOf = (r: ReturnType<typeof check>) => (r.ok ? 'ok' : r.gate);++describe('a correct repair passes', () => {+ test('the Tier 1 kind_map output passes every gate', () => {+ expect(check(BEFORE, page(facts(ROW1_FIXED, ROW2)), PRIVATE, 'deterministic')).toEqual({ ok: true });+ });++ test('a page that compiles validates against itself, even under a header with an unmapped column name', () => {+ const odd = page(facts(ROW2).replace('| notability |', '| salience |'));+ expect(check(odd, odd)).toEqual({ ok: true });+ });++ test('a close_fence repair passes', () => {+ const before = page([FB, FH, ROW2, '', ''].join('\n'));+ const r = normalizeFences(before, PRIVATE);+ expect(r.fixes.map(f => f.class)).toEqual(['close_fence']);+ expect(check(before, r.page, PRIVATE, 'deterministic')).toEqual({ ok: true });+ });+});++describe('one adversarial repair per gate', () => {+ test('(a) still_invalid: a residual warning remains', () => {+ const r = check(BEFORE, BEFORE);+ expect(r).toMatchObject({ ok: false, gate: 'a', reason: 'still_invalid', fence: 'facts', section: 'body' });+ });++ test('(e) row_count_changed: a dropped row', () => {+ const r = check(BEFORE, page(facts(ROW1_FIXED)));+ expect(r).toMatchObject({ ok: false, gate: 'e', reason: 'row_count_changed', rows: [2] });+ });++ test('(e) row_count_changed: closing after the first of two row blocks strands the second', () => {+ const body = [FB, FH, ROW2, '', '| 3 | Gamma claim | fact | 0.8 | private | high | | | call | |', ''].join('\n');+ const stranded = [FB, FH, ROW2, FE, '', '| 3 | Gamma claim | fact | 0.8 | private | high | | | call | |', ''].join('\n');+ expect(normalizeFences(page(body), PRIVATE).residual.map(i => i.reason)).toEqual(['split_rows']);+ expect(gateOf(check(page(body), page(stranded)))).toBe('e');+ expect(sanitizeRemoteBody(body)).not.toContain('Gamma claim');+ expect(sanitizeRemoteBody(body)).not.toContain('Beta claim');+ });++ test('(b) claim_changed: claim text edited', () => {+ const r = check(BEFORE, page(facts(ROW1_FIXED, ROW2.replace('Beta claim', 'Beta claim, edited'))));+ expect(r).toMatchObject({ ok: false, gate: 'b', reason: 'claim_changed', rows: [2] });+ });++ test('(b) claim_changed: rows reordered', () => {+ expect(gateOf(check(BEFORE, page(facts(ROW2, ROW1_FIXED))))).toBe('b');+ });++ test('(c) row_number_changed: a valid, unique row number moved', () => {+ const r = check(BEFORE, page(facts(ROW1_FIXED, ROW2.replace('| 2 |', '| 3 |'))));+ expect(r).toMatchObject({ ok: false, gate: 'c', reason: 'row_number_changed', rows: [2] });+ });++ test('(d) visibility_loosened: private became world', () => {+ const r = check(BEFORE, page(facts(ROW1_FIXED, ROW2.replace('private', 'world'))));+ expect(r).toMatchObject({ ok: false, gate: 'd', reason: 'visibility_loosened', rows: [2] });+ });++ test('(d) an invalid visibility becomes world only through public on a world page', () => {+ const before = page(facts('| 1 | Delta claim | fact | 0.9 | public | medium | | | | |'));+ const world = page(facts('| 1 | Delta claim | fact | 0.9 | world | medium | | | | |'));+ expect(gateOf(check(before, world, PRIVATE))).toBe('d');+ expect(gateOf(check(before, world, { pageVisibility: 'world' }))).toBe('ok');+ const team = page(facts('| 1 | Delta claim | fact | 0.9 | team | medium | | | | |'));+ expect(gateOf(check(team, world, { pageVisibility: 'world' }))).toBe('d');+ });++ test('(f) cell_changed: a valid confidence edited', () => {+ const r = check(BEFORE, page(facts(ROW1_FIXED, ROW2.replace('0.8', '0.7'))));+ expect(r).toMatchObject({ ok: false, gate: 'f', reason: 'cell_changed', rows: [2] });+ });++ test('(g) protection_loosened: closing a fence before trailing prose would publish the prose', () => {+ const before = page([FB, FH, ROW2, '', 'TRAILING-NOTE stays private'].join('\n'));+ const after = page([FB, FH, ROW2, FE, '', 'TRAILING-NOTE stays private'].join('\n'));+ expect(check(before, after)).toMatchObject({ ok: false, gate: 'g', reason: 'protection_loosened' });+ });++ test('failures are location-only', () => {+ const r = check(BEFORE, page(facts(ROW1_FIXED, ROW2.replace('Beta claim', 'Beta claim, edited'))));+ expect(JSON.stringify(r)).not.toContain('Beta');+ });+});++describe('gate (f): Tier 3 stubs (TE2)', () => {+ const gapRow = '| 2 | Zeta claim | fact | 0.9 | private | medium | 2026-02-02 | call |';+ const gapBefore = page(facts(ROW2.replace('| 2 |', '| 1 |'), gapRow));++ test('realigning a middle-gap row (cells move, text unchanged) passes', () => {+ const realigned = page(facts(ROW2.replace('| 2 |', '| 1 |'), '| 2 | Zeta claim | fact | 0.9 | private | medium | 2026-02-02 | | call | |'));+ expect(check(gapBefore, realigned)).toEqual({ ok: true });+ });++ test('editing a moved cell\'s text fails', () => {+ const edited = page(facts(ROW2.replace('| 2 |', '| 1 |'), '| 2 | Zeta claim | fact | 0.9 | private | medium | 2026-02-02 | | a call | |'));+ expect(gateOf(check(gapBefore, edited))).toBe('f');+ });++ const takesBefore = page(takes(+ '| 1 | Eta take | take | brain | 0.6 | 2026-01 | standup |',+ '| 2 | Theta take | take | brain | 0.5 |',+ ));+ const fixedShort = '| 2 | Theta take | take | brain | 0.5 | | |';+ test.each([+ ['weight', '| 1 | Eta take | take | brain | 0.7 | 2026-01 | standup |'],+ ['holder', '| 1 | Eta take | take | world | 0.6 | 2026-01 | standup |'],+ ['since', '| 1 | Eta take | take | brain | 0.6 | 2026-02 | standup |'],+ ['source', '| 1 | Eta take | take | brain | 0.6 | 2026-01 | review |'],+ ])('a stub that copies claims but edits a valid %s fails', (_, row1) => {+ expect(check(takesBefore, page(takes('| 1 | Eta take | take | brain | 0.6 | 2026-01 | standup |', fixedShort)))).toEqual({ ok: true });+ expect(gateOf(check(takesBefore, page(takes(row1, fixedShort))))).toBe('f');+ });++ test.each([+ ['confidence', ROW2.replace('0.8', '0.85')],+ ['context', ROW2.replace('| call | |', '| call | added note |')],+ ['since date', ROW2.replace('2026-02-02', '2026-02-03')],+ ])('a stub that edits a valid facts %s fails', (_, row2) => {+ expect(gateOf(check(BEFORE, page(facts(ROW1_FIXED, row2))))).toBe('f');+ });++ test('kind_map must keep the original word in context', () => {+ const dropped = '| 1 | Alpha claim | fact | 0.9 | private | medium | 2026-01-01 | | call | note |';+ expect(gateOf(check(BEFORE, page(facts(dropped, ROW2))))).toBe('f');+ });+});++describe('verified holders', () => {+ const before = page(takes('| 1 | Iota take | take | Alice Example | 0.6 | 2026-01 | call |'));+ const resolved = page(takes('| 1 | Iota take | take | people/alice-example | 0.6 | 2026-01 | call |'));++ test('a holder change passes only when Tier 2 verified that exact slug', () => {+ const verified: FenceCtx = { ...PRIVATE, verifiedHolders: new Map([['Alice Example', 'people/alice-example']]) };+ expect(check(before, resolved, verified, 'resolver')).toEqual({ ok: true });+ expect(gateOf(check(before, resolved, PRIVATE))).toBe('f');+ const other = page(takes('| 1 | Iota take | take | people/alice-other | 0.6 | 2026-01 | call |'));+ expect(gateOf(check(before, other, verified))).toBe('f');+ });++ test('assistant-style holders may only become brain', () => {+ const system = page(takes('| 1 | Kappa take | take | System | 0.6 | 2026-01 | call |'));+ expect(gateOf(check(system, page(takes('| 1 | Kappa take | take | brain | 0.6 | 2026-01 | call |'))))).toBe('ok');+ expect(gateOf(check(system, page(takes('| 1 | Kappa take | take | world | 0.6 | 2026-01 | call |'))))).toBe('f');+ });+});++describe('fixed point', () => {+ test('Tier 1 output is a fixed point; a malformed page or a model output with an enum variant is not', () => {+ expect(isFenceFixedPoint(normalizeFences(BEFORE, PRIVATE).page, PRIVATE)).toBe(true);+ expect(isFenceFixedPoint(BEFORE, PRIVATE)).toBe(false);+ expect(isFenceFixedPoint(page(facts(ROW2.replace('high', 'very_high'))), PRIVATE)).toBe(false);+ });+});