Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(fence-repair): merge_fences Tier 1 rule, validator mapping and receipt (#6377 lane A1)
garrytand7cb01c7800e
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex ffd5299446..13b7620efb 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -9,15 +9,15 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/fence-repair/refusal.ts` — #6188 the one fence check coordinated writers share. `scanCanonicalFences` decides from the strict parsers what the canonical projection refuses (a repeated marker outside code, any parser warning, a row number used twice on the page) and locates each defect from the raw-row view (`raw-rows.ts`, `schema.ts`), never from parser warning strings, which embed row text; reasons and messages come from `reasons.ts` (`FENCE_REASONS`, `fenceMessage`, `issueLocation`). `fenceOperationError` is the typed refusal (`invalid_fence`, wire `invalid_params`, or `take_row_collision` for a stored-row collision). `fenceFailureDetail` is the bounded, versioned `error_detail.fence` a failed receipt keeps through compaction; `fenceReceiptLocation` reads a receipt back from that detail, the message grammar or an older release's exact message, and never from an arbitrary `invalid_params`. `completeFenceLocation` names the section of a legacy receipt from the refused bytes. Tests: `test/fence-refusal.test.ts`, `test/fence-hold-surfaces.test.ts`, `test/persistence-sync-fence-holds.test.ts` (PGLite and Postgres).- `src/core/fence-repair/{types,schema,raw-rows,reasons}.ts` — #6188 the shared fence vocabulary, all location-only. `types.ts`: `FenceIssue`, `FenceFix`, `FenceCtx`, `FenceReason`, `FixClass`. `schema.ts`: canonical columns, accepted widths (facts 9/10/14, takes 6/7/13), header aliases, enum and kind synonym tables (exported for the format reference), cell validity. `raw-rows.ts`: `extractRawRows` reads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row is `accepted` exactly when the strict parser returns it. `reasons.ts`: `FENCE_REASONS` (tier, auto-retry, actor, fix template, docs anchor per reason; the registry's `invalid_fence.reasons`; templates a repair can clear name the read-only `gbrain repair fences` preview) and `fenceMessage`. Tests: `test/fence-repair-raw-rows.test.ts`, `test/fence-repair-reasons.test.ts`.- `scripts/build-fence-format.ts` — #6188 renders the generated region of `docs/guides/fence-format.md` (between `BEGIN/END GENERATED fence-format`) from the fence constants: markers, the column tables and layouts from `schema.ts` (`COLUMNS`, `BASE_WIDTH`, `MIN_CELLS`, `CANONICAL_HEADER`, `ALLOWED`, `COLUMN_DEFAULTS`, `NAMED_COLUMNS`, `TOLERATED_TRAILING`, `HEADER_ALIASES`), holder outcomes computed with `isValidHolder`/`holderAlias`, the Tier 1 rule table from the synonym tables (bound to `FixClass` by `satisfies`), screen reasons grouped by tier and the gate table from `reasons.ts`. It parses both synthetic examples with the strict parsers and throws on any warning. `--check` exits 1 when the committed region is stale. Drift test: `test/fence-format-reference.test.ts` (the region, the examples, the reference's links, and one `fence-<reason>` row per reason in `write-refusals.md` with the reason table's tier and auto-retry and a link into the reference).-- `src/core/fence-repair/{normalize,structure,content,rules}.ts` — #6188 Tier 1. `normalizeFences(page, ctx)` returns a page that compiles plus location-only fixes and residual issues; a page whose fences compile comes back as the same object, and only edited cells, markers and headers change (no table is re-rendered). `structure.ts` closes a fence only when nothing but blank lines follows its last row and fixes two-dash takes markers; `content.ts` rewrites headers into canonical order with header-level defaults and renumbers prior-aware across both sections (`nextFreeRowNum`: above every fence and stored number; hidden rows never move); `rules.ts` holds the cell rules (kind map with the original word kept in `context`, enum and holder synonyms, percent confidence). `safeNormalizeFences` turns a throw into residual `normalizer_failed`. Tests: `test/fence-repair-normalize.test.ts`, `test/fence-repair-fixtures.test.ts`.-- `src/core/fence-repair/{validate,validate-cells,page-checks}.ts` — #6188 the one gate every tier's output passes before a write: (a) compiles, (e) row count and containment, (b) claims, (c) existing row numbers, (d) visibility only tightens, (f) per-row cell preservation with rule-produced changes only, (g) nothing the privacy boundary hid is shown; gates (b), (c), (e) and (f) read the raw-row view. `isFenceFixedPoint` is E14. `page-checks.ts` holds `strictFailures` (gate a, the projection's three checks) and `exposedLines` (gate g). Tests: `test/fence-repair-validate.test.ts`.+- `src/core/fence-repair/{normalize,structure,content,rules,merge}.ts` — #6188 Tier 1. `normalizeFences(page, ctx)` returns a page that compiles plus location-only fixes and residual issues; a page whose fences compile comes back as the same object, and only edited cells, markers and headers change (no table is re-rendered). `structure.ts` merges first (below), closes a fence only when nothing but blank lines follows its last row and fixes two-dash takes markers; `content.ts` rewrites headers into canonical order with header-level defaults and renumbers prior-aware across both sections (`nextFreeRowNum`: above every fence and stored number; hidden rows never move); `rules.ts` holds the cell rules (kind map with the original word kept in `context`, enum and holder synonyms, percent confidence). `merge.ts` (#6377, `merge_fences`, clears `repeated_marker`): `mergePlan(raw, kind)` admits a section's N > 1 fences of a kind only when each is balanced with no near-miss marker, every header maps to the same canonical columns in the same order, every marker stands alone on its line, no row sits above a header and nothing but table lines sits inside any fence region (exactly N begin and N end markers outside code); it maps every before row (fence index, occurrence) to a merged occurrence or marks it `duplicateOf` a kept row when every cell but `#` is byte-equal as written (`rowKey`; only later fences' rows are dropped). `mergeEdits` appends the kept later rows after the primary's last table line, removes each later fence's marker lines and table, a heading line directly above it that repeats an earlier heading of the section, and collapses the blank lines around the block to one; the edit is kept only when `exposedLines` is empty. `mergeOrigins` tells the content pass each merged row's origin fence and before line (fixes and issues are reported at before-page lines, `beforeLine`), so `renumber` resolves a merged row's `superseded by #N` to its own before fence's row N (kept, or the kept row a dropped duplicate N equalled) and rewrites the reference to that row's final number (`renumber` fix on `context`/`source`); a reference from outside a merged fence keeps today's rule (any shared number it names is `superseded_ambiguous`). `mergePlans`/`mergedReceipt` re-derive the mapping from the before page for the validator and the receipt's `merged` entries. `safeNormalizeFences` turns a throw into residual `normalizer_failed`. Tests: `test/fence-repair-normalize.test.ts`, `test/fence-repair-fixtures.test.ts`, `test/fence-repair-merge.test.ts`.+- `src/core/fence-repair/{validate,validate-cells,page-checks}.ts` — #6188 the one gate every tier's output passes before a write: (a) compiles, (e) row count and containment, (b) claims, (c) existing row numbers, (d) visibility only tightens, (f) per-row cell preservation with rule-produced changes only, (g) nothing the privacy boundary hid is shown; gates (b), (c), (e) and (f) read the raw-row view. Before rows pair with after rows by primary-fence occurrence; when `ctx.issues` carries a `merge_fences` fix for a section and kind (#6377) the pairing is the merge mapping re-derived from the before page (`mergePlans`; a named merge the before page does not admit fails (e)): (e) requires the after count to equal the kept count and each dropped row to equal its kept row as written (`rowKey`), (b), (d) and (f) run per mapped row, (c) skips dropped rows and numbers used twice across every before fence, and (f) compares a merged row that carries `superseded by #N` as if written with the after number of its own before fence's row N (`withFollowedRef`); any other reference change is a changed cell. `isFenceFixedPoint` is E14. `page-checks.ts` holds `strictFailures` (gate a, the projection's three checks) and `exposedLines` (gate g). Tests: `test/fence-repair-validate.test.ts`, `test/fence-repair-merge.test.ts`.- `src/core/fence-repair/{tier1,import-step,config,report}.ts` — #6188 Tier 1 on every write path. `fenceStep(page, ctx, { normalize })` is the step the coordinated screen, `importFromContent` and the append verbs share: no work beyond a marker substring check for a page with no fence, one shared scan when the fences compile, and `normalized` only when the validator passes and the output is a fixed point; otherwise `residual` with issues and the refusal location (`fenceIssuesWire` is the D18 `fence_issues` shape). `import-step.ts`: `applyImportFences` runs inside `importFromContent` before the remote hidden-row merge and withdrawal preservation (E7), reusing the screen's verdict unless hidden rows or a planned `renumber` need the database (stored rows load only then); `normalizeTargetFences` normalizes an append verb's target page or throws `target_fence_malformed` for a residual in its own fence kind; `normalizePageFences` serves synthesize verify. `config.ts`: `fences.normalize` (default on, read only when there is something to fix) and the model-repair caps `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00), validated at `config set` as non-negative USD (0 = no model spend) and read by `readFenceRepairCaps` (stored value = a user cap). `report.ts`: the one `fences_normalized` shape (count, by_class, writers, sample paths for local callers, coaching fix), the `fence_normalized` coaching notice and the per-file import tally (`fence_issues` for lenient imports). Tests: `test/fence-write-verbs.test.ts`, `test/persistence-sync-fence-holds.test.ts`, `test/fence-normalize-overhead.slow.test.ts`.- `src/core/fence-repair/hold-fix.ts` — #6188 (D16, D17, E35, Codex CEO #7) what an `invalid_fence` sync hold tells an agent (the OWNER list routes `owner_unavailable`, `owner_cli_required` and the #6278 owner conditions `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing` to state `owner`). `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. 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(engine, sourceId, { remote })`: managed owner root, or the `OwnerRefusal` row (`persistence/owner-refusal.ts`) that says why this host may not write it (a remote caller's row names no local path), legacy checkout, mirror flag, and the `RepairBusySet` (`persistence/repair-busy.ts`: in-flight writes plus the not-yet-admitted entries of every unfinished sync cursor, failing closed); an unfinished sync no longer marks the whole source busy. `writeFenceRepair` turns a `sync_in_progress` raised at the write's admission into `{ ok: false, reason: 'sync_in_progress' }`. `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/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource(engine, sourceId, { remote })`: managed owner root, or the `OwnerRefusal` row (`persistence/owner-refusal.ts`) that says why this host may not write it (a remote caller's row names no local path), legacy checkout, mirror flag, and the `RepairBusySet` (`persistence/repair-busy.ts`: in-flight writes plus the not-yet-admitted entries of every unfinished sync cursor, failing closed); an unfinished sync no longer marks the whole source busy. `writeFenceRepair` turns a `sync_in_progress` raised at the write's admission into `{ ok: false, reason: 'sync_in_progress' }`. `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, and for a `merge_fences` repair `merged`: per merged fence and section the fence count and every before row as `{occurrence, from_fence, kept_as | duplicate_of}`, at most `MERGED_ROWS_MAX` rows, built by `mergedReceipt`; `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).- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.diff --git a/docs/guides/fence-format.md b/docs/guides/fence-format.mdindex d02176877b..4f5bf8a393 100644--- a/docs/guides/fence-format.md+++ b/docs/guides/fence-format.md@@ -168,6 +168,7 @@ These rules run on every write path for free. They edit or move cell text and ne| Class | What it rewrites || --- | --- |+| `merge_fences` | A section with more than one fence of a kind becomes one fence when every fence has both markers, the same canonical header and nothing but table lines inside: the later fences' rows are appended to the first in document order, a later row whose cells (every column but `#`) equal a kept row's as written is dropped, a number that now collides is renumbered (see [row numbers](#row-numbers)) and a `superseded by #N` reference follows its own fence's row N, and the later markers, tables and a repeated section heading above them are removed. Anything else stays `repeated_marker` and a person merges the fences. || `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 (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. |@@ -232,7 +233,7 @@ No tier writes a fence until all of these hold, and the result is one the rules| (b) | [`claim_changed`](write-refusals.md#fence-claim_changed) | Every claim cell is unchanged (struck claims included). || (c) | [`row_number_changed`](write-refusals.md#fence-row_number_changed) | Every row number that was valid and unique still names the same claim. || (d) | [`visibility_loosened`](write-refusals.md#fence-visibility_loosened) | No row becomes more visible: `private` never turns `world`. |-| (e) | [`row_count_changed`](write-refusals.md#fence-row_count_changed) | No row is added or dropped, and every row of the fence stays inside it. |+| (e) | [`row_count_changed`](write-refusals.md#fence-row_count_changed) | No row is added or dropped, and every row of the fence stays inside it; under `merge_fences` the only rows dropped are the exact duplicates its mapping names. || (f) | [`cell_changed`](write-refusals.md#fence-cell_changed) | A cell valid in its column keeps its text; a misaligned cell may only move, and text changes only through a named rule. || (g) | [`protection_loosened`](write-refusals.md#fence-protection_loosened) | Text the privacy boundary hid before the repair stays hidden after it. |<!-- END GENERATED fence-format -->diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 64b89a67b1..1e0a0ef617 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -320,7 +320,7 @@ clears or retries it with no one acting.| <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). || <a id="fence-unclosed_trailing_content"></a>`unclosed_trailing_content` | A fence has no end marker and other text follows its table, so closing it automatically could expose text the privacy boundary hides. | `manual` | no | Add the end marker directly after the last table row, or wrap a mere mention of the marker in backticks. Format: [markers](fence-format.md#markers). || <a id="fence-marker_near_miss"></a>`marker_near_miss` | A line uses the two-dash takes marker (`<!-- gbrain:takes:begin -->`) or mentions it with no takes table after it. Two-dash markers directly above a takes table are rewritten by themselves. | `manual` | no | Use the exact three-dash markers around the takes table, or wrap a mere mention in backticks. Format: [markers](fence-format.md#markers). |-| <a id="fence-repeated_marker"></a>`repeated_marker` | A body or timeline section has a second begin or end marker for the same fence outside code. | `manual` | no | Keep one begin and one end marker per fence in that section, with every row in one table. Format: [markers](fence-format.md#markers). |+| <a id="fence-repeated_marker"></a>`repeated_marker` | A body or timeline section has a second begin or end marker for the same fence outside code. Two or more fences that each have both markers, the same canonical header and nothing but table lines inside are merged by themselves (`merge_fences`: later rows appended, exact duplicates dropped, colliding numbers renumbered, a repeated section heading removed). | `manual` | no | Give the extra fence both markers and the first fence's header and move any other text out of it, so the next write or maintenance run merges them; or merge by hand, keeping one begin and one end marker per fence in that section with every row in one table. Format: [markers](fence-format.md#markers), [what gbrain rewrites](fence-format.md#normalized). || <a id="fence-takes_in_facts"></a>`takes_in_facts` | A facts fence holds a takes table. | `manual` | no | Move the rows into a takes fence (or add them with `takes_add`), or rewrite them as facts rows. Format: [takes](fence-format.md#takes-columns). || <a id="fence-superseded_ambiguous"></a>`superseded_ambiguous` | Two rows share a number and a `superseded by #N` reference names that number, so renumbering could repoint the reference. | `manual` | no | Decide which row keeps the number, give the other a number above every number on the page, and fix the reference. Format: [row numbers](fence-format.md#row-numbers). || <a id="fence-enum_unmapped"></a>`enum_unmapped` | A facts `kind`, `visibility` or `notability` cell holds a value outside the allowed list and its synonyms (the message names the column and the allowed values). | `manual` | no | Use one of the allowed values. Format: [facts](fence-format.md#facts-columns). |diff --git a/docs/plans/2026-10-09-001-fix-content-repair-lane-6377-plan.md b/docs/plans/2026-10-09-001-fix-content-repair-lane-6377-plan.mdnew file mode 100644index 0000000000..958bb9fbf6--- /dev/null+++ b/docs/plans/2026-10-09-001-fix-content-repair-lane-6377-plan.md@@ -0,0 +1,122 @@+## Implementation plan+# Content-repair lane (#6377): sync holds clear themselves, a frontier model decides the cases that need judgment++Thread: GBRA-72. Issue: #6377. Builds on #5988 (holds), #6188 (fence repair tiers, gates, caps, maintenance phase), #6340/#6347 (`sync status` / `sync unblock`, the class / safe_actions / needs_human triple). One PR to `garrytan/gbrain`, version stamped at the merge slot (master + 1 PATCH; no migration expected). Paired gbrain-evals PR for the model-tier eval. Reviewed by /autoplan (CEO, DX, Eng; Codex gpt-6-astra outside voice, 13 findings; record in section 8).++## 0. Why now++Holding instead of failing (#5988, #6188, #6347) was the first half. The second half is still a person: every content hold ends with "gbrain will not guess this repair" and a `fix` that sends an operator to edit a file. On Garry's brain on 2026-10-09 five holds (`invalid_fence` ×2, `frontmatter_slug_conflict` ×3) sat 16 hours until an external agent fixed them by hand; the week before, the same brain needed 198 frontmatter repairs, 471 glued-fence repairs and 146 fence-adoption retries from an external agent writing ad-hoc scripts against gbrain's error messages. Four of the five holds were mechanical. The fifth (a duplicate person page) is the case where gbrain's deterministic proposal (delete the `slug:` line) would have made the brain worse: it would have minted a second page for the same person.++Goal: the end user never sees a content hold unless gbrain itself, after trying, says `needs_human` with a one-paragraph reason written for a person and the exact command that applies what it proposes.++## 1. What exists today (read on master dda603ac)++- Holds: `src/core/persistence/sync-holds.ts` (one `op_checkpoints` row per hold, `gitHoldFix` per code, `holdRepairSteps` per source; hold metadata is location-only by contract, `sync-holds.ts:20`). `sync status` / `sync unblock` (`src/core/persistence/sync-status.ts`, `sync-fault-class.ts`): both codes already carry `safe_actions: ['repair']` (`sync-fault-class.ts:46,48`); what is missing is execution: `unblock --apply` **refuses** them ("not something unblock performs; run the fix it names", `sync-status.ts:162`) and `UnblockOutcome.applied.action` admits only `retry` actions (`sync-status.ts:126`).+- Fence repair (`src/core/fence-repair/*`, `src/core/repair/fences.ts`): Tier 1 lossless rules (`normalize.ts`, `structure.ts`, `content.ts`), Tier 2 holder resolver, Tier 3 model (`llm.ts`: the model sees the header plus the residual rows only, returns one table; `TIER3_REASONS` = screen reasons with `tier: 'llm'`), gates (a)–(g) (`validate.ts`; pairs compare `primaryFence` only, `validate.ts:87`, positional rows, `validate.ts:105`), attempt memo, daily USD ledger (`FENCE_REPAIR_LEDGER = {scope:'llm_repair', resolver:'fences'}`, each key its own ceiling), caps `fences.repair.max_usd_per_page` ($0.30) / `_per_day` ($1), switches `fences.repair.enabled` / `fences.repair.llm` (default on), model `models.fence_repair` with the measured fallback list (`measured.ts`). The preview calls no model; model output is produced at apply time (`fences.ts:18`). The maintenance cycle runs it (`src/core/cycle/fence-repair.ts`, 300 s budget). Receipts ride the write (`receipt.ts`) and the commit subject is `gbrain: repair fence in <path> (<classes>)` (`effect-model.ts:18`).+- The two fence reasons in the issue are **manual-only** in the reason table (`reasons.ts`): `repeated_marker` and `unclosed_trailing_content`. `structure.ts planClose` (line 115) refuses to close when text trails the table because gate (g): everything after an unpaired begin marker is hidden by the privacy boundary (`page-checks.ts:7`, shared by remote sanitization, the chunker and the strip functions), and closing early would publish it. `fenceBlocked` skips any fence with a repeated marker.+- `frontmatter_slug_conflict` (`markdown.ts:542`): held when frontmatter `slug:` differs from the path slug after slug normalization and the `slugExempt` check (a declared slug that already is the page's own slug is exempt). `gbrain repair frontmatter --include-ambiguous` proposes removing the line (`repair/frontmatter.ts:175`); the kind is `explicit_only` + `consent: 'destructive'`, so nothing runs it unattended.+- Page merge primitives exist only for the narrow phantom shape (`cycle/phantom-redirect.ts`, `phantom-redirect-managed.ts`: both page keys locked, deletion bound to the merged revision, withdrawals moved before facts, custom frontmatter and timeline residue refused, `phantom-redirect.ts:455-509`). Nothing general; `deletePageThrough` (`write-through.ts:563`) is best-effort and takes no commit subject.++## 2. Design++One lane, two tiers, one contract. Every repair goes preview → hash-bound apply → receipt, and the maintenance cycle applies the current plan unattended under the caps, exactly as `fence_repair` does today. The model **chooses**; every byte written comes from a deterministic rule and passes the gates.++### Lane A: fence structure repairs become deterministic (Tier 1), with the model for the judgment residue++A1. **`merge_fences`** (new Tier 1 fix class; clears `repeated_marker`). When one section holds N > 1 fences of the same kind and each is balanced (begin and end marker) with a header that maps to the canonical columns: the later fences' rows are appended to the primary fence in document order; a row whose cells (every column except the row number) equal a kept row's cells after cell trimming is dropped as an exact duplicate; an appended row whose number collides with a kept row is renumbered above the page's highest number (stored rows consulted as the `renumber` rule does; `superseded by #N` references follow); the later fences' markers, tables and a duplicated section heading immediately above them (`## Facts` twice) are removed; blank lines collapse to one. Anything else (an unbalanced repeat, a header that does not map, a repeat whose region holds non-table text) stays `repeated_marker` manual. Near-duplicates (same claim, different confidence or date) are **not** deduped: both rows stay and the contradiction machinery owns that case.++ **Validator (Codex #3).** The gates pair `primaryFence` before and after, positionally, so a merge is invisible to them. `validate.ts` gains a merge mapping: when the before section holds several fences of a kind and the after holds one and the fixes include `merge_fences`, the before rows are the concatenation of every fence's rows in document order, each mapped to an after row by occurrence or marked `duplicate_of: <occurrence>`; gates (b) claims, (c) numbers, (d) visibility and (f) cells run through that mapping; gate (e) accepts exactly the rows marked duplicate and only when the kept row's cells are byte-equal after trimming. Gate (c) already skips a number that is not page-unique (`validate.ts:126`), so a renumbered colliding row passes it and every unique number keeps its claim. The receipt carries occurrence identities (`merged: {fences: N, rows: [{occurrence, from_fence, kept_as | duplicate_of}]}`), never cell text. T1 mutates a claim in the *second* fence and proves gate (b) rejects it.++A2. **Closing an unclosed fence ahead of trailing text** (clears `unclosed_trailing_content`; Codex #2 reshaped it). The fence has no end marker, its rows are one contiguous block, and lines follow the last row. Closing after the last row makes those lines visible to whatever reads through the privacy boundary. Two cases:+ - **No exposure**: the page is `private` (effective visibility: `effectiveVisibility`, the same read the fence ctx already makes). Remote readers never see a private page's body and local readers see everything, so nothing new is disclosed; the end marker is inserted after the last row deterministically (`close_fence`, as today when nothing trails) and the receipt records `trailing_lines: N`. Gate (g) is unchanged: on a private page the boundary hides nothing from anyone, and the gate exemption is keyed to that fact, not to the fix class.+ - **Exposure** (a `world` page): nothing unattended. The model tier (A3) classifies the tail; a `prose` verdict makes the close **previewable** (the preview prints the exact lines that would become visible and the hash binds them), and only an explicit `gbrain repair content --apply --expect <hash>` applies it. Unattended runs (cycle, `sync unblock`) record `needs_human` with the rendered paragraph: "gbrain can close the takes fence in the timeline after row N; lines L1–L2 would then be visible to readers of this page. Approve with: gbrain repair content --source <id> --only <path> --apply --expect <hash>". So the one judgment that discloses text is the user's, hash-bound, as Codex asked; everything else clears itself.+ - A tail that mentions a fence marker stays `marker_near_miss` manual as today.++A3. **Model tier for the tail** (new Tier 3 request kind `tail`, same gateway call, caps, ledger and memo as rows). The model sees the fence's begin line, header, every row and the trailing lines to the section end (never the rest of the page) and answers one JSON object `{"tail": "prose" | "rows" | "unsure"}`. `rows` (the tail holds table rows written without pipes) and `unsure` render `unclosed_ambiguous_tail` (new reason, manual, with the exact edit); `prose` on a world page yields the previewable close above; on a private page the model is never called (A2 closes deterministically). The memo key is the fence region's sha256 + model + prompt version, so an unchanged tail never costs twice and a transient `llm_unavailable` does not consume it. The `rows_through_line` realignment idea from the first draft is cut (Codex #1): once a fence is closed, the existing row rules and the row prompt handle its rows on the next normalization round.++### Lane B: `frontmatter_slug_conflict` gets a judgment tier; merging is recommended, not executed++B1. **New repair kind `slug-conflicts`** (`src/core/repair/slug-conflicts.ts`; `REPAIR_KINDS` + `registry.ts` with `preview_bound: true`, `spends: 'llm'`, `checks: []` so doctor's first-match lookup keeps `git_held_files` on `frontmatter` (Codex #12), **not** `explicit_only`, so `--all`, `doctor --remediate` and the cycle phase run it). Candidates: every `frontmatter_slug_conflict` hold of the sources in scope (plus `--only <path>`). Identity is resolved, not textual (Codex #8): the frontmatter slug is normalized the way the screen does, resolved through `slug_aliases` (`readPageSnapshot(..., {resolveAlias: true})`) to a page id in the same source; a slug that resolves to the held file's own page is `slugExempt` and never a candidate; the held file may have no page yet (`page_id: null`, a new file) and that is a normal candidate.++B2. **Deterministic tier** (no model, confidence `high`): `remove_slug` when the named slug resolves to **no page** and names no other file in the checkout (a stray `slug:` from a template or a renamed file; nothing to merge into), or when the named page has a different `type` **and** shares no title token with the held file (the two COMPENDIUM cases). The edit is the one line, applied through the frontmatter repair's existing publication path (`prepareRepairPublication` / `submitManagedFileRepair`: exact bytes bound to the sha256 the preview read, import, hold clear and Git target effect in one coordinated write; legacy sources back up, write, import, clear the hold and print the commit step). Everything else is `ambiguous` → B3.++B3. **Model tier** (`tier: 'llm'`). The model sees: both files' frontmatter, headings and first 60 lines of body plus any line that mentions the other's slug anywhere in either body (Codex #7: evidence beyond the first 60 lines), both slugs and paths, the hold's reason, and the allowed answers. It returns one JSON object: `{"action":"remove_slug"}`, `{"action":"merge_into","canonical":"<one of the two slugs>"}` or `{"action":"needs_human"}`, plus an optional `why` sentence that goes into the run's output only, never into hold metadata (Codex #11). Same provider path as the fence tier, same failure classes, same `thinkingOffControl` and output ceiling. Memo key: sha256 of both participants' content + both ids + model + prompt version + rules version. Model: `models.content_repair` (explicit always runs) else `models.fence_repair` else the content-repair measured list (section 4), else the fence list. **Caps and ledger (Codex #9):** the kind reserves against the existing `FENCE_REPAIR_LEDGER` identity (one `fences.repair.max_usd_per_day` for the whole lane, today's prior spend counted) and the same per-page cap; `repair content` passes the fences run's remaining allowance into the slug-conflicts run. `fences.repair.llm=false` turns the model tier off for both kinds; `--no-llm` per run.++B4. **Outcomes.** `remove_slug` (deterministic, or the model's answer) applies as in B2. `merge_into` is **not executed in this PR**: it becomes `needs_human` with the rendered paragraph "This file and page `<canonical>` describe the same `<type>`; gbrain recommends merging the unique sections of `<path>` into `<canonical>` and deleting `<path>`, then committing; the hold clears on the next sync. gbrain does not merge pages by itself yet." and the recommendation stored as codes and slugs on the hold (`meta.content_repair: {action:'merge_into', canonical, model, at}`). `needs_human` from the model renders the generic paragraph ("gbrain could not decide whether `<path>` and `<canonical>` are the same page; decide which keeps the slug …"). Codex #4–#7 show that a general lossless merge needs coordinated two-page intents (both ids, revisions, incarnation, owner epoch, file hashes), withdrawal and metadata preservation rules, revision-bound deletion and database-aware recovery that the phantom path has only for its narrow shape. That is a feature of its own, filed in TODOS.md with those requirements; the acceptance criterion for the duplicate case ("merge_into … or needs_human with that recommendation, not a slug deletion") is met by the recommendation.++B5. **Receipt, trailer and hold state (Codex #6, #11).** Every content repair commit (fence and slug-conflict) carries the Git trailer `gbrain-repair: <hold_code> <tier> <confidence>` through the commit note in `effect-model.ts` (`fenceRepairCommit` gains a trailer line the Git effect prints after a blank line; legacy commit steps print the same `-m` pair). The durable receipt is the write's outcome: the existing `fence_repair` receipt gains `merged`/`trailing_lines`; the slug-conflict write carries a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256), validated by a parser like `parseFenceRepairReceipt` so nothing forged reaches a commit message. Receipts distinguish `published` from the Git effect's own state (`committed: effect | commit_step | not_in_git`) as the fence receipt does today; no promise about reverting beyond "git revert of the single file commit restores the bytes; the hold then re-screens". Hold state: `meta.content_repair` is written with `recordContentHoldRepair` (conditional on the hold's `upstream_version`, like `recordFenceHoldRepair`), carries reason codes, slugs, `at` and `next_attempt_after` only, and `writeGitHold` keeps it when a re-screen rewrites a hold with the same `upstream_version` and code; a changed file drops it. `sync status` renders `needs_human: true` and the paragraph from those codes (`human_reason` templates in `sync-fault-class.ts`), never model prose. A hold the lane could not decide is retried on `next_attempt_after` (24 h for `llm_unavailable`/`budget_exhausted`, never for `needs_human` until the file changes).++### Lane C: the lane runs by itself++C1. **Cycle phase `content_repair`** (`src/core/cycle/content-repair.ts`, after `fence_repair` in the phase table): one bounded run of `slug-conflicts` through `repairRunner` (apply on a real run, preview on dry run), deadline min(120 s, a third of the job's remaining time), gated on `fences.repair.enabled`; reports counts by action and reason, spend and the oldest unresolved hold's age; never fails the cycle. `holdRepairSteps` says "the next maintenance run repairs the fence and slug-conflict holds it can by itself" when the lane is active. Every unresolved hold stays listed with its state (`needs_human`, `paid`, `owner`, `apply`): nothing hides budget-blocked or owner-unavailable work (Codex #12).++C2. **`sync unblock --apply`** performs `repair`: for `invalid_fence` holds it runs the `fences` kind on those paths, for `frontmatter_slug_conflict` the `slug-conflicts` kind, each a bounded apply under the caps, then schedules the re-screen and prints the sync. `UnblockOutcome.applied` gains `action: 'repair'` with per-path structured outcomes (`repaired | held | needs_human | skipped`, reason code, `llm_usd`, receipt ref, exact next action); `--no-llm` keeps to the free tiers; `--no-repair` restores the old refuse-only behaviour. The runbook sentence "unblock writes no page" changes to "unblock writes only hash-bound repairs and prints each receipt" (BEHAVIOR_CHANGES row). `invalid_frontmatter` and `rename_held` still route to `repair frontmatter` (interpretive YAML fixes stay consent-gated; TODOS entry with the weekly counts from the issue).++C3. **`gbrain repair content`** runs `fences` then `slug-conflicts` for the same `--source`/`--only` selection, printing each kind's own preview hash (no combined hash scheme); `--apply` without `--expect` applies both current plans (both kinds are `preview_bound` without `explicit_only`, as `fences` is today), `--apply --expect <fences-hash>[,<slug-hash>]` applies exactly those sets, `--max-usd` is the lane's allowance for the run (remaining allowance flows from the first kind to the second). Both component plans are built before the first mutation (Codex #10). `gitHoldFix` names this command for both codes.++C4. **Reason table and surfaces.** New reasons in `reasons.ts`: `unclosed_ambiguous_tail` (manual, exact edit), `tail_exposure_approval` (paid: false, actor `user`, the hash-bound approval above). Error registry rows with agent-operator envelopes for `unclosed_ambiguous_tail`, `tail_exposure_approval`, `content_repair_needs_human`, `merge_recommended`; `bun run build:error-codes`. `holdRescreenDue` is unchanged for slug conflicts (already unconditional, `sync-holds.ts:343`); `FENCE_RULES_VERSION` bumps so older fence holds re-screen under the widened rules.++### What this plan does not do++- No LLM-composed text, no model-executed merge: the model chooses among coded actions; every byte written comes from a deterministic rule and passes the gates.+- No page merge executor (B4; follow-up with Codex's requirements in TODOS.md).+- No YAML frontmatter interpretation unattended (the 198 weekly frontmatter repairs): TODOS.md.+- No change to what `put_page`/`capture` accept on write beyond the Tier 1 `merge_fences` rule, which `fences.normalize` already governs (lossless, gated).++## 3. Tests (smallest set that proves each claim)++- T1 `fence-repair-structure.test.ts`: A1 merges two balanced facts fences (3 rows + 85 rows, 3 exact duplicates) into one, removes the duplicate heading, renumbers collisions, records occurrences; a mutated claim in the **second** fence fails gate (b); a dropped non-duplicate fails (e); an unbalanced repeat or a non-mapping header stays manual; near-duplicates both kept. A2: a private page with two trailing bullets closes after the last row with `trailing_lines: 2`; a world page with the same tail is not closed unattended and renders `tail_exposure_approval`; a marker mention stays manual.+- T2 `fence-repair-llm.test.ts`: the tail prompt builds from the fence region only; `prose`/`rows`/`unsure` parse; malformed/truncated/refused classes; `prose` on a world page produces the previewable close whose hash covers the exposed lines; a changed tail invalidates the hash; the memo blocks a second paid call on unchanged bytes and does not consume on `llm_unavailable`.+- T2b (Codex #2): a world page whose unclosed tail holds a sentence; after an unattended cycle and `sync unblock --apply`, remote `get_page`, remote search and the chunker still do not return that sentence; after the explicit hash-bound apply they do.+- T3 `repair-slug-conflicts.test.ts` (PGLite + temp Git checkout, as `repair-fences.test.ts`): deterministic `remove_slug` when the named page is absent, or of another type with no shared title token; a slug resolving through an alias to the held file's own page is exempt; the duplicate-person pair (mutual hygiene notes) goes to the model tier; stubbed `merge_into` → hold carries `content_repair` codes, `sync status` shows `needs_human` with the rendered paragraph naming the canonical, nothing written; stubbed `remove_slug` applies through the coordinated path and clears the hold; preview writes nothing and calls no model; `changed_since_preview`; cap exhaustion → `budget_exhausted` and nothing applied; the ledger key is `FENCE_REPAIR_LEDGER` (a prior fences spend counts).+- T4 `sync-status-unblock.test.ts`: `unblock --apply` repairs an `invalid_fence` hold and a deterministic slug-conflict hold, lists structured per-path outcomes, schedules re-screens, prints the sync; `--no-llm` holds the model-tier candidate `llm_disabled`; `--no-repair` refuses as before; `needs_human` holds are listed and not retried.+- T5 `cycle-content-repair.test.ts`: the phase runs within budget, gates on `fences.repair.enabled`, reports counts, never fails the cycle.+- T6 Acceptance fixture (`test/fixtures/content-repair/`, placeholder names): the issue's five holds plus 45 seeded ones across `repeated_marker`, `unclosed_trailing_content` (private and world pages), `frontmatter_slug_conflict` (absent page, other type, duplicate pair, alias-exempt). One maintenance cycle with the transport stubbed, then the printed re-screen sync; assert the exact remaining hold set: the world-page tails as `tail_exposure_approval`, the duplicate pair as `merge_recommended`, everything else cleared with a receipt each (Codex #13).+- T7 Goldens: export surface, CLI flag registry, error-code registry, behavior-change notice, docs anchors, sync-runbook table pin.++## 4. Eval (gbrain-evals, paired PR)++`evals/content-repair-judgment/`: 48 synthetic pairs with placeholder names: 15 true duplicates with mutual notes, 10 true duplicates without notes, 10 stray template slugs onto unrelated pages, 8 adversarial (unrelated people with the same name, a misleading `-2` suffix on a different person, a forged "duplicate" note pointing at an unrelated page, identity evidence only after line 60), 5 genuinely ambiguous. Models per the project rule: `openai:gpt-6.1-sol`, `anthropic:claude-opus-5-5`, `anthropic:claude-sonnet-5-5` (no Fable, no gpt-5.4-mini, no older generations); 3 runs each. Preregistered rule (Codex #7): hard failures are `remove_slug` on a true duplicate and `merge_into` on an unrelated pair or with the wrong canonical; a model qualifies with zero hard failures and ≥ 80% `merge_into` with the right canonical on true duplicates; `needs_human` is always acceptable. Verdicts and preregistration mirrored into gbrain-evals; `CONTENT_REPAIR_MEASURED_MODELS` ships whatever met the rule, best first, ties to the cheaper model. If the eval is not done when the PR is otherwise ready, the fallback stays the fence list (both frontier) and the constant is filled by the gbrain-evals PR's follow-up; the CHANGELOG says so.++## 5. Docs, notices, release++- `docs/guides/write-refusals.md`: `repeated_marker` and `unclosed_trailing_content` say what repairs them and when the user's approval is needed; `frontmatter_slug_conflict` gets the three outcomes; new anchors `unclosed_ambiguous_tail`, `tail_exposure_approval`, `merge_recommended`, `content_repair_needs_human`. GBRA-57 (#6277 touches this guide) told before editing.+- `docs/guides/repair.md` "held files": the lane, `gbrain repair content`, the trailer, what a receipt proves. `docs/guides/sync-unblock-runbook.md`: unblock performs `repair` (hash-bound, receipts), `--no-repair`; decision-table rows updated and the pinned test regenerated.+- `docs/architecture/KEY_FILES.md` entries for `repair/slug-conflicts.ts`, `fence-repair/merge.ts`, `fence-repair/llm-tail.ts`, `cycle/content-repair.ts`. CLAUDE.md fence invariant amended (merge mapping; the private-page close).+- `src/core/behavior-change-notice.ts` rows: the maintenance run merges repeated fences, closes unclosed fences on private pages and clears stray slug conflicts by itself; a model (under the fence-repair caps) classifies ambiguous cases; `sync unblock --apply` now writes hash-bound repairs. CHANGELOG entry in the repo's voice. AGENTS.md "Sync held a file" paragraph points at the lane. TODOS.md: merge executor requirements, unattended frontmatter interpretation.+- Version: master + 1 PATCH at the merge slot (GBRA-40 confirms); every version stamp synced; `UBI_OWNER=gbra72` full gate.++## 6. Risks and the answer to each++- Disclosing hidden text → only private pages close unattended; world pages need the user's hash-bound approval of the exact lines (T2b proves remote reads stay clean until then).+- A wrong `remove_slug` mints a duplicate page → the deterministic tier removes a slug only when there is nothing to merge into (no page, or a different type with no title overlap); the model tier's hard-failure eval covers the rest; `merge_into` never deletes anything in this PR.+- Dedup drops a real row → byte equality after trimming only, recorded per occurrence; the validator mapping protects every kept row.+- Spend → one shared day cap (default $1), memo, per-page cap; `fences.repair.llm=false` is the kill switch; `--no-llm` per run.+- Racing a sync → both kinds use `repairBusy` admission re-reads and the coordinated file-repair intent's hash binding, as fences does today.+- Two threads editing `write-refusals.md` (GBRA-57) → coordinate before the docs lane; merge master before the gate.++## 7. Decisions for Garry++- D1. Duplicate pages: this PR recommends the merge (`needs_human` naming the canonical, nothing changed) instead of executing it; the executor ships separately once it has the coordinated two-page intent Codex specified. Plan: recommend now, execute in the follow-up.+- D2. Text hidden behind an unclosed fence on a world-visible page becomes visible only after you (or your agent) approve the exact lines with the hash-bound apply; private pages close by themselves. Plan: as stated.+- D3. One cap for the whole lane under the existing `fences.repair.*` keys (no new keys, no migration). Plan: keep the keys; docs call them the content-repair caps.++## 8. Review record++/autoplan 2026-10-09 (GBRA-72). Phases: CEO (scope), DX (agent operator contract), Eng (dual voices: Claude adversarial pass + Codex `gpt-6-astra` outside review, `~/.capy/work/gbra72/codex-review.md`, verdict needs-rework on draft 1). Decisions applied to draft 2 above, by principle (safety over convenience, reuse over new machinery, smallest change that meets acceptance, no guessing about privacy):++| # | Finding (Codex / own) | Decision |+|---|---|---|+| 1 | Scope: general merge system beyond acceptance; cut the structure classifier unless needed | Merge executor cut (B4 → recommendation + TODOS). Tail classifier kept, narrowed to one question (`prose|rows|unsure`); `rows_through_line` cut. |+| 2 | Blocker: pipe-free tail is no permission to expose text | Accepted. Unattended close only on private pages (no disclosure); world pages need the user's hash-bound approval of the exact lines; T2b proves remote reads stay clean. |+| 3 | Blocker: validator pairs primary fences only; gate (c) has no renumber exemption | Accepted. Merge mapping in `validate.ts` through every gate; (c) already tolerates non-unique numbers; receipts carry occurrences; T1 mutates the second fence. |+| 4–6 | Blockers: merge overwrites concurrent work, drops metadata/withdrawals, false two-commit revert claim | Accepted by removing merge execution from this PR; requirements recorded in TODOS.md for the follow-up. |+| 7 | Blocker: corroboration and eval do not guard false merges | Eval rule rewritten with hard failures and adversarial pairs; no unattended merge at all in this PR. |+| 8 | Identity: aliases, pageless held files, slug exemptions | Accepted (B1). |+| 9 | Ledger: new resolver key is a new bucket | Accepted: reuse `FENCE_REPAIR_LEDGER`; remaining allowance flows between kinds; memo keyed on both participants. |+| 10 | Explicit approval must bind a concrete decision | Accepted where it still applies: the tail approval hash binds the exact exposed lines; both component plans built before the first mutation. |+| 11 | Hold metadata contract; model prose | Accepted: codes and slugs only on the hold, templates render the paragraph, conditional writes carried across re-screens. |+| 12 | JSON/doctor integration | Accepted: structured per-path unblock outcomes, `checks: []` on the new kind, nothing hidden. |+| 13 | Tests do not prove safety | T2b and T6 (exact remaining set after the printed sync) added; the concurrent-writer deletion test moves with the merge executor. |+| own | Tier 1 rules also run on write paths under `fences.normalize` | `merge_fences` is lossless and gated, so it runs there too; the private-page close as well; nothing exposes on world pages without approval. |+| own | DX: `needs_human` paragraphs must carry the exact apply command | Templates include the `--apply --expect <hash>` command where one exists. |diff --git a/scripts/build-fence-format.ts b/scripts/build-fence-format.tsindex 10ee266286..29c900d792 100644--- a/scripts/build-fence-format.ts+++ b/scripts/build-fence-format.ts@@ -75,7 +75,7 @@ const GATE_TEXT = {b: 'Every claim cell is unchanged (struck claims included).',c: 'Every row number that was valid and unique still names the same claim.',d: 'No row becomes more visible: `private` never turns `world`.',- e: 'No row is added or dropped, and every row of the fence stays inside it.',+ e: 'No row is added or dropped, and every row of the fence stays inside it; under `merge_fences` the only rows dropped are the exact duplicates its mapping names.',f: 'A cell valid in its column keeps its text; a misaligned cell may only move, and text changes only through a named rule.',g: 'Text the privacy boundary hid before the repair stays hidden after it.',} satisfies Record<GateLetter, string>;@@ -185,6 +185,7 @@ function synonymLines(table: Readonly<Record<string, string>>): string {function normalizedTable(): string {const brainWords = [...BRAIN_ALIASES].filter(word => word !== 'brain');const text = {+ merge_fences: 'A section with more than one fence of a kind becomes one fence when every fence has both markers, the same canonical header and nothing but table lines inside: the later fences\' rows are appended to the first in document order, a later row whose cells (every column but `#`) equal a kept row\'s as written is dropped, a number that now collides is renumbered (see [row numbers](#row-numbers)) and a `superseded by #N` reference follows its own fence\'s row N, and the later markers, tables and a repeated section heading above them are removed. Anything else stays `repeated_marker` and a person merges the fences.',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 (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.',diff --git a/src/core/fence-repair/content.ts b/src/core/fence-repair/content.tsindex 48cd10066e..f23ccad218 100644--- a/src/core/fence-repair/content.ts+++ b/src/core/fence-repair/content.ts@@ -4,7 +4,11 @@* prior-aware `renumber` across body and timeline. Of two rows sharing a* number, the one matching the stored row keeps it; otherwise a row in a* fence that parses clean keeps it (Invariant 0), and the first occurrence- * only breaks the remaining tie.+ * only breaks the remaining tie. A `superseded by #N` reference that names a+ * shared number is ambiguous, except inside a fence `merge_fences` built+ * (#6377): there it names its own before-fence's row N and follows that+ * row's new number (or the number of the kept row a dropped duplicate N+ * equalled).** Cells are edited in place by source span; a row is re-rendered only when* its header is rewritten, and then every cell keeps its source text and only@@ -14,6 +18,7 @@import { parseFactsFence } from '../facts-fence.ts';import { stripStrikethrough } from '../fence-shared.ts';import { parseTakesFence } from '../takes-fence.ts';+import type { MergeOrigins } from './merge.ts';import { planRowRules, type CellText, type RowPlan } from './rules.ts';import { extractRawRows, rowNumOf, type RawFence, type RawRow, type RawSection } from './raw-rows.ts';import { ALLOWED, BASE_WIDTH, canonicalColumn, CANONICAL_HEADER, collapse, COLUMN_DEFAULTS, COLUMNS, supersededRef } from './schema.ts';@@ -43,7 +48,11 @@ interface RowWork {needsNumber: boolean;/** The row's fence parses with no warning (Invariant 0 prefers to leave it alone). */clean: boolean;+ /** Index of the before fence the row came from, when `merge_fences` built its fence; null otherwise. */+ origin: number | null;newNum?: number;+ /** The `superseded by #N` reference the row carries now names this number. */+ refTo?: number;}interface FenceWork {@@ -60,6 +69,7 @@ interface Pass {works: FenceWork[];/** All rows of each kind in page order (body first), workable or not. */rows: Record<FenceKind, RowWork[]>;+ merges: readonly MergeOrigins[];/** Next number to hand out; one counter for both kinds, so no new number repeats on the page. */next: number | null;nextNumber: () => number;@@ -68,8 +78,8 @@ interface Pass {const REPORTED: ReadonlySet<FenceReason> = new Set(['row_before_header', 'no_header', 'short_row', 'extra_cells']);/** Plan and apply the content rules; `nextNumber` is called only when a row needs a new number. */-export function contentPass(texts: Record<FenceSection, string>, ctx: FenceCtx, nextNumber: () => number): ContentResult {- const pass: Pass = { ctx, fixes: [], residual: [], edits: { body: [], timeline: [] }, works: [], rows: { facts: [], takes: [] }, next: null, nextNumber };+export function contentPass(texts: Record<FenceSection, string>, ctx: FenceCtx, nextNumber: () => number, merges: readonly MergeOrigins[] = []): ContentResult {+ const pass: Pass = { ctx, fixes: [], residual: [], edits: { body: [], timeline: [] }, works: [], rows: { facts: [], takes: [] }, next: null, nextNumber, merges };for (const section of ['body', 'timeline'] as const) planSection(pass, extractRawRows(texts[section], section));for (const kind of ['facts', 'takes'] as const) renumber(pass, kind);for (const work of pass.works) emitFence(pass, work);@@ -95,7 +105,8 @@ function planSection(pass: Pass, raw: RawSection): void {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));+ const merged = mergeOf(pass, fence);+ const rows = fence.rows.map(row => rowWork(pass, fence, row, workable, clean, merged?.origins[row.occurrence] ?? null));pass.rows[fence.kind].push(...rows);if (workable) pass.works.push({ fence, rewrite, rows });}@@ -143,13 +154,17 @@ function planRewrite(fence: RawFence): Rewrite {return { target, defaults };}-function rowWork(pass: Pass, fence: RawFence, row: RawRow, workable: boolean, clean: boolean): RowWork {+function mergeOf(pass: Pass, fence: RawFence): MergeOrigins | undefined {+ return pass.merges.find(m => m.section === fence.section && m.kind === fence.kind);+}++function rowWork(pass: Pass, fence: RawFence, row: RawRow, workable: boolean, clean: boolean, origin: number | null): RowWork {const num = rowNumOf(fence, row);const aligned = workable && !row.beforeHeader && row.shape === 'ok';const plan = aligned ? planRowRules(fence.kind, cellTexts(row), pass.ctx) : null;const hidden = num !== null && (pass.ctx.hiddenRows?.has(num) ?? false);const minted = aligned && !fence.columns.includes('#') && fence.needsRewrite;- return { fence, row, num, plan, eligible: aligned && !hidden, needsNumber: minted || (plan?.badNumber ?? false), clean };+ return { fence, row, num, plan, eligible: aligned && !hidden, needsNumber: minted || (plan?.badNumber ?? false), clean, origin };}function cellTexts(row: RawRow): Map<string, CellText> {@@ -161,12 +176,26 @@ function claimKey(row: RawRow): string {return collapse(stripStrikethrough(row.byColumn.get('claim')?.text ?? '').text);}+const REF_COLUMN: Record<FenceKind, string> = { facts: 'context', takes: 'source' };++function refOf(kind: FenceKind, w: RowWork): number | null {+ return supersededRef(w.row.byColumn.get(REF_COLUMN[kind])?.text ?? '');+}+function renumber(pass: Pass, kind: FenceKind): void {const rows = pass.rows[kind];- const refColumn = kind === 'facts' ? 'context' : 'source';- const refs = new Set(rows.map(w => supersededRef(w.row.byColumn.get(refColumn)?.text ?? '')).filter(n => n !== null));+ // A reference from outside a merged fence makes any shared number it names ambiguous; a merged row's reference is resolved to its own before fence below.+ const refs = new Set(rows.filter(w => w.origin === null).map(w => refOf(kind, w)).filter(n => n !== null));const groups = new Map<number, RowWork[]>();for (const w of rows) if (w.num !== null) groups.set(w.num, [...(groups.get(w.num) ?? []), w]);+ const targets = new Map<RowWork, RowWork>();+ for (const w of rows) {+ const num = w.origin === null ? null : refOf(kind, w);+ if (num === null) continue;+ const target = localTarget(pass, kind, w, num, groups);+ if (target === 'ambiguous') pass.residual.push(issueAt(w.fence, 'superseded_ambiguous', w.row.line, num, '#'));+ else if (target) targets.set(w, target);+ }for (const [num, group] of groups) {if (group.length < 2) continue;if (refs.has(num)) {@@ -187,6 +216,40 @@ function renumber(pass: Pass, kind: FenceKind): void {pass.next ??= pass.nextNumber();w.newNum = pass.next++;}+ for (const [w, target] of targets) {+ const final = finalNum(target);+ if (final === null || final === refOf(kind, w)) continue;+ if (!w.plan) {+ pass.residual.push(issueAt(w.fence, 'superseded_ambiguous', w.row.line, refOf(kind, w), '#'));+ continue;+ }+ w.refTo = final;+ }+}++/**+ * The row a merged row's `superseded by #N` names: the one row numbered N of+ * its own before fence, or the kept row a dropped duplicate numbered N of+ * that fence equalled. With neither, N must not be a shared number.+ */+function localTarget(pass: Pass, kind: FenceKind, w: RowWork, num: number, groups: ReadonlyMap<number, RowWork[]>): RowWork | 'ambiguous' | null {+ const merged = mergeOf(pass, w.fence)!;+ const section = pass.rows[kind].filter(r => r.fence.section === w.fence.section);+ const own = section.filter(r => r.origin === w.origin && r.num === num);+ const dropped = merged.dropped.filter(d => d.fence === w.origin && d.num === num).map(d => section[d.keptOccurrence]!);+ const candidates = [...own, ...dropped];+ if (candidates.length > 1) return 'ambiguous';+ if (candidates.length === 1) return candidates[0]!;+ return (groups.get(num)?.length ?? 0) > 1 ? 'ambiguous' : null;+}++/** The reference cell rewritten to the row's new number, on top of any rule change to the same cell. */+function refEdit(w: RowWork, kind: FenceKind): void {+ const column = REF_COLUMN[kind];+ const change = w.plan!.changes.find(c => c.column === column);+ const raw = (change?.raw ?? w.row.byColumn.get(column)?.raw ?? '').replace(/(superseded by #)\d+/i, `$1${w.refTo}`);+ if (change) change.raw = raw;+ else w.plan!.changes.push({ column, raw, class: 'renumber' });}/** The number the row was written with (`0` and negatives included), or null when the cell is not numeric or absent. */@@ -208,8 +271,13 @@ function emitFence(pass: Pass, work: FenceWork): void {if (w.newNum !== undefined) {pass.fixes.push({ fence: fence.kind, section: fence.section, row, column: '#', line: w.row.line, class: 'renumber', from: writtenNum(w.row) });}+ if (w.refTo !== undefined) {+ refEdit(w, fence.kind);+ pass.fixes.push({ fence: fence.kind, section: fence.section, row, column: REF_COLUMN[fence.kind], line: w.row.line, class: 'renumber' });+ }for (const change of w.plan.changes) {if (change.column === 'context' && change.class === 'kind_map') continue;+ if (change.column === REF_COLUMN[fence.kind] && change.class === 'renumber') continue;pass.fixes.push({ fence: fence.kind, section: fence.section, row, column: change.column, line: w.row.line, class: change.class });}for (const i of w.plan.issues) pass.residual.push(issueAt(fence, i.reason, w.row.line, row, i.column, i.allowed));diff --git a/src/core/fence-repair/merge.ts b/src/core/fence-repair/merge.tsnew file mode 100644index 0000000000..6e553a7106--- /dev/null+++ b/src/core/fence-repair/merge.ts@@ -0,0 +1,259 @@+/**+ * Tier 1 `merge_fences` (#6377): a section that holds more than one fence of+ * a kind becomes one fence, so `repeated_marker` no longer needs a person+ * when the merge has one obvious meaning.+ *+ * The rule applies only when every fence of the kind is balanced (begin and+ * end marker, no near-miss form), every header maps to the same canonical+ * columns in the same order, every marker stands alone on its line and+ * nothing but the header, separators and rows sits inside any fence region.+ * The later fences' rows are appended to the primary fence in document+ * order; a later row whose cells (every column but `#`, trimmed source text)+ * equal a kept row's cells is dropped as a duplicate. The later fences'+ * markers and tables go, together with a section heading that repeats an+ * earlier heading directly above a removed fence, and the blank lines around+ * each removed block collapse to one. Row numbers that now collide are+ * renumbered by the content pass (`renumber`), and a `superseded by #N`+ * reference inside a merged fence follows its own fence's row N.+ *+ * `mergePlan` is the one source of the before-to-after row mapping: the+ * normalizer edits from it, the validator (`validate.ts`) re-derives it from+ * the before page to check gates (b)-(f) row by row, and the receipt carries+ * it location-only (`mergedReceipt`).+ */+import { indexOfOutsideCode, scanMarkdownCode, type MarkdownCodeMap } from '../fence-scan.ts';+import { sectionsOf } from './page-checks.ts';+import { extractRawRows, MARKERS, parseRowSpans, rowNumOf, type RawFence, type RawRow, type RawSection } from './raw-rows.ts';+import type { MergedFenceReceipt } from './receipt.ts';+import type { Edit } from './structure.ts';+import type { FenceFix, FenceKind, FencePage, FenceSection } from './types.ts';++export interface MergeRow {+ /** Index into `MergePlan.fences` (0 is the primary). */+ fence: number;+ /** The row's occurrence in that fence. */+ occurrence: number;+ row: RawRow;+ /** Occurrence in the merged fence; null for a dropped duplicate. */+ keptAs: number | null;+ /** Index into `MergePlan.rows` of the kept row this one duplicates; null for a kept row. */+ duplicateOf: number | null;+}++export interface MergePlan {+ kind: FenceKind;+ section: FenceSection;+ /** Every fence of the kind, in document order. */+ fences: RawFence[];+ /** Every row of every fence, in document order. */+ rows: MergeRow[];+}++/** What the content pass needs to know about a merged fence in the text it reads. */+export interface MergeOrigins {+ section: FenceSection;+ kind: FenceKind;+ /** Per merged-fence occurrence: the index of the fence the row came from. */+ origins: number[];+ /** Per merged-fence occurrence: the row's line in the merged section text. */+ mergedLines: number[];+ /** Per merged-fence occurrence: the row's line in the before section text. */+ beforeLines: number[];+ /** Dropped duplicates: the fence and row number each had, and the merged occurrence of the row it duplicates. */+ dropped: Array<{ fence: number; num: number | null; keptOccurrence: number }>;+}++const HEADING = /^#{1,6}\s/;+const BLANK = /^[ \t]*$/;++/** The merge of a kind's fences in one section, or null when the rule does not apply. */+export function mergePlan(raw: RawSection, kind: FenceKind): MergePlan | null {+ const fences = raw.fences.filter(f => f.kind === kind);+ if (fences.length < 2 || !fences[0]!.primary) return null;+ if (raw.issues.some(i => i.fence === kind && i.reason === 'missing_begin')) return null;+ const code = scanMarkdownCode(raw.text);+ if (countOutsideCode(raw.text, MARKERS[kind].begin, code) !== fences.length || countOutsideCode(raw.text, MARKERS[kind].end, code) !== fences.length) return null;+ const columns = fences[0]!.columns;+ for (const fence of fences) {+ if (!fence.end || fence.begin.nearMiss || fence.end.nearMiss || !fence.header) return null;+ if (fence.columns.length !== columns.length || fence.columns.some((c, i) => c === null || c !== columns[i])) return null;+ if (fence.issues.some(i => i.reason === 'row_before_header')) return null;+ if (!markerAlone(raw.text, fence.begin) || !markerAlone(raw.text, fence.end) || !tableOnly(raw.text, fence.regionStart, fence.regionEnd)) return null;+ }+ const rows: MergeRow[] = [];+ const kept = new Map<string, number>();+ let next = 0;+ fences.forEach((fence, index) => {+ for (const row of fence.rows) {+ const key = rowKey(fence, row);+ const earlier = index > 0 ? kept.get(key) : undefined;+ if (earlier !== undefined) {+ rows.push({ fence: index, occurrence: row.occurrence, row, keptAs: null, duplicateOf: earlier });+ continue;+ }+ kept.set(key, rows.length);+ rows.push({ fence: index, occurrence: row.occurrence, row, keptAs: next++, duplicateOf: null });+ }+ });+ return { kind, section: raw.section, fences, rows };+}++/** Every cell but `#` as written (trimmed source text), in column order, then the cells no column takes. */+export function rowKey(fence: RawFence, row: RawRow): string {+ const cells = fence.columns.filter((c): c is string => c !== null && c !== '#').map(c => row.byColumn.get(c)?.raw ?? '');+ return [...cells, ...row.extra.map(c => c.raw)].join('\u0000');+}++function countOutsideCode(text: string, needle: string, code: MarkdownCodeMap): number {+ let n = 0;+ for (let i = indexOfOutsideCode(text, needle, 0, code); i !== -1; i = indexOfOutsideCode(text, needle, i + needle.length, code)) n++;+ return n;+}++/** The marker is the whole of its line (so the line can go with the fence). */+function markerAlone(text: string, marker: { start: number; end: number }): boolean {+ const [start, end] = lineBounds(text, marker.start);+ return text.slice(start, end).trim() === text.slice(marker.start, marker.end);+}++/** Every non-blank line of the region is a pipe-table line. */+function tableOnly(text: string, start: number, end: number): boolean {+ for (let at = start; at < end;) {+ const nl = text.indexOf('\n', at);+ const lineEnd = nl === -1 || nl > end ? end : nl;+ if (text.slice(at, lineEnd).trim() && parseRowSpans(text, at, lineEnd, 0) === null) return false;+ if (lineEnd === end) break;+ at = lineEnd + 1;+ }+ return true;+}++/** `[start, end)` of the line holding `at`, without its line ending. */+function lineBounds(text: string, at: number): [number, number] {+ const start = text.lastIndexOf('\n', at - 1) + 1;+ const nl = text.indexOf('\n', at);+ let end = nl === -1 ? text.length : nl;+ if (end > start && text[end - 1] === '\r') end--;+ return [start, end];+}++/** Offset just past the line ending of the line holding `at` (the text end when it has none). */+function lineAfter(text: string, at: number): number {+ const nl = text.indexOf('\n', at);+ return nl === -1 ? text.length : nl + 1;+}++function lineEnding(text: string, at: number): string {+ const nl = text.indexOf('\n', at);+ return nl !== -1 && nl > 0 && text[nl - 1] === '\r' ? '\r\n' : '\n';+}++/** The edits that turn the section into one fence: appended rows, removed later fences, removed repeated headings, collapsed blanks. */+export function mergeEdits(text: string, plan: MergePlan): Edit[] {+ const primary = plan.fences[0]!;+ const tail = [primary.header, ...primary.separators, ...primary.rows].filter((r): r is RawRow => r !== null).sort((a, b) => b.line - a.line)[0]!;+ const [, tailEnd] = lineBounds(text, tail.start);+ const eol = lineEnding(text, tail.start);+ const appended = plan.rows.filter(r => r.fence > 0 && r.keptAs !== null).map(r => `${eol}${text.slice(r.row.start, r.row.end)}`).join('');+ const edits: Edit[] = appended ? [{ start: tailEnd, end: tailEnd, text: appended }] : [];+ const headings = new Set<string>();+ for (const fence of plan.fences.slice(1)) {+ let [start] = lineBounds(text, fence.begin.start);+ for (const line of linesBefore(text, start)) {+ if (BLANK.test(line.text)) continue;+ if (HEADING.test(line.text) && earlierHeading(text, line.start, line.text.trim(), headings)) start = line.start;+ break;+ }+ let end = lineAfter(text, fence.end!.start);+ let blankBefore = false;+ for (const line of linesBefore(text, start)) {+ if (!BLANK.test(line.text)) break;+ start = line.start;+ blankBefore = true;+ }+ let blankAfter = false;+ while (end < text.length) {+ const [lineStart, lineEnd] = lineBounds(text, end);+ if (!BLANK.test(text.slice(lineStart, lineEnd))) break;+ end = lineAfter(text, end);+ blankAfter = true;+ }+ edits.push({ start, end, text: (blankBefore || blankAfter) && start > 0 && end < text.length ? lineEnding(text, fence.begin.start) : '' });+ }+ return edits;+}++/** The lines before offset `at` (which starts a line), nearest first, without line endings. */+function* linesBefore(text: string, at: number): Generator<{ start: number; text: string }> {+ while (at > 0) {+ const [start, end] = lineBounds(text, at - 1);+ yield { start, text: text.slice(start, end) };+ at = start;+ }+}++/** A line with the same trimmed heading text appears before `before` in the section. */+function earlierHeading(text: string, before: number, heading: string, cache: Set<string>): boolean {+ if (cache.has(heading)) return true;+ let at = 0;+ while (at < before) {+ const nl = text.indexOf('\n', at);+ const end = nl === -1 || nl > before ? before : nl;+ if (text.slice(at, end).trim() === heading) {+ cache.add(heading);+ return true;+ }+ if (nl === -1 || nl >= before) break;+ at = nl + 1;+ }+ return false;+}++/** The merged fence's row origins in `merged`, the section text after `mergeEdits`. */+export function mergeOrigins(plan: MergePlan, merged: string): MergeOrigins {+ const fence = extractRawRows(merged, plan.section).fences.find(f => f.kind === plan.kind && f.primary);+ const kept = plan.rows.filter(r => r.keptAs !== null);+ if (!fence || fence.rows.length !== kept.length) throw new Error('merged fence rows do not match the merge plan');+ return {+ section: plan.section, kind: plan.kind,+ origins: kept.map(r => r.fence),+ mergedLines: fence.rows.map(r => r.line),+ beforeLines: kept.map(r => r.row.line),+ dropped: plan.rows.filter(r => r.keptAs === null).map(r => ({ fence: r.fence, num: rowNumOf(plan.fences[r.fence]!, r.row), keptOccurrence: plan.rows[r.duplicateOf!]!.keptAs! })),+ };+}++/** Lines of fixes and issues reported on the merged text, mapped back to the before section's lines. */+export function beforeLine(merges: readonly MergeOrigins[], item: { fence: FenceKind; section: FenceSection; line: number | null }): number | null {+ if (item.line === null) return null;+ const origin = merges.find(m => m.section === item.section && m.kind === item.fence);+ if (!origin) return item.line;+ const at = origin.mergedLines.indexOf(item.line);+ return at === -1 ? item.line : origin.beforeLines[at]!;+}++/** The merge plans the fixes of a repair name, re-derived from the before page (null when a named merge does not apply to it). */+export function mergePlans(before: FencePage, fixes: ReadonlyArray<{ class: string; fence: FenceKind; section: FenceSection }>): Map<string, MergePlan> | null {+ const plans = new Map<string, MergePlan>();+ const sections = new Map(sectionsOf(before));+ for (const fix of fixes) {+ if (fix.class !== 'merge_fences' || plans.has(`${fix.section}:${fix.fence}`)) continue;+ const plan = mergePlan(extractRawRows(sections.get(fix.section) ?? '', fix.section), fix.fence);+ if (!plan) return null;+ plans.set(`${fix.section}:${fix.fence}`, plan);+ }+ return plans;+}++/** The receipt's `merged` entries for a repair whose fixes include `merge_fences`; undefined when none does. Location only. */+export function mergedReceipt(before: FencePage, fixes: readonly FenceFix[]): MergedFenceReceipt[] | undefined {+ const plans = mergePlans(before, fixes);+ if (!plans?.size) return undefined;+ return [...plans.values()].map(plan => ({+ fence: plan.kind, section: plan.section, fences: plan.fences.length,+ rows: plan.rows.map(r => ({+ occurrence: r.occurrence, from_fence: r.fence,+ ...(r.keptAs !== null ? { kept_as: r.keptAs } : { duplicate_of: plan.rows[r.duplicateOf!]!.keptAs! }),+ })),+ }));+}diff --git a/src/core/fence-repair/normalize.ts b/src/core/fence-repair/normalize.tsindex 7ccc68f8e3..15b480d921 100644--- a/src/core/fence-repair/normalize.ts+++ b/src/core/fence-repair/normalize.ts@@ -15,6 +15,7 @@* which turns a throw into the residual reason `normalizer_failed`.*/import { contentPass } from './content.ts';+import { beforeLine, type MergeOrigins } from './merge.ts';import { sectionsOf, strictFailures, strictPageClean } from './page-checks.ts';import { extractRawRows, rowNumOf } from './raw-rows.ts';import { strayCellPass } from './stray-cells.ts';@@ -22,7 +23,7 @@ import { structuralPass } from './structure.ts';import type { FenceCtx, FenceFix, FenceIssue, FencePage, FenceSection, StoredRowMap } from './types.ts';/** Rule-set version; bump when a rule widens. It is part of the hold `fence_version` (`FENCE_VERSION`), so older holds are re-screened. */-export const FENCE_RULES_VERSION = 2;+export const FENCE_RULES_VERSION = 3;export interface NormalizeResult<T extends FencePage> {page: T;@@ -40,16 +41,20 @@ export function normalizeFences<T extends FencePage>(page: T, ctx: FenceCtx): Noconst fixes: FenceFix[] = [];const residual: FenceIssue[] = [];const texts: Record<FenceSection, string> = { body: '', timeline: '' };+ const merges: MergeOrigins[] = [];for (const [section, text] of sectionsOf(page)) {const pass = structuralPass(text, section);const stray = strayCellPass(pass.text, section);texts[section] = stray.text;fixes.push(...pass.fixes, ...stray.fixes);residual.push(...pass.residual);+ merges.push(...pass.merges);}- const content = contentPass(texts, ctx, () => Math.max(nextFreeRowNum(page, ctx.storedRows), maxHidden(ctx) + 1));+ const content = contentPass(texts, ctx, () => Math.max(nextFreeRowNum(page, ctx.storedRows), maxHidden(ctx) + 1), merges);fixes.push(...content.fixes);residual.push(...content.residual);+ // Rows a merge moved are reported at their line in the before page, where the file still has them.+ if (merges.length) for (const item of [...fixes, ...residual]) item.line = beforeLine(merges, item);const out = withSections(page, content.texts);if (!residual.length) residual.push(...unparseable(out));return { page: out, fixes, residual };diff --git a/src/core/fence-repair/reasons.ts b/src/core/fence-repair/reasons.tsindex 80de5ad061..60565dee7b 100644--- a/src/core/fence-repair/reasons.ts+++ b/src/core/fence-repair/reasons.ts@@ -63,7 +63,7 @@ const SPECS: Record<FenceReason, Omit<FenceReasonSpec, 'docs'>> = {split_rows: entry(manual, 'The {fence} fence that begins at line {line} in the {section} has no end marker and its rows are split by blank lines or text. Join the rows into one table and add the end marker after the last row.'),unclosed_trailing_content: entry(manual, 'The {fence} fence that begins at line {line} in the {section} has no end marker and other text follows its table. Add the end marker directly after the last table row, or wrap the marker in backticks if the text only mentions it; gbrain does not guess where the fence ends.'),marker_near_miss: entry(manual, 'Line {line} of the {section} mentions the takes begin marker but is not a fence followed by a table. Wrap the mention in backticks, or use the exact three-dash marker above a takes table.'),- repeated_marker: entry(manual, 'The {section} repeats a {fence} fence marker (line {line}); a section holds at most one facts fence and one takes fence. Merge the fences into one or delete the extra marker.'),+ repeated_marker: entry(manual, 'The {section} repeats a {fence} fence marker (line {line}); a section holds at most one facts fence and one takes fence. gbrain merges the fences itself when each has a begin and an end marker, the same canonical header and nothing but table lines inside (`merge_fences`: later rows appended, exact duplicates dropped, colliding numbers renumbered). Otherwise, give the fence at line {line} both markers, the same header as the first fence, and move any other text out of it, or delete the extra marker.'),takes_in_facts: entry(manual, 'The {fence} fence in the {section} at line {line} holds a takes table. Move the rows into a takes fence (or use `takes_add`), or rewrite them as facts rows.'),superseded_ambiguous: entry(manual, 'Row number(s) {rows} appear more than once in the {fence} fence and a `superseded by` reference names them. Decide which row keeps each number, renumber the other and fix the reference.'),enum_unmapped: entry(manual, 'Column(s) {columns} of row(s) {rows} in the {fence} fence ({section}, line {line}) hold a value gbrain cannot map. Use one of {allowed}.'),diff --git a/src/core/fence-repair/receipt.ts b/src/core/fence-repair/receipt.tsindex bfbea41fe9..07e5f7c233 100644--- a/src/core/fence-repair/receipt.ts+++ b/src/core/fence-repair/receipt.ts@@ -4,14 +4,36 @@** The receipt rides the write's durable outcome (`fence_repair`): the actor* `fence-repair`, the tier, the fix classes with their rows and columns, the- * model (Tier 3 only), the sha256 of the bytes before and after, and the- * model spend. Location and hashes only: never a claim, holder or any other- * cell value, so it is safe in receipts, results and commit messages.+ * model (Tier 3 only), the sha256 of the bytes before and after, the model+ * spend and, for a `merge_fences` repair (#6377), where every before row+ * went. Location and hashes only: never a claim, holder or any other cell+ * value, so it is safe in receipts, results and commit messages.*/-import type { FenceTier } from './types.ts';+import type { FenceKind, FenceSection, FenceTier } from './types.ts';export const FENCE_REPAIR_ACTOR = 'fence-repair';+/** One fence `merge_fences` built: every before row by fence index and occurrence, and where it went. */+export interface MergedFenceReceipt {+ fence: FenceKind;+ section: FenceSection;+ /** How many fences of the kind the section held. */+ fences: number;+ rows: Array<{+ /** The row's occurrence in the fence it came from. */+ occurrence: number;+ /** Index of that fence in document order (0 is the primary). */+ from_fence: number;+ /** Occurrence in the merged fence. */+ kept_as?: number;+ /** Merged-fence occurrence of the kept row this exact duplicate equalled. */+ duplicate_of?: number;+ }>;+}++/** Most rows one merged fence records (an 85-row fence is the case this was built for). */+export const MERGED_ROWS_MAX = 2000;+export interface FenceRepairReceipt {actor: typeof FENCE_REPAIR_ACTOR;tier: Exclude<FenceTier, 'manual'>;@@ -25,6 +47,8 @@ export interface FenceRepairReceipt {after_sha256: string;/** Model spend for this page (USD); 0 for the free tiers, null for an unpriced model. */cost_usd: number | null;+ /** Where every row of each merged fence went (`merge_fences`); absent otherwise. */+ merged?: MergedFenceReceipt[];}const CLASS = /^[a-z_]{1,40}$/;@@ -42,8 +66,38 @@ export function parseFenceRepairReceipt(value: unknown): FenceRepairReceipt | nuif (r.model !== null && (typeof r.model !== 'string' || r.model.length > 200 || /[\r\n]/.test(r.model))) return null;if (typeof r.before_sha256 !== 'string' || !SHA.test(r.before_sha256) || typeof r.after_sha256 !== 'string' || !SHA.test(r.after_sha256)) return null;if (r.cost_usd !== null && (typeof r.cost_usd !== 'number' || !Number.isFinite(r.cost_usd) || r.cost_usd < 0)) return null;+ const merged = r.merged === undefined ? undefined : parseMerged(r.merged);+ if (merged === null) return null;return { actor: FENCE_REPAIR_ACTOR, tier: r.tier as FenceRepairReceipt['tier'], classes: [...r.classes as string[]], rows: [...r.rows as number[]],- columns: [...r.columns as string[]], model: r.model as string | null, before_sha256: r.before_sha256, after_sha256: r.after_sha256, cost_usd: r.cost_usd as number | null };+ columns: [...r.columns as string[]], model: r.model as string | null, before_sha256: r.before_sha256, after_sha256: r.after_sha256, cost_usd: r.cost_usd as number | null,+ ...(merged ? { merged } : {}) };+}++const index = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 0;++/** The `merged` entries: at most one per fence and section, each row sent to exactly one of `kept_as` / `duplicate_of`. */+function parseMerged(value: unknown): MergedFenceReceipt[] | null {+ if (!Array.isArray(value) || value.length > 4) return null;+ const out: MergedFenceReceipt[] = [];+ for (const entry of value) {+ if (!entry || typeof entry !== 'object') return null;+ const e = entry as Record<string, unknown>;+ if ((e.fence !== 'facts' && e.fence !== 'takes') || (e.section !== 'body' && e.section !== 'timeline')) return null;+ if (out.some(o => o.fence === e.fence && o.section === e.section)) return null;+ if (!index(e.fences) || e.fences < 2 || !Array.isArray(e.rows) || e.rows.length > MERGED_ROWS_MAX) return null;+ const rows: MergedFenceReceipt['rows'] = [];+ for (const row of e.rows) {+ if (!row || typeof row !== 'object') return null;+ const m = row as Record<string, unknown>;+ if (!index(m.occurrence) || !index(m.from_fence) || m.from_fence >= e.fences) return null;+ if ((m.kept_as === undefined) === (m.duplicate_of === undefined)) return null;+ if (m.kept_as !== undefined && !index(m.kept_as)) return null;+ if (m.duplicate_of !== undefined && !index(m.duplicate_of)) return null;+ rows.push({ occurrence: m.occurrence, from_fence: m.from_fence, ...(m.kept_as !== undefined ? { kept_as: m.kept_as } : { duplicate_of: m.duplicate_of as number }) });+ }+ out.push({ fence: e.fence, section: e.section, fences: e.fences, rows });+ }+ return out;}/** `gbrain: repair fence in <path> (<classes>)`, the subject of a repaired file's commit. */diff --git a/src/core/fence-repair/structure.ts b/src/core/fence-repair/structure.tsindex e89cbf3e5d..718528b34f 100644--- a/src/core/fence-repair/structure.ts+++ b/src/core/fence-repair/structure.ts@@ -1,6 +1,7 @@/**- * Structural Tier 1 rules for one section (#6188): `marker_form` (takes- * two-dash markers) and `close_fence` (a missing end marker).+ * Structural Tier 1 rules for one section (#6188): `merge_fences` (several+ * balanced fences of a kind, #6377, merge.ts), `marker_form` (takes two-dash+ * markers) and `close_fence` (a missing end marker).** `close_fence` inserts the end marker after the last table row only when* every row of the before-region is one contiguous block and nothing but@@ -10,6 +11,7 @@* is also checked against `exposedLines` before it is kept.*/import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';+import { mergeEdits, mergeOrigins, mergePlan, type MergeOrigins, type MergePlan } from './merge.ts';import { exposedLines } from './page-checks.ts';import { extractRawRows, MARKERS, parseRowSpans, primaryFence, type RawFence, type RawSection } from './raw-rows.ts';import type { FenceFix, FenceIssue, FenceReason, FenceSection, FixClass } from './types.ts';@@ -24,12 +26,16 @@ export interface PassResult {text: string;fixes: FenceFix[];residual: FenceIssue[];+ /** Row origins of every fence `merge_fences` built, for the content pass. */+ merges: MergeOrigins[];}interface Step {edits: Edit[];fixes: FenceFix[];residual: FenceIssue[];+ /** Merge plans whose edits were kept; their origins are read once the edits are applied. */+ merged: MergePlan[];}/** Apply non-overlapping edits (any order) to `text`. */@@ -43,11 +49,13 @@ export function applyEdits(text: string, edits: readonly Edit[]): string {export function structuralPass(text: string, section: FenceSection): PassResult {let current = text;const fixes: FenceFix[] = [];+ const merges: MergeOrigins[] = [];for (let round = 0; round < 3; round++) {const step = structuralStep(current, section);- if (!step.edits.length) return { text: current, fixes, residual: step.residual };+ if (!step.edits.length) return { text: current, fixes, residual: step.residual, merges };current = applyEdits(current, step.edits);fixes.push(...step.fixes);+ merges.push(...step.merged.map(plan => mergeOrigins(plan, current)));}throw new Error('fence structure rules did not settle');}@@ -60,10 +68,21 @@ export function fenceBlocked(raw: RawSection, fence: RawFence): boolean {function structuralStep(text: string, section: FenceSection): Step {const raw = extractRawRows(text, section);- const step: Step = { edits: [], fixes: [], residual: [] };+ const step: Step = { edits: [], fixes: [], residual: [], merged: [] };for (const kind of ['facts', 'takes'] as const) {const fence = primaryFence(raw, kind);- if (!fence || fenceBlocked(raw, fence)) continue;+ if (!fence) continue;+ const plan = mergePlan(raw, kind);+ if (plan) {+ // A merge that would show hidden text stays `repeated_marker`, which the content pass reports from the fence's issues.+ const edits = mergeEdits(text, plan);+ if (exposedLines(text, applyEdits(text, edits)).length) continue;+ step.edits.push(...edits);+ step.fixes.push({ fence: kind, section, row: null, column: null, line: fence.begin.line, class: 'merge_fences' });+ step.merged.push(plan);+ continue;+ }+ if (fenceBlocked(raw, fence)) continue;const edits = markerEdits(text, fence);if (edits === null) {step.residual.push(fenceIssue(fence, 'marker_near_miss', fence.begin.line));diff --git a/src/core/fence-repair/types.ts b/src/core/fence-repair/types.tsindex 2f02e9a148..4ce6553c7f 100644--- a/src/core/fence-repair/types.ts+++ b/src/core/fence-repair/types.ts@@ -22,6 +22,7 @@ export type GateLetter = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g';/** The class each applied fix carries in receipts, holds and previews. */export type FixClass =+ | 'merge_fences'| 'close_fence'| 'marker_form'| 'stray_empty_cell'diff --git a/src/core/fence-repair/validate.ts b/src/core/fence-repair/validate.tsindex f393fb0729..746dcb1122 100644--- a/src/core/fence-repair/validate.ts+++ b/src/core/fence-repair/validate.ts@@ -16,13 +16,24 @@* before-region, never strict-parser output. (e) runs before (b) so a dropped* or stranded row reports the row-count gate. Failures carry the reason, the* gate letter and row numbers only.+ *+ * Before rows pair with after rows by occurrence in the primary fence. When+ * the fixes name `merge_fences` for a section and kind (#6377), the pairing+ * is the merge mapping re-derived from the before page (`merge.ts`): every+ * fence's rows in document order, each kept at its merged occurrence or+ * dropped as an exact duplicate of a kept row. Gate (e) then accepts exactly+ * the dropped rows, each only when its cells equal the kept row's cells as+ * written; the other gates run row by row through the mapping; a+ * `superseded by #N` reference in a merged row may read the new number of+ * its own before-fence's row N. Without a merge fix nothing changes.*/+import { mergePlans, rowKey, type MergePlan } from './merge.ts';import { normalizeFences } from './normalize.ts';import { exposedLines, sectionsOf, strictFailures } from './page-checks.ts';import { extractRawRows, primaryFence, rowNumOf, type RawFence, type RawRow } from './raw-rows.ts';import { cellsChanged } from './validate-cells.ts';import { GATE_REASONS } from './reasons.ts';-import { cellValid, collapse, enumSynonym } from './schema.ts';+import { cellValid, collapse, enumSynonym, supersededRef } from './schema.ts';import type { FenceCtx, FenceKind, FenceLocation, FencePage, FenceReason, FenceSection, FenceTier, GateLetter } from './types.ts';export interface ValidateCtx extends FenceCtx {@@ -44,12 +55,24 @@ export type ValidateResult =rows: number[];};+/** One before row and the after row it pairs with (null for a dropped duplicate). */+interface Paired {+ row: RawRow;+ /** The before fence holding the row. */+ fence: RawFence;+ after: RawRow | null;+ /** The before row an exact duplicate was dropped for. */+ duplicateOf: Paired | null;+}+/** One fence kind in one section, before and after. */export interface FencePair {section: FenceSection;kind: FenceKind;before: RawFence | null;after: RawFence | null;+ /** Every before row in document order (all fences of the kind under a merge). */+ rows: Paired[];}type Failure = { gate: GateLetter; fence: FenceKind | null; section: FenceSection | null; rows: number[] };@@ -76,7 +99,8 @@ function firstFailure(before: FencePage, after: FencePage, ctx: ValidateCtx): Faconst f = strict[0]!;return { gate: 'a', fence: f.fence, section: f.section, rows: f.rows };}- const pairs = fencePairs(before, after);+ const pairs = fencePairs(before, after, ctx);+ if (!pairs) return { gate: 'e', fence: null, section: null, rows: [] };for (const check of [rowCount, claims, rowNumbers, visibility, cells]) {const failed = check(pairs, ctx);if (failed) return failed;@@ -84,17 +108,34 @@ function firstFailure(before: FencePage, after: FencePage, ctx: ValidateCtx): Fareturn protection(before, after);}-function fencePairs(before: FencePage, after: FencePage): FencePair[] {+/** Null when the fixes name a merge the before page does not admit (nothing the mapping could vouch for). */+function fencePairs(before: FencePage, after: FencePage, ctx: ValidateCtx): FencePair[] | null {+ const merges = mergePlans(before, ctx.issues.flatMap(i => ('class' in i && typeof i.class === 'string' ? [{ fence: i.fence, section: i.section, class: i.class }] : [])));+ if (!merges) return null;const afterSections = new Map(sectionsOf(after));return sectionsOf(before).flatMap(([section, text]) => {const b = extractRawRows(text, section);const a = extractRawRows(afterSections.get(section) ?? '', section);- return (['facts', 'takes'] as const).map(kind => ({ section, kind, before: primaryFence(b, kind), after: primaryFence(a, kind) }));+ return (['facts', 'takes'] as const).map(kind => {+ const pair: FencePair = { section, kind, before: primaryFence(b, kind), after: primaryFence(a, kind), rows: [] };+ const plan = merges.get(`${section}:${kind}`);+ pair.rows = plan ? mergedRows(plan, pair.after) : rowsOf(pair.before).map(row => ({ row, fence: pair.before!, after: rowsOf(pair.after)[row.occurrence] ?? null, duplicateOf: null }));+ return pair;+ });});}+function mergedRows(plan: MergePlan, after: RawFence | null): Paired[] {+ const afterRows = rowsOf(after);+ const paired: Paired[] = [];+ for (const r of plan.rows) {+ paired.push({ row: r.row, fence: plan.fences[r.fence]!, after: r.keptAs === null ? null : afterRows[r.keptAs] ?? null, duplicateOf: r.duplicateOf === null ? null : paired[r.duplicateOf]! });+ }+ return paired;+}+const rowsOf = (fence: RawFence | null): RawRow[] => fence?.rows ?? [];-const numOf = (fence: RawFence | null, row: RawRow | undefined): number | null => (fence && row ? rowNumOf(fence, row) : null);+const numOf = (fence: RawFence | null, row: RawRow | undefined | null): number | null => (fence && row ? rowNumOf(fence, row) : null);const claimOf = (row: RawRow): string => collapse(row.byColumn.get('claim')?.text ?? '');function numbers(fence: RawFence | null, rows: readonly RawRow[]): number[] {@@ -104,11 +145,15 @@ function numbers(fence: RawFence | null, rows: readonly RawRow[]): number[] {/** (e) */function rowCount(pairs: FencePair[]): Failure | null {for (const pair of pairs) {- const b = rowsOf(pair.before);+ const kept = pair.rows.filter(p => p.duplicateOf === null);const a = rowsOf(pair.after);- if (b.length === a.length) continue;- const longer = b.length > a.length ? { fence: pair.before, rows: b } : { fence: pair.after, rows: a };- return at(pair, 'e', numbers(longer.fence, longer.rows.slice(Math.min(a.length, b.length))));+ if (kept.length !== a.length) {+ const longer = kept.length > a.length ? { fence: pair.before, rows: kept.map(p => p.row) } : { fence: pair.after, rows: a };+ return at(pair, 'e', numbers(longer.fence, longer.rows.slice(Math.min(a.length, kept.length))));+ }+ // A dropped row is admitted only as an exact copy of its kept row, as both were written.+ const dropped = pair.rows.filter(p => p.duplicateOf !== null && rowKey(p.fence, p.row) !== rowKey(p.duplicateOf!.fence, p.duplicateOf!.row));+ if (dropped.length) return at(pair, 'e', dropped.map(p => numOf(p.fence, p.row)).filter((n): n is number => n !== null));}return null;}@@ -116,9 +161,8 @@ function rowCount(pairs: FencePair[]): Failure | null {/** (b) */function claims(pairs: FencePair[]): Failure | null {for (const pair of pairs) {- const a = rowsOf(pair.after);- const changed = rowsOf(pair.before).filter((row, k) => claimOf(row) !== claimOf(a[k]!));- if (changed.length) return at(pair, 'b', numbers(pair.after, changed.map(r => a[r.occurrence]!)));+ const changed = pair.rows.filter(p => p.after && claimOf(p.row) !== claimOf(p.after));+ if (changed.length) return at(pair, 'b', numbers(pair.after, changed.map(p => p.after!)));}return null;}@@ -127,10 +171,10 @@ function claims(pairs: FencePair[]): Failure | null {function rowNumbers(pairs: FencePair[]): Failure | null {for (const kind of ['facts', 'takes'] as const) {const of = pairs.filter(p => p.kind === kind);- const before = of.flatMap(p => rowsOf(p.before).map(row => ({ num: numOf(p.before, row), claim: claimOf(row), pair: p })));+ const before = of.flatMap(p => p.rows.map(r => ({ num: numOf(r.fence, r.row), claim: claimOf(r.row), dropped: r.duplicateOf !== null, pair: p })));const after = new Set(of.flatMap(p => rowsOf(p.after).map(row => `${numOf(p.after, row)}\u0000${claimOf(row)}`)));for (const row of before) {- if (row.num === null || before.filter(r => r.num === row.num).length > 1) continue;+ if (row.num === null || row.dropped || before.filter(r => r.num === row.num).length > 1) continue;if (!after.has(`${row.num}\u0000${row.claim}`)) return at(row.pair, 'c', [row.num]);}}@@ -140,11 +184,9 @@ function rowNumbers(pairs: FencePair[]): Failure | null {/** (d) */function visibility(pairs: FencePair[], ctx: ValidateCtx): Failure | null {for (const pair of pairs.filter(p => p.kind === 'facts')) {- const a = rowsOf(pair.after);- for (const row of rowsOf(pair.before)) {- const after = a[row.occurrence]!;- if (after.byColumn.get('visibility')?.text.trim().toLowerCase() !== 'world') continue;- if (!mayBecomeWorld(row, ctx)) return at(pair, 'd', numbers(pair.after, [after]));+ for (const p of pair.rows) {+ if (!p.after || p.after.byColumn.get('visibility')?.text.trim().toLowerCase() !== 'world') continue;+ if (!mayBecomeWorld(p.row, ctx)) return at(pair, 'd', numbers(pair.after, [p.after]));}}return null;@@ -162,15 +204,39 @@ function mayBecomeWorld(row: RawRow, ctx: ValidateCtx): boolean {/** (f) */function cells(pairs: FencePair[], ctx: ValidateCtx): Failure | null {for (const pair of pairs) {- const a = rowsOf(pair.after);- for (const row of rowsOf(pair.before)) {- const after = a[row.occurrence]!;- if (cellsChanged(pair, row, after, ctx).length) return at(pair, 'f', numbers(pair.after, [after]));+ for (const p of pair.rows) {+ if (!p.after) continue;+ if (cellsChanged(pair, withFollowedRef(pair, p), p.after, ctx).length) return at(pair, 'f', numbers(pair.after, [p.after]));}}return null;}+/**+ * Under a merge, a `superseded by #N` reference in a before row may follow+ * the one row numbered N of the row's own before fence (kept, or the kept+ * row its exact duplicate equalled) to that row's after number: the before+ * row is compared as if written with the new number. Any other reference+ * change fails gate (f) as a changed cell.+ */+function withFollowedRef(pair: FencePair, p: Paired): RawRow {+ if (pair.rows.every(r => r.fence === pair.before)) return p.row;+ const column = pair.kind === 'facts' ? 'context' : 'source';+ const cell = p.row.byColumn.get(column);+ const ref = cell ? supersededRef(cell.text) : null;+ if (ref === null) return p.row;+ const own = pair.rows.filter(r => r.fence === p.fence && numOf(r.fence, r.row) === ref);+ if (own.length !== 1) return p.row;+ const target = own[0]!.duplicateOf ?? own[0]!;+ const now = numOf(pair.after, target.after);+ if (now === null || now === ref) return p.row;+ const rewrite = (text: string) => text.replace(/(superseded by #)\d+/i, `$1${now}`);+ const followed = { ...cell!, text: rewrite(cell!.text), raw: rewrite(cell!.raw) };+ const byColumn = new Map(p.row.byColumn);+ byColumn.set(column, followed);+ return { ...p.row, byColumn, cells: p.row.cells.map(c => (c === cell ? followed : c)) };+}+/** (g) */function protection(before: FencePage, after: FencePage): Failure | null {const afterSections = new Map(sectionsOf(after));diff --git a/src/core/repair/fences.ts b/src/core/repair/fences.tsindex 109af92834..9c79c580e6 100644--- a/src/core/repair/fences.ts+++ b/src/core/repair/fences.ts@@ -55,8 +55,9 @@ import { readGitSourceHolds, recordFenceHoldRepair } from '../persistence/sync-himport { attemptStore } from '../fence-repair/attempts.ts';import { listFenceCandidates, runFenceCensus, type FenceCandidate } from '../fence-repair/census.ts';import { fenceRepairLlmEnabled, readFenceRepairCaps } from '../fence-repair/config.ts';+import { mergedReceipt } from '../fence-repair/merge.ts';import { FENCE_REASONS } from '../fence-repair/reasons.ts';-import { FENCE_REPAIR_ACTOR } from '../fence-repair/receipt.ts';+import { FENCE_REPAIR_ACTOR, type MergedFenceReceipt } from '../fence-repair/receipt.ts';import { checkoutFileExists, loadFenceSource, pageSha, readFenceTarget, spliceFileSections, writeFenceRepair, type FenceRepairMode, type FenceSource, type FenceTarget } from '../fence-repair/repair-io.ts';import type { OwnerRefusal } from '../persistence/owner-refusal.ts';import { repairBusy, repairBusyMessage } from '../persistence/repair-busy.ts';@@ -447,7 +448,7 @@ async function applyFence(ctx: OperationContext, entry: ApprovedFence, opts: Appif (analysis.status === 'proposal') {const bytes = afterBytes(target, analysis.after);if (opts.expect && bytes?.sha !== entry.after) return skipped('changed_since_preview', `The repair of ${entry.path ?? entry.slug} differs from the preview; preview again.`);- return write(ctx, src, target, analysis.after, { tier: analysis.tier, classes: classesOf(analysis.fixes), ...fixLocation(analysis.fixes, []), model: null, cost: 0 }, opts, heldOutcome);+ return write(ctx, src, target, analysis.after, { tier: analysis.tier, classes: classesOf(analysis.fixes), ...fixLocation(analysis.fixes, []), model: null, cost: 0, merged: mergedReceipt(target.page, analysis.fixes) }, opts, heldOutcome);}return tier3(ctx, src, target, analysis, entry, opts, heldOutcome);}@@ -455,9 +456,9 @@ async function applyFence(ctx: OperationContext, entry: ApprovedFence, opts: Apptype HeldFn = (reason: string, message: string, extra?: { gate?: GateLetter; rows?: number[]; next?: string | null; tier?: FenceTier }) => Promise<RepairItemOutcome>;async function write(ctx: OperationContext, src: FenceSource, target: FenceTarget, after: FencePage,- r: { tier: RepairTier; classes: string[]; rows: number[]; columns: string[]; model: string | null; cost: number | null }, opts: ApplyOptions, held: HeldFn): Promise<RepairItemOutcome> {- const outcome = await writeFenceRepair(ctx, src, target, after, { actor: FENCE_REPAIR_ACTOR, tier: r.tier, classes: r.classes, rows: r.rows, columns: r.columns, model: r.model, cost_usd: r.cost },- { embed: opts.embed });+ r: { tier: RepairTier; classes: string[]; rows: number[]; columns: string[]; model: string | null; cost: number | null; merged?: MergedFenceReceipt[] | undefined }, opts: ApplyOptions, held: HeldFn): Promise<RepairItemOutcome> {+ const outcome = await writeFenceRepair(ctx, src, target, after, { actor: FENCE_REPAIR_ACTOR, tier: r.tier, classes: r.classes, rows: r.rows, columns: r.columns, model: r.model, cost_usd: r.cost,+ ...(r.merged ? { merged: r.merged } : {}) }, { embed: opts.embed });if (!outcome.ok) {if (outcome.reason === 'changed_since_read') return { applied: false, outcome: 'skipped', reason: 'changed_since_read', detail: { path: target.path, slug: target.slug, mode: target.mode, message: outcome.message } };if (outcome.reason === 'sync_in_progress') {@@ -499,8 +500,8 @@ async function tier3(ctx: OperationContext, src: FenceSource, target: FenceTargeinputs: [{ name: 'usd', how: 'The new daily cap in USD the user agrees to; it must exceed what is already spent today.' }],verify: { argv: ['gbrain', 'doctor', '--only', 'fence_integrity', '--json'] } } } };}- const written = await write(ctx, src, target, result.after, { tier: 'llm', classes: classesOf(analysis.fixes, result.cleared), ...fixLocation(analysis.fixes, analysis.residual), model, cost: result.spentUsd },- opts, held);+ const written = await write(ctx, src, target, result.after, { tier: 'llm', classes: classesOf(analysis.fixes, result.cleared), ...fixLocation(analysis.fixes, analysis.residual), model, cost: result.spentUsd,+ merged: mergedReceipt(target.page, analysis.fixes) }, opts, held);const store = attemptStore(engine);if (written.applied) await store.publish(result.claim);else if (written.reason === 'changed_since_read' || written.reason === 'sync_in_progress') await store.transient(result.claim, written.reason);diff --git a/test/fence-refusal.test.ts b/test/fence-refusal.test.tsindex 2821a322e4..94f98fc3f1 100644--- a/test/fence-refusal.test.ts+++ b/test/fence-refusal.test.ts@@ -48,8 +48,8 @@ const cases: Array<[name: string, body: string, timeline: string, expected: Reco['duplicate row across sections', facts(fact(6)), facts(fact(6)), { reason: 'row_collision', fence: 'facts', section: 'timeline', rows: [6] }],];-/** The cases Tier 1 fixes losslessly (#6188): a missing end marker with nothing after the table, two-dash takes markers, an invented facts kind, duplicate row numbers. */-const TIER1_FIXABLE = new Set(['missing end marker', 'two-dash takes markers', 'unknown facts kind', 'duplicate row in one fence', 'duplicate row across sections']);+/** The cases Tier 1 fixes losslessly (#6188, #6377): a missing end marker with nothing after the table, two-dash takes markers, two balanced fences of a kind, an invented facts kind, duplicate row numbers. */+const TIER1_FIXABLE = new Set(['missing end marker', 'two-dash takes markers', 'repeated marker', 'unknown facts kind', 'duplicate row in one fence', 'duplicate row across sections']);describe('the shared fence check', () => {test('a clean page, a page without fences, a fence quoted in code and a lone end marker (the projection reads none) pass the check', () => {diff --git a/test/fence-repair-fixtures.test.ts b/test/fence-repair-fixtures.test.tsindex 77cb231733..1cbfd857c7 100644--- a/test/fence-repair-fixtures.test.ts+++ b/test/fence-repair-fixtures.test.ts@@ -71,11 +71,14 @@ 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[] {+/** Claims of every fence of a kind in document order; `distinct` keeps each claim's first occurrence (what a `merge_fences` dedupe leaves). */+function rawClaims(page: FencePage, distinct = false): 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'));+ return (['facts', 'takes'] as const).map(kind => {+ const claims = raw.fences.filter(f => f.kind === kind).flatMap(f => f.rows).map(r => r.byColumn.get('claim')?.text.replace(/\s+/g, ' ').trim() ?? '');+ return `${section}:${kind}:` + (distinct ? [...new Set(claims)] : claims).join('\u0001');+ });});}@@ -112,7 +115,8 @@ describe('fence fixtures in the test suite', () => {continue;}expect(normalizeFences(r.page, PRIVATE).fixes).toEqual([]);- expect(rawClaims(r.page)).toEqual(rawClaims(before));+ const merged = r.fixes.some(f => f.class === 'merge_fences');+ expect(rawClaims(r.page, merged)).toEqual(rawClaims(before, merged));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 });diff --git a/test/fence-repair-merge.test.ts b/test/fence-repair-merge.test.tsnew file mode 100644index 0000000000..d97f3d6d34--- /dev/null+++ b/test/fence-repair-merge.test.ts@@ -0,0 +1,247 @@+/**+ * Tier 1 `merge_fences` (#6377): a section with several balanced fences of+ * a kind becomes one fence; the validator checks the result row by row+ * through the merge mapping; the receipt carries the mapping location-only.+ * 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 { normalizeFences } from '../src/core/fence-repair/normalize.ts';+import { mergedReceipt } from '../src/core/fence-repair/merge.ts';+import { strictPageClean } from '../src/core/fence-repair/page-checks.ts';+import { FENCE_REPAIR_ACTOR, parseFenceRepairReceipt, type FenceRepairReceipt } from '../src/core/fence-repair/receipt.ts';+import { FENCE_REASONS, renderFenceFix } from '../src/core/fence-repair/reasons.ts';+import { fenceStep } from '../src/core/fence-repair/tier1.ts';+import { validateFenceRepair } from '../src/core/fence-repair/validate.ts';+import type { FenceCtx, FencePage, FenceReason } 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 factsRow = (n: string | number, claim: string, o: Partial<Record<'kind' | 'conf' | 'vis' | 'ctx', string>> = {}) =>+ `| ${n} | ${claim} | ${o.kind ?? 'fact'} | ${o.conf ?? '1.0'} | ${o.vis ?? 'private'} | medium | 2026-01-01 | | call | ${o.ctx ?? ''} |`;+const takesRow = (n: string | number, claim: string, o: Partial<Record<'who' | 'w' | 'src', string>> = {}) =>+ `| ${n} | ${claim} | take | ${o.who ?? 'brain'} | ${o.w ?? '0.5'} | 2026-01 | ${o.src ?? 'notes'} |`;+const facts = (rows: string[], heading = '## Facts', header = FH) => [heading, '', FB, '', header, 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(before: FencePage, ctx: FenceCtx = PRIVATE) {+ return { before, ...normalizeFences(before, ctx) };+}+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();+const validate = (r: ReturnType<typeof run>, after: FencePage = r.page, ctx: FenceCtx = PRIVATE) =>+ validateFenceRepair(r.before, after, { ...ctx, tier: 'deterministic', issues: [...r.fixes, ...r.residual] });++/** A clean Tier 1 repair: no residual, compiles, passes every gate, fixed point. */+function expectRepaired(r: ReturnType<typeof run>, ctx: FenceCtx = PRIVATE) {+ expect(r.residual).toEqual([]);+ expect(strictPageClean(r.page)).toBe(true);+ expect(validate(r, r.page, ctx)).toEqual({ ok: true });+ expect(normalizeFences(r.page, ctx).fixes).toEqual([]);+}++/** The issue's shape: a 3-row fence, then an 85-row fence under a second `## Facts` heading. */+const FIRST = [factsRow(1, 'Alpha claim'), factsRow(2, 'Beta claim'), factsRow(3, 'Gamma claim')];+const SECOND: string[] = [];+for (let i = 1; i <= 85; i++) {+ if (i === 1) SECOND.push(factsRow(1, 'Omega claim')); // collides with #1+ else if (i === 2) SECOND.push(factsRow(2, 'Beta claim')); // exact duplicate, same number+ else if (i === 3) SECOND.push(factsRow(3, 'Delta claim')); // collides with #3+ else if (i === 40) SECOND.push(factsRow(40, 'Alpha claim')); // exact duplicate, other number+ else if (i === 41) SECOND.push(factsRow(41, 'Gamma claim')); // exact duplicate, other number+ else if (i === 50) SECOND.push(factsRow(50, '~~Old fifty~~', { ctx: 'superseded by #3' })); // names this fence's #3+ else SECOND.push(factsRow(i, `Claim ${i}`));+}+const ISSUE_BODY = [facts(FIRST), facts(SECOND)].join('\n');++describe('merge_fences', () => {+ test('two balanced facts fences merge into one: duplicates dropped, collisions renumbered, the reference follows, the second heading goes', () => {+ const r = run(page(ISSUE_BODY));+ expect(classes(r)).toEqual(['merge_fences', 'renumber']);+ expectRepaired(r);+ const expected = [...FIRST, factsRow(86, 'Omega claim'), factsRow(87, 'Delta claim'),+ ...SECOND.slice(3).filter((_, k) => ![40 - 4, 41 - 4].includes(k)).map(line => line.replace('superseded by #3', 'superseded by #87'))];+ expect(r.page.compiled_truth).toBe(facts(expected));+ const parsed = parseFactsFence(r.page.compiled_truth);+ expect(parsed.warnings).toEqual([]);+ expect(parsed.facts.length).toBe(85);+ expect(parsed.facts.find(f => f.rowNum === 50)).toMatchObject({ active: false, supersededBy: 87 });+ expect(parsed.facts.find(f => f.rowNum === 87)!.claim).toBe('Delta claim');+ // Fixes name the before page's lines: the merge at the primary begin marker, each renumber at the row in the second fence.+ expect(r.fixes).toEqual([+ { fence: 'facts', section: 'body', row: null, column: null, line: 3, class: 'merge_fences' },+ { fence: 'facts', section: 'body', row: 86, column: '#', line: 18, class: 'renumber', from: 1 },+ { fence: 'facts', section: 'body', row: 87, column: '#', line: 20, class: 'renumber', from: 3 },+ { fence: 'facts', section: 'body', row: 50, column: 'context', line: 67, class: 'renumber' },+ ]);+ expect(JSON.stringify([r.fixes, r.residual])).not.toMatch(/claim|Alpha|Omega/i);+ });++ test('the receipt mapping names every before row by fence and occurrence, kept or duplicate, and parses back', () => {+ const r = run(page(ISSUE_BODY));+ const merged = mergedReceipt(r.before, r.fixes)!;+ expect(merged).toHaveLength(1);+ expect(merged[0]).toMatchObject({ fence: 'facts', section: 'body', fences: 2 });+ expect(merged[0]!.rows).toHaveLength(88);+ expect(merged[0]!.rows.slice(0, 5)).toEqual([+ { occurrence: 0, from_fence: 0, kept_as: 0 }, { occurrence: 1, from_fence: 0, kept_as: 1 }, { occurrence: 2, from_fence: 0, kept_as: 2 },+ { occurrence: 0, from_fence: 1, kept_as: 3 }, { occurrence: 1, from_fence: 1, duplicate_of: 1 },+ ]);+ expect(merged[0]!.rows.filter(row => row.duplicate_of !== undefined)).toEqual([+ { occurrence: 1, from_fence: 1, duplicate_of: 1 }, { occurrence: 39, from_fence: 1, duplicate_of: 0 }, { occurrence: 40, from_fence: 1, duplicate_of: 2 },+ ]);+ expect(merged[0]!.rows.filter(row => row.kept_as !== undefined)).toHaveLength(85);+ expect(JSON.stringify(merged)).not.toMatch(/claim/i);+ const receipt: FenceRepairReceipt = { actor: FENCE_REPAIR_ACTOR, tier: 'deterministic', classes: ['merge_fences', 'renumber'], rows: [50, 86, 87], columns: ['#', 'context'],+ model: null, before_sha256: 'a'.repeat(64), after_sha256: 'b'.repeat(64), cost_usd: 0, merged };+ expect(parseFenceRepairReceipt(JSON.parse(JSON.stringify(receipt)))).toEqual(receipt);+ const { merged: _omitted, ...plain } = receipt;+ expect(parseFenceRepairReceipt(plain)).toEqual(plain);+ for (const bad of [+ [{ ...merged[0], rows: [{ occurrence: 0, from_fence: 0, kept_as: 0, duplicate_of: 1 }] }],+ [{ ...merged[0], rows: [{ occurrence: 0, from_fence: 0 }] }],+ [{ ...merged[0], rows: [{ occurrence: 0, from_fence: 2, kept_as: 0 }] }],+ [{ ...merged[0], fences: 1 }],+ [merged[0], merged[0]],+ 'merged',+ ]) expect(parseFenceRepairReceipt({ ...receipt, merged: bad })).toBeNull();+ expect(mergedReceipt(page(facts(FIRST)), [])).toBeUndefined();+ });++ test('the coordinated write step admits the merged page as a Tier 1 normalization', () => {+ const step = fenceStep(page(ISSUE_BODY), PRIVATE, { normalize: true });+ expect(step.status).toBe('normalized');+ if (step.status === 'normalized') expect(step.fixes.map(f => f.class)).toContain('merge_fences');+ const off = fenceStep(page(ISSUE_BODY), PRIVATE, { normalize: false });+ expect(off.status).toBe('residual');+ if (off.status === 'residual') expect(off.fixable.map(f => f.class)).toContain('merge_fences');+ });++ test('(b) a claim mutated in the second fence is rejected through the mapping', () => {+ const r = run(page(ISSUE_BODY));+ const after = page(r.page.compiled_truth.replace(factsRow(70, 'Claim 70'), factsRow(70, 'Claim 70, edited')));+ expect(validate(r, after)).toMatchObject({ ok: false, gate: 'b', reason: 'claim_changed', fence: 'facts', section: 'body', rows: [70] });+ });++ test('(e) a dropped row that is not an exact duplicate is rejected', () => {+ const r = run(page(ISSUE_BODY));+ const after = page(r.page.compiled_truth.replace(`${factsRow(70, 'Claim 70')}\n`, ''));+ expect(validate(r, after)).toMatchObject({ ok: false, gate: 'e', reason: 'row_count_changed', fence: 'facts', section: 'body' });+ });++ test('(e) a duplicate the mapping does not name cannot be dropped, and the mapping is re-derived from the before page', () => {+ const body = [facts([factsRow(1, 'Alpha claim')]), facts([factsRow(2, 'Alpha claim', { conf: '0.9' }), factsRow(3, 'Beta claim')])].join('\n');+ const r = run(page(body));+ expect(parseFactsFence(r.page.compiled_truth).facts.map(f => [f.rowNum, f.confidence])).toEqual([[1, 1], [2, 0.9], [3, 1]]);+ expectRepaired(r);+ const dropped = page(facts([factsRow(1, 'Alpha claim'), factsRow(3, 'Beta claim')]));+ expect(validate(r, dropped)).toMatchObject({ ok: false, gate: 'e', rows: [3] });+ // A merge fix claimed for a page with one fence has no mapping to vouch for it.+ const single = page(facts([factsRow(1, 'Alpha claim')]));+ expect(validateFenceRepair(single, single, { ...PRIVATE, tier: 'deterministic', issues: r.fixes })).toMatchObject({ ok: false, gate: 'e' });+ });++ test('(f) a reference may follow only its own fence\'s renumbered row; any other reference change is a changed cell', () => {+ const r = run(page(ISSUE_BODY));+ const stray = page(r.page.compiled_truth.replace('superseded by #87', 'superseded by #86'));+ expect(validate(r, stray)).toMatchObject({ ok: false, gate: 'f', reason: 'cell_changed', rows: [50] });+ const unchanged = page(r.page.compiled_truth.replace('superseded by #87', 'superseded by #3'));+ expect(validate(r, unchanged)).toMatchObject({ ok: false, gate: 'f', rows: [50] });+ });++ test('a reference to a dropped duplicate follows the kept row; a kind_map rewrite and the reference share one context cell', () => {+ const body = [facts(FIRST), facts([factsRow(40, 'Alpha claim'), factsRow(41, '~~Old~~', { kind: 'signal', ctx: 'superseded by #40' })])].join('\n');+ const r = run(page(body));+ expect(classes(r)).toEqual(['kind_map', 'merge_fences', 'renumber']);+ expectRepaired(r);+ const old = parseFactsFence(r.page.compiled_truth).facts.find(f => f.rowNum === 41)!;+ expect(old).toMatchObject({ active: false, supersededBy: 1, kind: 'fact', context: 'superseded by #1; original kind: signal' });+ });++ test('near-duplicates (same claim, different confidence) are both kept', () => {+ const body = [facts([factsRow(1, 'Alpha claim')]), facts([factsRow(1, 'Alpha claim', { conf: '0.7' })])].join('\n');+ const r = run(page(body));+ expect(classes(r)).toEqual(['merge_fences', 'renumber']);+ expect(parseFactsFence(r.page.compiled_truth).facts.map(f => [f.rowNum, f.claim, f.confidence])).toEqual([[1, 'Alpha claim', 1], [2, 'Alpha claim', 0.7]]);+ expectRepaired(r);+ });++ test('a stored row keeps its number, as the renumber rule decides', () => {+ const body = [facts([factsRow(1, 'Alpha claim')]), facts([factsRow(1, 'Stored claim')])].join('\n');+ const stored: FenceCtx = { pageVisibility: 'private', storedRows: { facts: new Map([[1, 'Stored claim']]), takes: new Map() } };+ const r = run(page(body), stored);+ expect(parseFactsFence(r.page.compiled_truth).facts.map(f => [f.rowNum, f.claim])).toEqual([[2, 'Alpha claim'], [1, 'Stored claim']]);+ expectRepaired(r, stored);+ });++ test('takes fences merge the same way', () => {+ const body = [takes([takesRow(1, 'Alpha take'), takesRow(2, 'Beta take')]), takes([takesRow(2, 'Beta take'), takesRow(3, 'Gamma take'), takesRow(1, 'Delta take', { src: 'superseded by #2' })])].join('\n');+ const r = run(page(body));+ expect(classes(r)).toEqual(['merge_fences', 'renumber']);+ expect(r.page.compiled_truth).toBe(takes([takesRow(1, 'Alpha take'), takesRow(2, 'Beta take'), takesRow(3, 'Gamma take'), takesRow(4, 'Delta take', { src: 'superseded by #2' })]));+ expect(parseTakesFence(r.page.compiled_truth).takes.map(t => [t.rowNum, t.claim])).toEqual([[1, 'Alpha take'], [2, 'Beta take'], [3, 'Gamma take'], [4, 'Delta take']]);+ expectRepaired(r);+ });++ test('three fences, a heading that differs, prose between fences and CRLF endings', () => {+ const body = [facts([factsRow(1, 'Alpha claim')]), 'Prose between the fences.', '', facts([factsRow(2, 'Beta claim')], '## More facts'), facts([factsRow(3, 'Gamma claim')]), 'Trailing prose.', '']+ .join('\n').replace(/\n/g, '\r\n');+ const r = run(page(body));+ expect(classes(r)).toEqual(['merge_fences']);+ expect(r.page.compiled_truth).toBe(['## Facts', '', FB, '', FH, FS, factsRow(1, 'Alpha claim'), factsRow(2, 'Beta claim'), factsRow(3, 'Gamma claim'), FE, '', 'Prose between the fences.', '',+ '## More facts', '', 'Trailing prose.', ''].join('\r\n'));+ expectRepaired(r);+ expect(mergedReceipt(r.before, r.fixes)![0]).toMatchObject({ fences: 3 });+ });++ test('the merged page is held `repeated_marker` no longer; the reason table says gbrain merges and names the edit otherwise', () => {+ expect(FENCE_REASONS.repeated_marker.tier).toBe('manual');+ const fix = renderFenceFix({ reason: 'repeated_marker', fence: 'facts', section: 'body', rows: [], columns: [], line: 12 });+ expect(fix).toContain('merge_fences');+ expect(fix).toContain('line 12');+ expect(FENCE_REASONS.repeated_marker.fix).not.toMatch(/\{(?!fence|section|line|rows|columns|allowed)\w+\}/);+ });+});++describe('what stays repeated_marker (manual, nothing changes)', () => {+ const cases: Array<[string, string]> = [+ ['an unbalanced repeat', [facts(FIRST), ['## Facts', '', FB, '', FH, FS, factsRow(9, 'Theta claim'), ''].join('\n')].join('\n')],+ ['a header that does not map', [facts(FIRST), facts([factsRow(9, 'Theta claim')], '## Facts', FH.replace('| notability |', '| salience |'))].join('\n')],+ ['a header in another column order', [facts(FIRST), facts([factsRow(9, 'Theta claim')], '## Facts', FH.replace('| # | claim |', '| claim | # |'))].join('\n')],+ ['stray text inside the repeated fence', [facts(FIRST), facts([factsRow(9, 'Theta claim'), 'A note inside the fence.'])].join('\n')],+ ['stray text inside the primary fence', [facts([...FIRST, 'A note inside the fence.']), facts([factsRow(9, 'Theta claim')])].join('\n')],+ ['a marker sharing its line with text', [facts(FIRST), facts([factsRow(9, 'Theta claim')]).replace(FE, `${FE} trailing words`)].join('\n')],+ ['a repeat whose rows sit above its header', [facts(FIRST), ['## Facts', '', FB, factsRow(9, 'Theta claim'), FH, FS, FE, ''].join('\n')].join('\n')],+ ['a stray end marker besides the two fences', [facts(FIRST), facts([factsRow(9, 'Theta claim')]), FE, ''].join('\n')],+ ];+ for (const [name, body] of cases) {+ test(name, () => {+ const r = run(page(body));+ expect(reasons(r)).toContain('repeated_marker');+ expect(r.fixes.map(f => f.class)).not.toContain('merge_fences');+ expect(r.page.compiled_truth).toBe(body);+ expect(FENCE_REASONS.repeated_marker.manualOnly).toBe(true);+ });+ }++ test('a facts fence in the body and one in the timeline are two sections, not a repeat: nothing merges', () => {+ const before = page(facts(FIRST), facts([factsRow(9, 'Theta claim')]));+ const r = run(before);+ expect(r.page).toBe(before);+ expect(r.fixes).toEqual([]);+ expect(strictPageClean(before)).toBe(true);+ });++ test('a page with a single fence is untouched', () => {+ const before = page(facts(FIRST));+ expect(normalizeFences(before, PRIVATE).page).toBe(before);+ const dirty = page(facts([factsRow(1, 'Alpha claim', { kind: 'signal' })]));+ expect(classes(run(dirty))).toEqual(['kind_map']);+ });+});diff --git a/test/fence-repair-normalize.test.ts b/test/fence-repair-normalize.test.tsindex 52fab66c57..69a497cb7a 100644--- a/test/fence-repair-normalize.test.ts+++ b/test/fence-repair-normalize.test.ts@@ -166,8 +166,8 @@ describe('close_fence and the protection boundary', () => {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');+ test('a repeated marker that merge_fences cannot merge (text inside the repeat) is manual and nothing changes', () => {+ const body = [facts(factsRow(1, 'Alpha two', { kind: 'signal' })), facts(factsRow(2, 'Beta two'), 'A note inside the fence.')].join('\n');const r = run(body);expect(reasons(r)).toContain('repeated_marker');expect(r.page.compiled_truth).toBe(body);