Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(fence-repair): a fence with no header reads numbered rows by position, so a claim an unescaped pipe cut is held manual, not sent to Tier 3 (#6188)

garrytan8e03698b811b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 480915b953..f8197a53e6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -51,7 +51,7 @@ gbrain config set fences.repair.llm false # keep table rows away from the mo
- `src/core/repair/fences.ts`: the `fences` repair kind (preview-bound, `spends: 'llm'`). Candidates come from the fence census after a bounded scan (`GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s); `--only`, `--skip` and `--slug` also reach files and pages the census has not judged yet. A candidate whose source is owned by another host (`owner_unavailable`) or mid-sync (`sync_in_progress`) is skipped, and every candidate is re-read before any fix runs.
- Holder names (`src/core/fence-repair/repair-tiers.ts`) resolve strictly, without same-name guessing, only to `people/` and `companies/` pages, and never to a private page from a world-visible one. A model repair claims the attempt memo, checks the per-page cap and the run's allowance, reserves on the daily ledger before each call and settles the real tokens after; a rewrite the checks rejected, or a HOLD (`llm_declined`), is never paid for again for unchanged bytes. The call (`src/core/fence-repair/llm.ts`, prompt version 2) uses no tools, no fallback model and no temperature; its output ceiling adds 2,048 tokens for a model whose reasoning the call cannot turn off, and the estimate uses the ceiling the gateway sends. It gets one corrective re-ask only when the answer does not parse or changes the row count; any other gate rejection is final. A headerless table of 14-cell rows is sent with the wide header.
- The model default (`src/core/fence-repair/model.ts`, `measured.ts`): `models.fence_repair` when set; else the first of the measured models (`openai:gpt-6.1-sol`, `anthropic:claude-opus-5-5`, `anthropic:claude-fable-5-1`; the models that met the eval's bar on its round 1 fixtures and its held-out set) whose provider key the brain has; else none (`no_measured_model`, a paid hold whose fix sets `models.fence_repair`). `openai:gpt-6.1-sol` joins the price table at $2/$10 per million tokens and stays out of OpenAI tier-default discovery. `fences.repair.max_usd_per_page` defaults to $0.30 (was $0.05), the largest worst-case page estimate of the measured models on the eval's fixtures being $0.27.
-- Tier 1 `stray_empty_cell` (`src/core/fence-repair/stray-cells.ts`) removes empty cells from a row with too many only when exactly one removal makes every checked column valid. `extra_cells` is now manual, and a facts `kind_map` reads only a kind word (at most three words, no sentence punctuation, link or strikethrough); anything else is `claim_split`, manual. `FENCE_RULES_VERSION` is 2, so older holds are screened again.
+- Tier 1 `stray_empty_cell` (`src/core/fence-repair/stray-cells.ts`) removes empty cells from a row with too many only when exactly one removal makes every checked column valid. `extra_cells` is now manual, and a facts `kind_map` reads only a kind word (at most three words, no sentence punctuation, link or strikethrough); anything else is `claim_split`, manual. A fence with no header gets the same checks for every row that starts with a row number, read by position, so a cut claim there is held instead of sent to the model. `FENCE_RULES_VERSION` is 2, so older holds are screened again.
- Every rewrite passes the same validation gates as the inline repair, plus a fixed-point check, before it is written. A misaligned cell whose text is unchanged is now moved to the column it belongs to rather than rejected.
- Write-back (`src/core/fence-repair/repair-io.ts`): managed sources go through `managed_file_repair` with a location-only `fence_repair` receipt checked at submission and again when prepared (remote callers are refused); other checkouts are confined, re-hashed (`changed_since_read`), backed up, written and imported, with the backup restored if the import refuses; database-only pages and mirrors get a revision-bound write.
- Repair kinds can carry a per-item model cost (the preview estimate follows `--limit`, and an apply stops before an item it cannot afford), a deadline and an early stop. `--expect` works for every preview-bound kind; `--max-usd` only for kinds that call a paid model, and only lowers the cap.
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index eba4f0ef3e..ad2abf6b53 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -13,7 +13,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `src/core/fence-repair/hold-fix.ts` — #6188 (D16, D17, E35, Codex CEO #7) what an `invalid_fence` sync hold tells an agent. `readFenceAutoRepair` (two reads: `fences.repair.enabled`, `fences.repair.llm` and `autopilot.last_global_at` from `config`, plus the last completed `autopilot-global-maintenance` job) says whether the maintenance run repairs fences by itself (active within `FENCE_MAINTENANCE_ACTIVE_MS`, 24 h). `fenceHoldStatus` derives the state from the reason table and `meta.fence_repair`: `auto` (no action needed, the read-only preview), `apply` (preview, then apply), `manual` (manual-only reason, gate rejection or a model failure the run does not retry: the preview names the edit, then the sync), `paid` (`budget_exhausted`, `llm_disabled`, `no_pricing`: the exact config or `pricing set` command with consent `paid`), `owner` (the owner-host command, actor `host_admin`). `fenceHoldFix` is the local fix (`gbrain repair fences --source <id> --only <path>`), `fenceHoldRelay` the remote one (`tell_user_to_run`, no path), `fenceHoldLocation` the D16 object, `fenceFileLine` the file line of a section line. Location only. Tests: `test/fence-hold-surfaces.test.ts`, `test/sync-hold-surfaces.test.ts`.
- `src/core/fence-repair/{census,census-store}.ts` — #6188 the fence census: discovery only, nothing repairs. `runFenceCensus(engine, { sourceIds, deadline, now })` advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill over `pages.id`, then incremental passes over `updated_at >= watermark`, where each new watermark is the previous pass's start minus the oldest open writer transaction in `pg_stat_activity` and `LATE_COMMIT_GRACE_MS`, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk of `isFrontmatterScannablePath` files via `collectGitVisibleFiles`/`walkDir`, then only `git diff <walked commit>` files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the census `partial`. `judgeFences` runs the coordinated `fenceStep` (normalization on): `deterministic` when Tier 1 fixes it, else the highest `FENCE_REASONS` tier of its residual reasons (`reasonTier`; manual-only or page-dependent counts as manual). `listFenceCandidates` dedupes by page slug across `invalid_fence` holds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/`updated_at`/`content_hash`, file sha256/mtime, hold `upstream_version`); `summarizeFenceCensus` counts per source by bucket and tier with the oldest hold and scan state. `census-store.ts`: `op_checkpoints` rows `fence-candidate` (one per source incarnation and slug, `page`/`file` parts), `fence-scan` (cursors and last census) and `fence-trend` (one row per sync run, keyed by run id: a managed run's total is rewritten in the same transaction as each cursor step that changes it, so the trend never differs from the cursor, and a legacy run writes its total when it ends; plus one row per normalized page write via `recordPublicationFenceTrend`, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests: `test/fence-census.test.ts` (+ `test/e2e/fence-census-postgres.test.ts`), `test/doctor-fence-integrity.test.ts`.
- `src/core/fence-repair/{llm,repair-tiers}.ts` — #6188 Tier 2 and Tier 3 for one candidate. `analyzeFences`: Tier 1 (`safeNormalizeFences`, stored rows loaded only for `renumber`), Tier 2 (`resolveStrictEntityReference` without the same-name arm per `holder_unresolved` cell, only `people/`/`companies/` slugs, private pages excluded on a world page; hits feed `verifiedHolders`), then `proposal` (validated by gates (a)-(g) and a fixed point), `llm` (only `TIER3_REASONS` residuals left; a fence with stray text lines or no end marker is not eligible) or `manual`. `llm.ts`: `tier3Requests` (per fence: the header line and the residual rows, every row for a fence-level issue), `buildTier3Prompt` (schema, vocabulary, reason codes, page visibility, and rule 8: answer `HOLD` when a row has more than one reasonable reading; pinned by a prompt-bytes digest and `FENCE_REPAIR_PROMPT_VERSION`, 2), the layout (wide when the header names a wide column or, headerless, a row as written is wider than the narrow layout), `tier3TokenBudget` (the table's size plus `TIER3_REASONING_TOKENS` for a model whose reasoning the call cannot switch off, raised to the gateway's thinking headroom where the route has no switch: the estimate reserves what the gateway sends), `callTier3` (gateway `chat`, no tools, no fallback, thinking off; `llm_unavailable` when the provider throws, `llm_refused`, `llm_truncated` for any stop but a normal end, `llm_declined` for HOLD, `llm_malformed`/`llm_empty` from `extractSingleTable`, a wrong row count is a gate (e) failure), `spliceTier3` (rebuilds only that fence: canonical header, then every row in order with the sent rows replaced). `runTier3` claims the attempt (a rejected memo returns its verdict), checks the per-page cap and the run allowance, reserves on the daily ledger before each call (a refusal stops the run), settles actual tokens (an answerless call at its estimate), normalizes and validates the spliced page against the bytes as read, and re-asks once with the failed gate letter and rows only after a structural failure (gate (a) or (e)); any other gate or a HOLD is final and consumes the memo. `TIER3_REASONS` is the reason table's screen reasons of tier `llm`. Tests: `test/fence-repair-llm.test.ts`, `test/repair-fences.test.ts`.
-- `src/core/fence-repair/stray-cells.ts` — #6188 Tier 1 `stray_empty_cell` (`strayCellPass`, run by `normalizeFences` after the structural pass): in a balanced primary fence with a canonical header, a row with more cells than the layout loses empty cells (slot removed, every other byte kept) only when exactly one distinct deletion leaves every validated column valid; otherwise it stays `extra_cells`, now manual. `rules.ts` `kindWord` keeps facts `kind_map` to a kind word (at most three words, no sentence punctuation, link or strikethrough); other text is `claim_split` (manual), never a kind note. Tests: `test/fence-repair-normalize.test.ts`.
+- `src/core/fence-repair/stray-cells.ts` — #6188 Tier 1 `stray_empty_cell` (`strayCellPass`, run by `normalizeFences` after the structural pass): in a balanced primary fence with a canonical header, a row with more cells than the layout loses empty cells (slot removed, every other byte kept) only when exactly one distinct deletion leaves every validated column valid; otherwise it stays `extra_cells`, now manual. In a fence with no header, `headerlessMisfit` reads a row that starts with a row number by position: a `kind` cell that is not a kind word is `claim_split`, a row wider than any layout with an invalid validated column is `extra_cells` (after the same empty-cell removal), and `content.ts` holds both as manual, so a claim an unescaped `|` cut never reaches Tier 3. `rules.ts` `kindWord` keeps facts `kind_map` to a kind word (at most three words, no sentence punctuation, link or strikethrough); other text is `claim_split` (manual), never a kind note. Tests: `test/fence-repair-normalize.test.ts`.
- `src/core/fence-repair/{measured,model}.ts` — #6188 the Tier 3 eval's verdicts and the model they pick. `measured.ts`: `FENCE_REPAIR_MEASURED_MODELS` (the models that met the preregistered rule, best first) and `FENCE_REPAIR_MEASURED` (the behavior notice's accuracy sentence), updated together by the next eval. `model.ts`: `resolveFenceRepairModel(WithSource)`: an explicit `models.fence_repair` always (any model, priced or not); unset, the first measured model whose provider key the merged env has; else null (`no_measured_model`, a paid hold whose fix is `gbrain config set models.fence_repair <model>`). `gbrain models` reports the row through it (`measured default`). Tests: `test/repair-fences.test.ts`.
- `src/core/fence-repair/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource`: managed owner root (or `ownerElsewhere`), legacy checkout, mirror flag, unfinished managed sync cursor and the paths/slugs pending writes name. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `git add`/`git commit` step, dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.
- `src/core/fence-repair/attempts.ts` — #6188 attempt claims and the attempt memo for paid (Tier 3) fence repairs, one `op_checkpoints` row per candidate (op `fence-repair-attempt`) changed only by compare-and-swap on a record version: `claimed` → `dispatched` → `settled` → `published` | `rejected` | `transient`, at most one paid call plus one corrective re-ask per claim. A rejected or published memo (content sha256, model, fence rules version, prompt version) is not claimed again until one changes; transient failures do not consume it; an expired lease is taken over (a stale dispatch counts a crash, two reject the memo). Records carry location and reason codes and their source incarnation, so the purge keeps them while it lives. Tests: `test/fence-repair-attempts.test.ts` (+ Postgres e2e).
diff --git a/docs/guides/fence-format.md b/docs/guides/fence-format.md
index 162e858445..d02176877b 100644
--- a/docs/guides/fence-format.md
+++ b/docs/guides/fence-format.md
@@ -170,7 +170,7 @@ These rules run on every write path for free. They edit or move cell text and ne
| --- | --- |
| `close_fence` | A fence with no end marker gets one directly after its table, when nothing but blank lines follows the last row up to the end of the section. |
| `marker_form` | Two-dash takes markers (`<!-- gbrain:takes:begin -->`) directly above a takes table become the three-dash markers. Two-dash facts markers are not a fence and are left alone. |
-| `stray_empty_cell` | A row with more cells than its header loses empty cells, only when exactly one choice of empty cells to remove leaves every checked column (`#`, kind, confidence, visibility, notability, `claim_value`; takes kind, holder, weight) valid. Otherwise the row is `extra_cells` and a person fixes it. |
+| `stray_empty_cell` | A row with more cells than its header (with no header: than the narrow layout, or 14 facts cells) loses empty cells, only when exactly one choice of empty cells to remove leaves every checked column (`#`, kind, confidence, visibility, notability, `claim_value`; takes kind, holder, weight) valid. Otherwise the row is `extra_cells` and a person fixes it. |
| `renumber` | A row number that is zero, negative, not a number or a duplicate gets a new number (see [row numbers](#row-numbers)). |
| `column_default` | A required facts column missing from the whole header gets its write default: `confidence` `1.0`, `notability` `medium`, `visibility` `private`. Takes have no defaults; a takes fence with no weight is `weight_missing`. |
| `header_alias` | A header whose every column has a known spelling (see [header spellings](#header-spellings)) becomes the canonical header, and each row's cells move into canonical order unchanged. |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 404b835b27..953fc98dbf 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -294,8 +294,8 @@ clears or retries it with no one acting.
| <a id="fence-no_header"></a>`no_header` | The fence has table rows but no header row naming `claim` and `kind`. | `llm` | yes | Repaired by the next maintenance run. By hand: add the canonical header as the first table line. Format: [markers](fence-format.md#markers). |
| <a id="fence-row_before_header"></a>`row_before_header` | Rows sit above the header row. | `llm` | yes | Repaired by the next maintenance run. By hand: move them below the header. Format: [markers](fence-format.md#markers). |
| <a id="fence-short_row"></a>`short_row` | A row is missing a cell in the middle, so its columns are ambiguous. A row short only in its optional trailing cells parses. | `llm` | yes | Repaired by the next maintenance run. By hand: add the missing cells so every column lines up. Format: [facts](fence-format.md#facts-layouts), [takes](fence-format.md#takes-layouts). |
-| <a id="fence-extra_cells"></a>`extra_cells` | A row has more cells than the header, and removing empty cells does not line it up (stray empty cells with one valid removal are rewritten by themselves). Often an unescaped `\|` cut a cell, usually the claim, in two; no gate can tell that from a misplaced cell, so it is never sent to the model. | `manual` | no | Join the cut cell with `\|`, or remove the extra cell. Format: [facts](fence-format.md#facts-layouts), [takes](fence-format.md#takes-layouts). |
-| <a id="fence-claim_split"></a>`claim_split` | A facts `kind` cell holds text, not a kind word (more than three words, sentence punctuation, a link or strikethrough): usually the end of a claim an unescaped `\|` cut in two, with the kind cell missing. gbrain does not store it as a kind note. | `manual` | no | Join the text back into the claim with `\|` and write the kind. Format: [facts](fence-format.md#facts-columns). |
+| <a id="fence-extra_cells"></a>`extra_cells` | A row has more cells than the header, and removing empty cells does not line it up (stray empty cells with one valid removal are rewritten by themselves). Often an unescaped `\|` cut a cell, usually the claim, in two; no gate can tell that from a misplaced cell, so it is never sent to the model. In a fence with no header, a row that starts with a row number is read by position the same way. | `manual` | no | Join the cut cell with `\|`, or remove the extra cell. Format: [facts](fence-format.md#facts-layouts), [takes](fence-format.md#takes-layouts). |
+| <a id="fence-claim_split"></a>`claim_split` | A facts `kind` cell holds text, not a kind word (more than three words, sentence punctuation, a link or strikethrough): usually the end of a claim an unescaped `\|` cut in two, with the kind cell missing. gbrain does not store it as a kind note. In a fence with no header, a row that starts with a row number is read by position, so its third cell is the kind. | `manual` | no | Join the text back into the claim with `\|` and write the kind. Format: [facts](fence-format.md#facts-columns). |
| <a id="fence-holder_unresolved"></a>`holder_unresolved` | A takes `who` cell is not `world`, `brain`, `people/<slug>` or `companies/<slug>` (for example a person's display name). | `resolver` | yes | Rewritten by the next maintenance run when it resolves to exactly one verified `people/` or `companies/` page (never a private page on a world-visible page). Otherwise write one of those forms by hand. Format: [holders](fence-format.md#holders). |
| <a id="fence-missing_begin"></a>`missing_begin` | An end marker has no begin marker before it. | `manual` | no | Add the begin marker above the table, or delete the stray end marker. Format: [markers](fence-format.md#markers). |
| <a id="fence-split_rows"></a>`split_rows` | A fence has no end marker and its rows are split by blank lines or text, so gbrain cannot tell which rows belong to it. | `manual` | no | Join the rows into one table and add the end marker after the last row. Format: [markers](fence-format.md#markers). |
diff --git a/evals/fence-repair-tier3/oracle.ts b/evals/fence-repair-tier3/oracle.ts
index bdd6ec57bb..c98056cfb6 100644
--- a/evals/fence-repair-tier3/oracle.ts
+++ b/evals/fence-repair-tier3/oracle.ts
@@ -43,14 +43,15 @@ const REASON_OF: Record<string, string | null> = {
* model call: extra cells that removing empty cells cannot line up (a
* misplaced text cell, a duplicated value, or a claim cut by an unescaped
* pipe), held as `extra_cells`, and a sentence in the facts `kind` column,
- * held as `claim_split`. Round 1 ids, then the held-out set's (`h-`).
+ * held as `claim_split`; in a fence with no header the same rows are read by
+ * position from their row number. Round 1 ids, then the held-out set's (`h-`).
*/
export const FREE_TIER_PATH: Readonly<Record<string, 'tier1' | 'manual'>> = {
'f-ex-01': 'tier1', 'f-ex-02': 'tier1', 'f-ex-03': 'tier1', 'f-ex-04': 'tier1', 'f-ex-06': 'tier1', 'f-ex-07': 'tier1',
't-ex-01': 'tier1', 't-ex-02': 'tier1', 't-ex-03': 'tier1', 't-ex-04': 'tier1',
'f-ex-05': 'manual', 'f-adv-01': 'manual', 'f-adv-02': 'manual', 'f-adv-03': 'manual', 'f-adv-04': 'manual', 't-adv-01': 'manual', 'f-gl-02': 'manual',
'h-f-ex-01': 'tier1', 'h-f-ex-02': 'tier1', 'h-f-ex-03': 'tier1', 'h-f-ex-04': 'tier1', 'h-t-ex-01': 'tier1', 'h-t-ex-02': 'tier1',
- 'h-f-ex-05': 'manual', 'h-adv-01': 'manual', 'h-adv-02': 'manual', 'h-spl-01': 'manual', 'h-spl-02': 'manual', 'h-spl-03': 'manual',
+ 'h-f-ex-05': 'manual', 'h-adv-01': 'manual', 'h-adv-02': 'manual', 'h-spl-01': 'manual', 'h-spl-02': 'manual', 'h-spl-03': 'manual', 'h-spl-04': 'manual',
};
export type AnswerFn = (f: Fixture, req: Tier3Request, variant: 'as_written' | 'blank_numbers') => string;
diff --git a/scripts/build-fence-format.ts b/scripts/build-fence-format.ts
index f038077a3f..10ee266286 100644
--- a/scripts/build-fence-format.ts
+++ b/scripts/build-fence-format.ts
@@ -187,7 +187,7 @@ function normalizedTable(): string {
const text = {
close_fence: 'A fence with no end marker gets one directly after its table, when nothing but blank lines follows the last row up to the end of the section.',
marker_form: 'Two-dash takes markers (`<!-- gbrain:takes:begin -->`) directly above a takes table become the three-dash markers. Two-dash facts markers are not a fence and are left alone.',
- stray_empty_cell: 'A row with more cells than its header loses empty cells, only when exactly one choice of empty cells to remove leaves every checked column (`#`, kind, confidence, visibility, notability, `claim_value`; takes kind, holder, weight) valid. Otherwise the row is `extra_cells` and a person fixes it.',
+ stray_empty_cell: 'A row with more cells than its header (with no header: than the narrow layout, or 14 facts cells) loses empty cells, only when exactly one choice of empty cells to remove leaves every checked column (`#`, kind, confidence, visibility, notability, `claim_value`; takes kind, holder, weight) valid. Otherwise the row is `extra_cells` and a person fixes it.',
renumber: 'A row number that is zero, negative, not a number or a duplicate gets a new number (see [row numbers](#row-numbers)).',
column_default: `A required facts column missing from the whole header gets its write default: ${Object.entries(COLUMN_DEFAULTS.facts).map(([c, v]) => `${code(c)} ${code(v)}`).join(', ')}. Takes have no defaults; a takes fence with no weight is \`weight_missing\`.`,
header_alias: 'A header whose every column has a known spelling (see [header spellings](#header-spellings)) becomes the canonical header, and each row\'s cells move into canonical order unchanged.',
diff --git a/src/core/fence-repair/content.ts b/src/core/fence-repair/content.ts
index d55725c953..48cd10066e 100644
--- a/src/core/fence-repair/content.ts
+++ b/src/core/fence-repair/content.ts
@@ -16,7 +16,8 @@ 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 { ALLOWED, BASE_WIDTH, canonicalColumn, CANONICAL_HEADER, collapse, COLUMN_DEFAULTS, COLUMNS, supersededRef } from './schema.ts';
+import { headerlessMisfit } from './stray-cells.ts';
import { applyEdits, fenceBlocked, type Edit } from './structure.ts';
import type { FenceCtx, FenceFix, FenceIssue, FenceKind, FenceReason, FenceSection } from './types.ts';
@@ -91,7 +92,7 @@ function planSection(pass: Pass, raw: RawSection): void {
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)));
+ if (balanced) pass.residual.push(...fence.issues.filter(i => REPORTED.has(i.reason)), ...headerlessIssues(fence));
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));
@@ -100,6 +101,15 @@ function planSection(pass: Pass, raw: RawSection): void {
}
}
+/** Rows of a fence with no header that cannot be read by position (stray-cells.ts), held as manual. */
+function headerlessIssues(fence: RawFence): FenceIssue[] {
+ return fence.rows.flatMap(row => {
+ const misfit = headerlessMisfit(fence, row);
+ if (!misfit) return [];
+ return [misfit === 'claim_split' ? issueAt(fence, misfit, row.line, rowNumOf(fence, row), 'kind', ALLOWED[fence.kind].kind) : issueAt(fence, misfit, row.line, rowNumOf(fence, row))];
+ });
+}
+
/** A balanced fence the content rules may edit; reports why not otherwise. */
function fenceWorkable(pass: Pass, fence: RawFence): boolean {
if (!fence.header) return false;
diff --git a/src/core/fence-repair/stray-cells.ts b/src/core/fence-repair/stray-cells.ts
index e285608aee..2bd929a499 100644
--- a/src/core/fence-repair/stray-cells.ts
+++ b/src/core/fence-repair/stray-cells.ts
@@ -8,10 +8,20 @@
* a claim cut in two by an unescaped `|` from a misplaced cell.
*
* Only rows read by position qualify: a balanced primary fence whose header
- * is the canonical layout. Each deletion removes the empty cell's slot
- * (its leading pipe and whitespace), so every other byte of the row stays.
+ * is the canonical layout, or a fence with no header at all. Each deletion
+ * removes the empty cell's slot (its leading pipe and whitespace), so every
+ * other byte of the row stays.
+ *
+ * With no header nothing marks a row's shape, so `headerlessMisfit` reads a
+ * row that starts with a row number positionally: a `kind` cell holding text
+ * that is not a kind word is `claim_split`, and a row wider than any layout
+ * (facts 10 or 14 cells, takes 7) with a validated column invalid is
+ * `extra_cells`. Unless this rule lines it up, the content pass holds it as
+ * manual, so a claim an unescaped `|` cut in two never reaches the model
+ * (gate (b) would compare against the cut claim).
*/
import { extractRawRows, rowNumOf, type RawCell, type RawFence, type RawRow } from './raw-rows.ts';
+import { kindWord } from './rules.ts';
import { BASE_WIDTH, cellValid, COLUMNS } from './schema.ts';
import { applyEdits, fenceBlocked, type Edit } from './structure.ts';
import type { FenceFix, FenceKind, FenceSection } from './types.ts';
@@ -24,9 +34,9 @@ export function strayCellPass(text: string, section: FenceSection): { text: stri
const edits: Edit[] = [];
const fixes: FenceFix[] = [];
for (const fence of raw.fences) {
- if (!fence.primary || !fence.end || fence.begin.nearMiss || fence.end.nearMiss || !fence.header || fence.needsRewrite || fenceBlocked(raw, fence)) continue;
+ if (!fence.primary || !fence.end || fence.begin.nearMiss || fence.end.nearMiss || fence.needsRewrite || fenceBlocked(raw, fence)) continue;
for (const row of fence.rows) {
- if (row.beforeHeader || row.shape !== 'extra_cells') continue;
+ if (fence.header ? row.beforeHeader || row.shape !== 'extra_cells' : !headerlessMisfit(fence, row)) continue;
const removed = uniqueDeletion(fence, row);
if (!removed) continue;
edits.push(...removed.map(cell => slotOf(text, row, cell)));
@@ -36,12 +46,35 @@ export function strayCellPass(text: string, section: FenceSection): { text: stri
return { text: edits.length ? applyEdits(text, edits) : text, fixes };
}
-/** The empty cells to delete, when exactly one distinct result makes every validated column valid. */
-function uniqueDeletion(fence: RawFence, row: RawRow): RawCell[] | null {
+/**
+ * Why a row of a fence with no header cannot be read by position, or null:
+ * only for a row that starts with a row number (the one anchor a headerless
+ * row has).
+ */
+export function headerlessMisfit(fence: RawFence, row: RawRow): 'claim_split' | 'extra_cells' | null {
const kind = fence.kind;
+ if (fence.header || !cellValid(kind, '#', row.cells[0]?.text ?? '')) return null;
+ const kindCell = row.cells[2]?.text.trim() ?? '';
+ if (kindCell && !cellValid(kind, 'kind', kindCell) && !kindWord(kindCell)) return 'claim_split';
+ const n = row.cells.length;
+ const fits = kind === 'facts' ? n <= BASE_WIDTH.facts || n === COLUMNS.facts.length : n <= BASE_WIDTH.takes;
+ return fits || row.cells.every((cell, j) => columnValid(fence, kind, j, cell.text)) ? null : 'extra_cells';
+}
+
+/** The widths a row may be cut back to: the header's layout, or with no header the narrow layout (facts 14 for a wider row). */
+function layoutWidths(fence: RawFence, row: RawRow): Set<number> {
+ const kind = fence.kind;
+ if (!fence.header) return new Set([kind === 'facts' && row.cells.length > COLUMNS.facts.length ? COLUMNS.facts.length : BASE_WIDTH[kind]]);
const headerLen = fence.columns.length;
const widths = new Set([Math.max(headerLen, BASE_WIDTH[kind])]);
if (kind === 'facts' && headerLen < COLUMNS.facts.length && row.cells.length > COLUMNS.facts.length) widths.add(COLUMNS.facts.length);
+ return widths;
+}
+
+/** The empty cells to delete, when exactly one distinct result makes every validated column valid. */
+function uniqueDeletion(fence: RawFence, row: RawRow): RawCell[] | null {
+ const kind = fence.kind;
+ const widths = layoutWidths(fence, row);
const empty = row.cells.flatMap((cell, i) => (cell.raw ? [] : [i]));
const valid = new Map<string, number[]>();
for (const width of widths) {
@@ -61,7 +94,7 @@ function uniqueDeletion(fence: RawFence, row: RawRow): RawCell[] | null {
/** The cell at index `j` passes its column's strict check (a cell with no column, or a free-text one, passes). */
function columnValid(fence: RawFence, kind: FenceKind, j: number, text: string): boolean {
- const column = kind === 'takes' && j >= BASE_WIDTH.takes ? fence.columns[j] ?? null : COLUMNS[kind][j] ?? null;
+ const column = kind === 'takes' && j >= BASE_WIDTH.takes ? (fence.header ? fence.columns[j] ?? null : null) : COLUMNS[kind][j] ?? null;
return column === null || cellValid(kind, column, text);
}
diff --git a/test/fence-repair-llm.test.ts b/test/fence-repair-llm.test.ts
index fb3128557e..91e99777cc 100644
--- a/test/fence-repair-llm.test.ts
+++ b/test/fence-repair-llm.test.ts
@@ -226,6 +226,13 @@ describe('runTier3: the re-ask and the decline', () => {
expect(out.ok).toBe(true);
});
+ test('a headerless row whose claim an unescaped pipe cut in two is held before any model call', async () => {
+ const page = { compiled_truth: `${FB}\n| 1 | Headerlesszq9 revenue grew | mostly from enterprise renewals, per the memo | fact | 0.9 | private | high | 2026-06-30 | | memo | |\n${FBE}\n`, timeline: '' };
+ const target = { mode: 'db', sourceId: 'default', key: 't3/split', slug: 't3/split', path: null, sourcePath: null, page, content: null, before: pageSha(page), snapshot: null, hold: null,
+ ctx: { pageVisibility: 'private' } } as FenceTarget;
+ expect(await analyzeFences(engine, target, { pageId: null })).toMatchObject({ status: 'manual', reason: 'claim_split' });
+ });
+
test('HOLD is held as llm_declined and consumes the memo: the same bytes are never sent again', async () => {
const first = await attempt('t3/hold', [result('HOLD')]);
expect(first.calls).toHaveLength(1);
diff --git a/test/fence-repair-normalize.test.ts b/test/fence-repair-normalize.test.ts
index 3ca11ebb1f..52fab66c57 100644
--- a/test/fence-repair-normalize.test.ts
+++ b/test/fence-repair-normalize.test.ts
@@ -484,3 +484,28 @@ describe('stray empty cells and split claims (#6188 T4)', () => {
expectRepaired(phrase);
});
});
+
+describe('fences with no header: rows read by their row number (#6188 T4)', () => {
+ const headerless = (...rows: string[]) => ['## Facts', '', FB, ...rows, FE, ''].join('\n');
+
+ test('a claim an unescaped pipe cut in two is held manual, never sent to the model; the row is untouched', () => {
+ const sentence = '| 4 | Synthco revenue grew 40% | mostly from enterprise renewals | fact | 0.9 | private | high | 2026-06-30 | | Q2 memo | |';
+ const short = '| 5 | Synthco churn fell | in Q3 | fact | 0.8 | private | medium | 2026-07-01 | | dashboard | |';
+ for (const [row, reason] of [[sentence, 'claim_split'], [short, 'extra_cells']] as const) {
+ const r = run(headerless(factsRow(1, 'Synthco anchor row'), row));
+ expect(reasons(r)).toEqual([reason, 'no_header'].sort() as FenceReason[]);
+ expect(r.fixes).toEqual([]);
+ expect(r.page.compiled_truth).toContain(row);
+ expect(FENCE_REASONS[reason].manualOnly).toBe(true);
+ }
+ });
+
+ test('a stray empty cell is still removed; aligned rows, and rows with no row number to anchor them, stay plain no_header', () => {
+ const r = run(headerless('| 6 | Synthco opened a lab | | event | 0.7 | private | low | 2026-05-01 | | site visit | |'));
+ expect(classes(r)).toEqual(['stray_empty_cell']);
+ expect(reasons(r)).toEqual(['no_header']);
+ expect(r.page.compiled_truth).toContain('| 6 | Synthco opened a lab | event | 0.7 | private | low | 2026-05-01 | | site visit | |');
+ expect(reasons(run(headerless(factsRow(1, 'Synthco aligned row'), '| 2 | Synthco short row | idea | 0.4 | private | low |')))).toEqual(['no_header']);
+ expect(reasons(run(headerless('| Synthco unnumbered row | event | 0.8 | private | low | 2026-02-01 | | press note | |')))).toEqual(['no_header']);
+ });
+});