Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(fence-repair): act on the Tier 3 eval: measured key-aware model default, HOLD declines, structural-only re-ask, reasoning budget, stray empty cells, split claims held (#6188)
garrytan7d75e08c83a5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a4af416bc2..e747431621 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,7 +14,7 @@ identifiers and attribution are available in the pre-removal Git revision**Broken facts and takes tables in your notes now get repaired by themselves.**-The last three releases stopped a broken table from blocking a sync, fixed the ones with only one possible meaning, and made `gbrain doctor` count the rest. This release repairs the rest. The background maintenance run now works through every broken table it finds, each with the cheapest method that is exactly right: fixed rules first, then holder names checked against your own people and company pages, and only for a table whose columns are scrambled, the chat model you configured. The model sees only that table's header and the rows it has to move, never the rest of the page, and it may move cells but never change what they say. Model spend has a hard cap of $0.05 per page and $1.00 per day. Every repair is committed with a message naming the file, so `git revert` undoes it.+The last three releases stopped a broken table from blocking a sync, fixed the ones with only one possible meaning, and made `gbrain doctor` count the rest. This release repairs the rest. The background maintenance run now works through every broken table it finds, each with the cheapest method that is exactly right: fixed rules first, then holder names checked against your own people and company pages, and only for a table whose columns are scrambled, a chat model. The model sees only that table's header and the rows it has to move, never the rest of the page; it may move cells but never change what they say, and it says HOLD instead of guessing when a row could be read two ways. By default gbrain uses a model it measured as accurate enough on this job, and only if you have that provider's key; otherwise the model step stays off until you pick one. Model spend has a hard cap of $0.30 per page and $1.00 per day. Every repair is committed with a message naming the file, so `git revert` undoes it.### How to use it@@ -35,11 +35,13 @@ gbrain config set fences.repair.llm false # keep table rows away from the mo| Managed sources | Each repaired file is committed as `gbrain: repair fence in <path> (<classes>)`. || Other sources | The original file is backed up under `~/.gbrain/backups/fences/` before the write, and `gbrain sources status` plus doctor show the repair until you commit it. || Held files | Every `invalid_fence` hold and the doctor `fence_integrity` fix point at the `gbrain repair fences` preview (`--only <path>` for one file). A table only a person can decide still names the exact edit. |-| Model choice | `models.fence_repair` picks the model (listed in `gbrain models`). |+| Model choice | `models.fence_repair` picks the model, and a model you set always runs. Unset, gbrain uses `openai:gpt-6.1-sol` when it has an OpenAI key, else `anthropic:claude-fable-5-1` when it has an Anthropic key, else no model (those tables wait as `no_measured_model`). `gbrain models` shows which. |+| Stray cells | A row with an extra empty cell is lined up by a free rule when exactly one cell can go. A row whose extra cells hold text, or a facts kind cell that holds a sentence, is held for a person: usually an unescaped `\|` cut the claim in two, and no check can tell that from a misplaced cell. |### Things to watch- How often the model's rewrites pass the checks is not measured yet.+- Each model call reserves its worst case, including room for a reasoning model to think, so the per-page cap is $0.30; measured spend was about $0.02 per repaired table on the most expensive default model.- A model gbrain has no price for still runs under the default caps, metered at the highest chat rate gbrain knows; under a cap you set, it waits until you register its price with `gbrain pricing set`.- When the daily cap runs out, repair stops and the remaining tables wait until 00:00 UTC; the run says when and how many.- Turning the settings off stops future repairs and does not undo past ones. A broken table you restore is held again on the next sync and repaired again by the next maintenance run, so pause first if you want to keep it.@@ -47,7 +49,9 @@ gbrain config set fences.repair.llm false # keep table rows away from the mo### Itemized changes- `src/core/repair/fences.ts`: the `fences` repair kind (preview-bound, `spends: 'llm'`). Candidates come from the fence census after a bounded scan (`GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s); `--only`, `--skip` and `--slug` also reach files and pages the census has not judged yet. A candidate whose source is owned by another host (`owner_unavailable`) or mid-sync (`sync_in_progress`) is skipped, and every candidate is re-read before any fix runs.-- Holder names (`src/core/fence-repair/repair-tiers.ts`) resolve strictly, without same-name guessing, only to `people/` and `companies/` pages, and never to a private page from a world-visible one. A model repair claims the attempt memo, checks the per-page cap and the run's allowance, reserves on the daily ledger before each call and settles the real tokens after; a rewrite the checks rejected for unchanged bytes is never paid for again. The call (`src/core/fence-repair/llm.ts`) uses no tools, no fallback model and no temperature, and gets at most one corrective re-ask.+- Holder names (`src/core/fence-repair/repair-tiers.ts`) resolve strictly, without same-name guessing, only to `people/` and `companies/` pages, and never to a private page from a world-visible one. A model repair claims the attempt memo, checks the per-page cap and the run's allowance, reserves on the daily ledger before each call and settles the real tokens after; a rewrite the checks rejected, or a HOLD (`llm_declined`), is never paid for again for unchanged bytes. The call (`src/core/fence-repair/llm.ts`, prompt version 2) uses no tools, no fallback model and no temperature; its output ceiling adds 2,048 tokens for a model whose reasoning the call cannot turn off, and the estimate uses the ceiling the gateway sends. It gets one corrective re-ask only when the answer does not parse or changes the row count; any other gate rejection is final. A headerless table of 14-cell rows is sent with the wide header.+- The model default (`src/core/fence-repair/model.ts`, `measured.ts`): `models.fence_repair` when set; else the first of the measured models (`openai:gpt-6.1-sol`, `anthropic:claude-fable-5-1`) whose provider key the brain has; else none (`no_measured_model`, a paid hold whose fix sets `models.fence_repair`). `openai:gpt-6.1-sol` joins the price table at $2/$10 per million tokens and stays out of OpenAI tier-default discovery. `fences.repair.max_usd_per_page` defaults to $0.30 (was $0.05), the largest worst-case page estimate of the measured models on the eval's fixtures being $0.27.+- Tier 1 `stray_empty_cell` (`src/core/fence-repair/stray-cells.ts`) removes empty cells from a row with too many only when exactly one removal makes every checked column valid. `extra_cells` is now manual, and a facts `kind_map` reads only a kind word (at most three words, no sentence punctuation, link or strikethrough); anything else is `claim_split`, manual. `FENCE_RULES_VERSION` is 2, so older holds are screened again.- Every rewrite passes the same validation gates as the inline repair, plus a fixed-point check, before it is written. A misaligned cell whose text is unchanged is now moved to the column it belongs to rather than rejected.- Write-back (`src/core/fence-repair/repair-io.ts`): managed sources go through `managed_file_repair` with a location-only `fence_repair` receipt checked at submission and again when prepared (remote callers are refused); other checkouts are confined, re-hashed (`changed_since_read`), backed up, written and imported, with the backup restored if the import refuses; database-only pages and mirrors get a revision-bound write.- Repair kinds can carry a per-item model cost (the preview estimate follows `--limit`, and an apply stops before an item it cannot afford), a deadline and an early stop. `--expect` works for every preview-bound kind; `--max-usd` only for kinds that call a paid model, and only lowers the cap.@@ -56,7 +60,7 @@ gbrain config set fences.repair.llm false # keep table rows away from the mo### For contributors-- `test/repair-fences.test.ts` (PGLite, and Postgres through `test/postgres-unit-arms.txt`) covers preview then the printed apply across all three fix methods, rejected rewrites never paid twice, transient errors, `--no-llm`, unpriced models under default and user caps, the budget stop, every skip reason, mirrors, remote refusal, backups and the uncommitted notice, doctor remediation budgets, the time budget, two concurrent appliers at the cap and the cycle phase across ticks, with a privacy sentinel throughout. `test/fence-repair-llm.test.ts` pins the prompt bytes; `test/fence-walkthrough.test.ts` checks the guide's walkthrough line by line against a local provider stand-in.+- `test/repair-fences.test.ts` (PGLite, and Postgres through `test/postgres-unit-arms.txt`) covers preview then the printed apply across all three fix methods, rejected rewrites never paid twice, transient errors, `--no-llm`, unpriced models under default and user caps, the budget stop, every skip reason, mirrors, remote refusal, backups and the uncommitted notice, doctor remediation budgets, the time budget, two concurrent appliers at the cap and the cycle phase across ticks, with a privacy sentinel throughout. `test/fence-repair-llm.test.ts` pins the prompt bytes and covers HOLD, the structural-only re-ask, the wide headerless layout and the reasoning allowance; `test/fence-repair-normalize.test.ts` covers stray empty cells and split claims; `test/fence-walkthrough.test.ts` checks the guide's walkthrough line by line against a local provider stand-in. `evals/fence-repair-tier3/` is the Tier 3 measurement instrument (78 hand-written fixtures, a production-path runner, a $0 oracle and the scorer); `test/eval-fence-repair-tier3.test.ts` guards it without a key.## [0.60.100.0] - 2026-10-07diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex a7032a1a4b..eba4f0ef3e 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -12,7 +12,9 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `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. `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; pinned by a prompt-bytes digest and `FENCE_REPAIR_PROMPT_VERSION`), `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_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. Tests: `test/fence-repair-llm.test.ts`, `test/repair-fences.test.ts`.+- `src/core/fence-repair/{llm,repair-tiers}.ts` — #6188 Tier 2 and Tier 3 for one candidate. `analyzeFences`: Tier 1 (`safeNormalizeFences`, stored rows loaded only for `renumber`), Tier 2 (`resolveStrictEntityReference` without the same-name arm per `holder_unresolved` cell, only `people/`/`companies/` slugs, private pages excluded on a world page; hits feed `verifiedHolders`), then `proposal` (validated by gates (a)-(g) and a fixed point), `llm` (only `TIER3_REASONS` residuals left; a fence with stray text lines or no end marker is not eligible) or `manual`. `llm.ts`: `tier3Requests` (per fence: the header line and the residual rows, every row for a fence-level issue), `buildTier3Prompt` (schema, vocabulary, reason codes, page visibility, and rule 8: answer `HOLD` when a row has more than one reasonable reading; pinned by a prompt-bytes digest and `FENCE_REPAIR_PROMPT_VERSION`, 2), the layout (wide when the header names a wide column or, headerless, a row as written is wider than the narrow layout), `tier3TokenBudget` (the table's size plus `TIER3_REASONING_TOKENS` for a model whose reasoning the call cannot switch off, raised to the gateway's thinking headroom where the route has no switch: the estimate reserves what the gateway sends), `callTier3` (gateway `chat`, no tools, no fallback, thinking off; `llm_unavailable` when the provider throws, `llm_refused`, `llm_truncated` for any stop but a normal end, `llm_declined` for HOLD, `llm_malformed`/`llm_empty` from `extractSingleTable`, a wrong row count is a gate (e) failure), `spliceTier3` (rebuilds only that fence: canonical header, then every row in order with the sent rows replaced). `runTier3` claims the attempt (a rejected memo returns its verdict), checks the per-page cap and the run allowance, reserves on the daily ledger before each call (a refusal stops the run), settles actual tokens (an answerless call at its estimate), normalizes and validates the spliced page against the bytes as read, and re-asks once with the failed gate letter and rows only after a structural failure (gate (a) or (e)); any other gate or a HOLD is final and consumes the memo. `TIER3_REASONS` is the reason table's screen reasons of tier `llm`. Tests: `test/fence-repair-llm.test.ts`, `test/repair-fences.test.ts`.+- `src/core/fence-repair/stray-cells.ts` — #6188 Tier 1 `stray_empty_cell` (`strayCellPass`, run by `normalizeFences` after the structural pass): in a balanced primary fence with a canonical header, a row with more cells than the layout loses empty cells (slot removed, every other byte kept) only when exactly one distinct deletion leaves every validated column valid; otherwise it stays `extra_cells`, now manual. `rules.ts` `kindWord` keeps facts `kind_map` to a kind word (at most three words, no sentence punctuation, link or strikethrough); other text is `claim_split` (manual), never a kind note. Tests: `test/fence-repair-normalize.test.ts`.+- `src/core/fence-repair/{measured,model}.ts` — #6188 the Tier 3 eval's verdicts and the model they pick. `measured.ts`: `FENCE_REPAIR_MEASURED_MODELS` (the models that met the preregistered rule, best first) and `FENCE_REPAIR_MEASURED` (the behavior notice's accuracy sentence), updated together by the next eval. `model.ts`: `resolveFenceRepairModel(WithSource)`: an explicit `models.fence_repair` always (any model, priced or not); unset, the first measured model whose provider key the merged env has; else null (`no_measured_model`, a paid hold whose fix is `gbrain config set models.fence_repair <model>`). `gbrain models` reports the row through it (`measured default`). Tests: `test/repair-fences.test.ts`.- `src/core/fence-repair/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource`: managed owner root (or `ownerElsewhere`), legacy checkout, mirror flag, unfinished managed sync cursor and the paths/slugs pending writes name. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `git add`/`git commit` step, dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.- `src/core/fence-repair/attempts.ts` — #6188 attempt claims and the attempt memo for paid (Tier 3) fence repairs, one `op_checkpoints` row per candidate (op `fence-repair-attempt`) changed only by compare-and-swap on a record version: `claimed` → `dispatched` → `settled` → `published` | `rejected` | `transient`, at most one paid call plus one corrective re-ask per claim. A rejected or published memo (content sha256, model, fence rules version, prompt version) is not claimed again until one changes; transient failures do not consume it; an expired lease is taken over (a stale dispatch counts a crash, two reject the memo). Records carry location and reason codes and their source incarnation, so the purge keeps them while it lives. Tests: `test/fence-repair-attempts.test.ts` (+ Postgres e2e).- `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`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex d7774061cc..16a5d07485 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -10,7 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`).- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).-- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a non-owner host is `owner_unavailable`, an unfinished managed sync cursor or a pending write naming it is `sync_in_progress` (E9); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `models.fence_repair` (`resolveFenceRepairModel`, tier `deep`). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, one corrective re-ask); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.+- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a non-owner host is `owner_unavailable`, an unfinished managed sync cursor or a pending write naming it is `sync_in_progress` (E9); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`.- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 80926cc007..990618e5f6 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1294,7 +1294,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| A facts or takes fence in the page cannot be imported without dropping or guessing rows, so the page (or the file) was not written. | Facts and takes fences are the page's structured rows. Importing a fence that does not parse, repeats a marker or reuses a row number would silently drop or renumber rows, so coordinated writers refuse it and managed sync holds the one file while the rest of the source syncs. | A refused write: fix the fence the message names (fence, section and rows; the reason says what is wrong) and send the page again with a new request_id, or write rows with remember / takes_add. A held file or stored page: the maintenance run repairs it; preview it now with gbrain repair fences --source <id> on the brain host. | agent | `repeat the read that failed` | 1 | no |-Reasons: `header_unmapped`, `no_header`, `row_before_header`, `short_row`, `extra_cells`, `holder_unresolved`, `missing_begin`, `split_rows`, `unclosed_trailing_content`, `marker_near_miss`, `repeated_marker`, `takes_in_facts`, `superseded_ambiguous`, `enum_unmapped`, `weight_missing`, `holder_missing`, `confidence_out_of_range`, `claim_value_invalid`, `takes_kind_unsupported`, `unparseable`, `row_collision`, `quoted_fence_rows`, `stored_row_collision`, `withdrawn_claim_in_malformed_fence`, `target_fence_malformed`, `prepare_time`, `normalizer_failed`, `llm_unavailable`, `llm_empty`, `llm_refused`, `llm_malformed`, `llm_truncated`, `llm_disabled`, `budget_exhausted`, `no_pricing`, `ledger_unavailable`, `owner_unavailable`, `owner_cli_required`, `sync_in_progress`, `time_budget`, `changed_since_read`, `changed_since_preview`, `still_invalid`, `claim_changed`, `row_number_changed`, `visibility_loosened`, `row_count_changed`, `cell_changed`, `protection_loosened`.+Reasons: `header_unmapped`, `no_header`, `row_before_header`, `short_row`, `extra_cells`, `claim_split`, `holder_unresolved`, `missing_begin`, `split_rows`, `unclosed_trailing_content`, `marker_near_miss`, `repeated_marker`, `takes_in_facts`, `superseded_ambiguous`, `enum_unmapped`, `weight_missing`, `holder_missing`, `confidence_out_of_range`, `claim_value_invalid`, `takes_kind_unsupported`, `unparseable`, `row_collision`, `quoted_fence_rows`, `stored_row_collision`, `withdrawn_claim_in_malformed_fence`, `target_fence_malformed`, `prepare_time`, `normalizer_failed`, `llm_unavailable`, `llm_empty`, `llm_refused`, `llm_malformed`, `llm_truncated`, `llm_declined`, `llm_disabled`, `no_measured_model`, `budget_exhausted`, `no_pricing`, `ledger_unavailable`, `owner_unavailable`, `owner_cli_required`, `sync_in_progress`, `time_budget`, `changed_since_read`, `changed_since_preview`, `still_invalid`, `claim_changed`, `row_number_changed`, `visibility_loosened`, `row_count_changed`, `cell_changed`, `protection_loosened`.More: [docs/guides/write-refusals.md#invalid_fence](../../docs/guides/write-refusals.md#invalid_fence)diff --git a/docs/guides/fence-format.md b/docs/guides/fence-format.mdindex 7f55c1282f..162e858445 100644--- a/docs/guides/fence-format.md+++ b/docs/guides/fence-format.md@@ -170,11 +170,12 @@ These rules run on every write path for free. They edit or move cell text and ne| --- | --- || `close_fence` | A fence with no end marker gets one directly after its table, when nothing but blank lines follows the last row up to the end of the section. || `marker_form` | Two-dash takes markers (`<!-- gbrain:takes:begin -->`) directly above a takes table become the three-dash markers. Two-dash facts markers are not a fence and are left alone. |+| `stray_empty_cell` | A row with more cells than its header loses empty cells, only when exactly one choice of empty cells to remove leaves every checked column (`#`, kind, confidence, visibility, notability, `claim_value`; takes kind, holder, weight) valid. Otherwise the row is `extra_cells` and a person fixes it. || `renumber` | A row number that is zero, negative, not a number or a duplicate gets a new number (see [row numbers](#row-numbers)). || `column_default` | A required facts column missing from the whole header gets its write default: `confidence` `1.0`, `notability` `medium`, `visibility` `private`. Takes have no defaults; a takes fence with no weight is `weight_missing`. || `header_alias` | A header whose every column has a known spelling (see [header spellings](#header-spellings)) becomes the canonical header, and each row's cells move into canonical order unchanged. || `enum_synonym` | Facts notability `critical`, `very high`, `highest` → `high`; `very low`, `minor` → `low`; visibility `internal`, `team`, `confidential`, `restricted`, `secret`, `shared` → `private`, and `public` → `world` only on a world-visible page (`private` otherwise); case and spacing variants of a canonical value. Any other word is `enum_unmapped`. |-| `kind_map` | Facts: `proposal`, `suggestion`, `hypothesis` → `idea`; `opinion`, `view`, `insight`, `assessment`, `frame` → `belief`; `promise`, `pledge` → `commitment`; `meeting`, `launch`, `announcement`, `milestone` → `event`; any other word → `fact`, with the word kept in `context` (for example `original kind: partnership`). Takes: `assessment`, `recommendation`, `strategic position`, `opinion`, `view` → `take`; `prediction`, `forecast` → `bet`; `guess`, `intuition` → `hunch`; any other word is `takes_kind_unsupported`, because gbrain never chooses a takes kind. |+| `kind_map` | Facts: `proposal`, `suggestion`, `hypothesis` → `idea`; `opinion`, `view`, `insight`, `assessment`, `frame` → `belief`; `promise`, `pledge` → `commitment`; `meeting`, `launch`, `announcement`, `milestone` → `event`; any other word → `fact`, with the word kept in `context` (for example `original kind: partnership`). A facts kind cell longer than three words, or with sentence punctuation, a link or strikethrough, is not read as a kind: it is `claim_split`, usually the end of a claim an unescaped `|` cut in two. Takes: `assessment`, `recommendation`, `strategic position`, `opinion`, `view` → `take`; `prediction`, `forecast` → `bet`; `guess`, `intuition` → `hunch`; any other word is `takes_kind_unsupported`, because gbrain never chooses a takes kind. || `holder_alias` | Takes holder `system`, `assistant`, `ai`, `agent`, `gbrain`, `model` (any case) → `brain`. || `confidence_format` | A percent or a number with stray spaces in `confidence` or `weight` becomes a decimal: `85%` → `0.85`, `0. 8` → `0.8`. A number outside 0 to 1 is `confidence_out_of_range`. || `holder_verified` | Tier 2, not Tier 1: a takes holder written as a name becomes the one `people/` or `companies/` page it resolves to exactly. On a world-visible page a private page never matches. Anything less certain stays `holder_unresolved`. |@@ -216,9 +217,9 @@ Header cells are compared case-insensitively, with spaces, `_` and `-` treated aA problem the rules above cannot fix exactly is held or refused with a reason. The reason says which tier clears it:-- **llm** (Tier 3, the configured chat model rewrites only the named rows): [`header_unmapped`](write-refusals.md#fence-header_unmapped), [`no_header`](write-refusals.md#fence-no_header), [`row_before_header`](write-refusals.md#fence-row_before_header), [`short_row`](write-refusals.md#fence-short_row), [`extra_cells`](write-refusals.md#fence-extra_cells).+- **llm** (Tier 3, the repair model rewrites only the named rows, or answers HOLD when a row has two readings): [`header_unmapped`](write-refusals.md#fence-header_unmapped), [`no_header`](write-refusals.md#fence-no_header), [`row_before_header`](write-refusals.md#fence-row_before_header), [`short_row`](write-refusals.md#fence-short_row).- **resolver** (Tier 2, verified holder lookup, free): [`holder_unresolved`](write-refusals.md#fence-holder_unresolved).-- **manual** (a person edits the fence; gbrain never guesses): [`missing_begin`](write-refusals.md#fence-missing_begin), [`split_rows`](write-refusals.md#fence-split_rows), [`unclosed_trailing_content`](write-refusals.md#fence-unclosed_trailing_content), [`marker_near_miss`](write-refusals.md#fence-marker_near_miss), [`repeated_marker`](write-refusals.md#fence-repeated_marker), [`takes_in_facts`](write-refusals.md#fence-takes_in_facts), [`superseded_ambiguous`](write-refusals.md#fence-superseded_ambiguous), [`enum_unmapped`](write-refusals.md#fence-enum_unmapped), [`weight_missing`](write-refusals.md#fence-weight_missing), [`holder_missing`](write-refusals.md#fence-holder_missing), [`confidence_out_of_range`](write-refusals.md#fence-confidence_out_of_range), [`claim_value_invalid`](write-refusals.md#fence-claim_value_invalid), [`takes_kind_unsupported`](write-refusals.md#fence-takes_kind_unsupported).+- **manual** (a person edits the fence; gbrain never guesses): [`extra_cells`](write-refusals.md#fence-extra_cells), [`claim_split`](write-refusals.md#fence-claim_split), [`missing_begin`](write-refusals.md#fence-missing_begin), [`split_rows`](write-refusals.md#fence-split_rows), [`unclosed_trailing_content`](write-refusals.md#fence-unclosed_trailing_content), [`marker_near_miss`](write-refusals.md#fence-marker_near_miss), [`repeated_marker`](write-refusals.md#fence-repeated_marker), [`takes_in_facts`](write-refusals.md#fence-takes_in_facts), [`superseded_ambiguous`](write-refusals.md#fence-superseded_ambiguous), [`enum_unmapped`](write-refusals.md#fence-enum_unmapped), [`weight_missing`](write-refusals.md#fence-weight_missing), [`holder_missing`](write-refusals.md#fence-holder_missing), [`confidence_out_of_range`](write-refusals.md#fence-confidence_out_of_range), [`claim_value_invalid`](write-refusals.md#fence-claim_value_invalid), [`takes_kind_unsupported`](write-refusals.md#fence-takes_kind_unsupported).<a id="gates"></a>### Gates every repair passesdiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 9d38f0cba0..28152c961a 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -841,18 +841,25 @@ Each candidate gets the cheapest tier that repairs it exactly:| Tier | What it does | Cost || --- | --- | --- |-| `deterministic` | The lossless rules every write already runs (missing end marker, row numbers, header aliases and order, enum and kind synonyms, assistant holders, percent confidences). | Free. |+| `deterministic` | The lossless rules every write already runs (missing end marker, stray empty cells with one valid removal, row numbers, header aliases and order, enum and kind synonyms, assistant holders, percent confidences). | Free. || `resolver` | A holder written as a display name becomes the `people/` or `companies/` page it names, only on an exact match (slug, unique slug basename or alias; never a guess, never a private page on a world-visible page). | Free. |-| `llm` | Rows only a rewrite can realign (no header, a header column with no canonical name, rows above the header, short rows, extra cells). The configured chat model (`models.fence_repair`) sees only the fence header and those rows, never valid rows of a row-level problem and never the rest of the page, with no tools. | Paid, within `fences.repair.max_usd_per_page` ($0.05) and `fences.repair.max_usd_per_day` ($1.00). |-| `manual` | Anything gbrain never guesses (a stray end marker, an unknown takes kind, a weight out of range, a holder no page matches). The preview names the exact edit. | Your edit. |+| `llm` | Rows only a rewrite can realign (no header, a header column with no canonical name, rows above the header, short rows). The repair model sees only the fence header and those rows, never valid rows of a row-level problem and never the rest of the page, with no tools, and answers HOLD instead of guessing when a row has two readings. | Paid, within `fences.repair.max_usd_per_page` ($0.30) and `fences.repair.max_usd_per_day` ($1.00). |+| `manual` | Anything gbrain never guesses (a stray end marker, an unknown takes kind, a weight out of range, a holder no page matches, extra cells that removing empty cells cannot line up, a sentence in the facts `kind` column). The preview names the exact edit. | Your edit. |Every proposal, whichever tier made it, must pass the validation[gates (a) to (g)](fence-format.md#gates) against the bytes as read (claims,existing row numbers and valid cells unchanged, no row more visible, nothing thefence hid shown) and be a normalizer fixed point, or it is not written. A model-proposal a gate rejects gets one corrective re-ask naming the gate and rows;-if that fails too the file stays held with the gate, and the same bytes are-never sent again until the file, the model or the rules change.+proposal that does not parse or changes the row count (gates (a) and (e)) gets+one corrective re-ask naming the gate and rows; any other gate rejection, a+HOLD, or a failed re-ask leaves the file held, and the same bytes are never+sent again until the file, the model or the rules change.++The repair model is `models.fence_repair` when set. Unset, it is the first+model the fence-repair eval measured as accurate enough whose provider key the+brain has: `openai:gpt-6.1-sol`, then `anthropic:claude-fable-5-1`. With+neither key, model-tier fences wait as `no_measured_model` until the user+picks a model.The session below is real output (volatile ids, hashes and times shown as`<id>`, `<hash>`, `<time>`; `test/fence-walkthrough.test.ts` runs these@@ -902,15 +909,15 @@ exists). An older gbrain blocked the source on the first fence it refused.```console$ gbrain repair fences --source notes- cost: 2 request ID(s), 32768 receipt bytes, 2 page(s) to re-embed, paid model ~$0.0112 ($1.0000 left under today's cap)- llm: notes:companies/acme-example.md (no_header; rewritten by openai:gpt-5.5 at apply time, gated by (a)-(g); est. $0.0112)+ cost: 2 request ID(s), 32768 receipt bytes, 2 page(s) to re-embed, paid model ~$0.0273 ($1.0000 left under today's cap)+ llm: notes:companies/acme-example.md (no_header; rewritten by openai:gpt-6.1-sol at apply time, gated by (a)-(g); est. $0.0273)resolver: notes:projects/widget-launch.md (holder_verified; rows 1)- tiers: deterministic=0, resolver=1, llm=1, held=0; model openai:gpt-5.5- model caps: $0.05/page, $1.00/day ($1.0000 left today)+ tiers: deterministic=0, resolver=1, llm=1, held=0; model openai:gpt-6.1-sol+ model caps: $0.30/page, $1.00/day ($1.0000 left today)-| 1 | The launch slips a week | bet | Alice Example | 0.6 | 2026-04 | standup |+| 1 | The launch slips a week | bet | people/alice-example | 0.6 | 2026-04 | standup |next: gbrain repair fences --source notes --apply --expect <hash>- Kinds that may call a paid model: fences (estimated $0.0112; $1.0000 left under today's cap).+ Kinds that may call a paid model: fences (estimated $0.0273; $1.0000 left under today's cap).```5. Apply exactly the previewed set. A file that changed since the preview is@@ -919,7 +926,7 @@ exists). An older gbrain blocked the source on the first fence it refused.```console$ gbrain repair fences --source notes --apply --expect <hash>- cost: 2 request ID(s), 32768 receipt bytes, 2 page(s) to re-embed, paid model $0.0072 spent ($0.9928 left under today's cap)+ cost: 2 request ID(s), 32768 receipt bytes, 2 page(s) to re-embed, paid model $0.0039 spent ($0.9961 left under today's cap)applied 2, skipped 0, completerepaired 2; nothing left in this selectionrepaired: notes:companies/acme-example tier=llm, classes=no_header, slug=companies/acme-example, mode=managed, path=companies/acme-example.md, imported=created, hold_cleared=true, committed=queued@@ -948,7 +955,7 @@ exists). An older gbrain blocked the source on the first fence it refused.```One command got the source syncing again (the sync), and two repaired the rest-(preview, apply), for $0.0072 of model spend.+(preview, apply), for $0.0039 of model spend.Selection and output:@@ -1009,9 +1016,9 @@ the next maintenance run, so pause first if you want to keep the original.| --- | --- | --- || `fences.repair.enabled` | `true` | `false` pauses the maintenance run's repair; `gbrain repair fences --apply` still works. || `fences.repair.llm` | `true` | `false` keeps every repair to the free tiers; model-tier holds stay `llm_disabled`. |-| `fences.repair.max_usd_per_page` | `0.05` | The most one page may spend on the model (one call plus one corrective re-ask). `0` means no model spend. |+| `fences.repair.max_usd_per_page` | `0.30` | The most one page may spend on the model, checked against each call's worst case (the prompt plus the full output ceiling, with 2,048 tokens for a reasoning model to think). `0` means no model spend. || `fences.repair.max_usd_per_day` | `1.00` | The most all processes together spend per UTC day, through a durable ledger. `0` means no model spend. |-| `models.fence_repair` | the `deep` tier | The model Tier 3 calls (`gbrain models` shows it). A model gbrain has no price for runs under the default caps at an estimated ceiling (the highest chat rate gbrain knows; `gbrain pricing set` makes it exact) and waits for its price under a cap you set. |+| `models.fence_repair` | unset: the first measured model with a key (`openai:gpt-6.1-sol`, then `anthropic:claude-fable-5-1`), else none | The model Tier 3 calls (`gbrain models` shows it). A model you set always runs; one gbrain has no price for runs under the default caps at an estimated ceiling (the highest chat rate gbrain knows; `gbrain pricing set` makes it exact) and waits for its price under a cap you set. || `fences.normalize` | `true` | `false` stops the inline rewrite on writes and syncs: a fixable fence is held or refused like any other. |## Resumediff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 86c215802c..372b1c6f8f 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -241,8 +241,9 @@ columns, the tier that fixes it and the estimated model cost against theremaining daily cap, and prints the apply command with its `--expect` hash.Applying needs no extra consent. Tier 1 and 2 changes are exact rules; Tier 3sends only the fence header and the rows it must realign (never valid rows,-never the rest of the page) to the configured chat model-(`models.fence_repair`), within `fences.repair.max_usd_per_page` ($0.05) and+never the rest of the page) to the repair model (`models.fence_repair`, or+unset the first measured model with a key: `openai:gpt-6.1-sol`, then+`anthropic:claude-fable-5-1`), within `fences.repair.max_usd_per_page` ($0.30) and`fences.repair.max_usd_per_day` ($1.00) ([spend](../operations/spend-controls.md#the-gates)).Every tier's output passes [gates (a) to (g)](fence-format.md#gates) beforeanything is written. `--no-llm` keeps a run to the free tiers and@@ -273,7 +274,7 @@ holder name to resolve), `llm` (a table only a rewrite can realign) and`manual` (an edit only a person can decide). It also shows the oldest hold'sage, the fences normalized in the last 7 days with their top writers (asource at 20 or more warns: something keeps writing malformed fences) and the-model-repair caps `fences.repair.max_usd_per_page` (default $0.05) and+model-repair caps `fences.repair.max_usd_per_page` (default $0.30) and`fences.repair.max_usd_per_day` (default $1.00) with today's spend. Each runscans for at most `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (10 s) and resumes where thelast one stopped; until a scan finishes the check is `partial` and never `ok`.@@ -293,7 +294,8 @@ clears or retries it with no one acting.| <a id="fence-no_header"></a>`no_header` | The fence has table rows but no header row naming `claim` and `kind`. | `llm` | yes | Repaired by the next maintenance run. By hand: add the canonical header as the first table line. Format: [markers](fence-format.md#markers). || <a id="fence-row_before_header"></a>`row_before_header` | Rows sit above the header row. | `llm` | yes | Repaired by the next maintenance run. By hand: move them below the header. Format: [markers](fence-format.md#markers). || <a id="fence-short_row"></a>`short_row` | A row is missing a cell in the middle, so its columns are ambiguous. A row short only in its optional trailing cells parses. | `llm` | yes | Repaired by the next maintenance run. By hand: add the missing cells so every column lines up. Format: [facts](fence-format.md#facts-layouts), [takes](fence-format.md#takes-layouts). |-| <a id="fence-extra_cells"></a>`extra_cells` | A row has more cells than the header, often an unescaped `\|` in a cell. | `llm` | yes | Repaired by the next maintenance run. By hand: escape the pipe as `\|` or remove the extra cell. Format: [facts](fence-format.md#facts-layouts), [takes](fence-format.md#takes-layouts). |+| <a id="fence-extra_cells"></a>`extra_cells` | A row has more cells than the header, and removing empty cells does not line it up (stray empty cells with one valid removal are rewritten by themselves). Often an unescaped `\|` cut a cell, usually the claim, in two; no gate can tell that from a misplaced cell, so it is never sent to the model. | `manual` | no | Join the cut cell with `\|`, or remove the extra cell. Format: [facts](fence-format.md#facts-layouts), [takes](fence-format.md#takes-layouts). |+| <a id="fence-claim_split"></a>`claim_split` | A facts `kind` cell holds text, not a kind word (more than three words, sentence punctuation, a link or strikethrough): usually the end of a claim an unescaped `\|` cut in two, with the kind cell missing. gbrain does not store it as a kind note. | `manual` | no | Join the text back into the claim with `\|` and write the kind. Format: [facts](fence-format.md#facts-columns). || <a id="fence-holder_unresolved"></a>`holder_unresolved` | A takes `who` cell is not `world`, `brain`, `people/<slug>` or `companies/<slug>` (for example a person's display name). | `resolver` | yes | Rewritten by the next maintenance run when it resolves to exactly one verified `people/` or `companies/` page (never a private page on a world-visible page). Otherwise write one of those forms by hand. Format: [holders](fence-format.md#holders). || <a id="fence-missing_begin"></a>`missing_begin` | An end marker has no begin marker before it. | `manual` | no | Add the begin marker above the table, or delete the stray end marker. Format: [markers](fence-format.md#markers). || <a id="fence-split_rows"></a>`split_rows` | A fence has no end marker and its rows are split by blank lines or text, so gbrain cannot tell which rows belong to it. | `manual` | no | Join the rows into one table and add the end marker after the last row. Format: [markers](fence-format.md#markers). |@@ -321,7 +323,9 @@ clears or retries it with no one acting.| <a id="fence-llm_refused"></a>`llm_refused` | The repair model declined to repair the fence. | `llm` | no | Fix the named rows by hand; the same file is not sent to the model again until it or the model changes. Format: [tiers](fence-format.md#never-guessed). || <a id="fence-llm_malformed"></a>`llm_malformed` | The repair model did not return exactly one table, or wrote text outside it. | `llm` | no | Fix the named rows by hand; the same file is not sent to the model again until it or the model changes. Format: [tiers](fence-format.md#never-guessed). || <a id="fence-llm_truncated"></a>`llm_truncated` | The repair model stopped before finishing; its output is rejected even when it parses. | `llm` | no | Fix the named rows by hand; the same file is not sent to the model again until it or the model changes. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-llm_declined"></a>`llm_declined` | The repair model answered HOLD: a row has more than one reasonable reading (two values for one column, or a cell that fits two columns), so it declined to guess. | `llm` | no | Fix the named rows by hand; the same file is not sent to the model again until it, the model or the rules change. Format: [tiers](fence-format.md#never-guessed). || <a id="fence-llm_disabled"></a>`llm_disabled` | Model repair is off (`fences.repair.llm false`), so a fence only Tier 3 can realign waits. | `llm` | no | Fix the named rows by hand, or ask the user before turning model repair back on: `gbrain config set fences.repair.llm true` (it spends within the caps). Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-no_measured_model"></a>`no_measured_model` | `models.fence_repair` is unset and no model the fence-repair eval measured as accurate enough (`openai:gpt-6.1-sol`, then `anthropic:claude-fable-5-1`) has a provider key on this brain, so model repair is off by default. | `llm` | no | Fix the named rows by hand, or ask the user which model to trust, then `gbrain config set models.fence_repair <provider:model>` (an explicit model always runs). Format: [tiers](fence-format.md#never-guessed). || <a id="fence-budget_exhausted"></a>`budget_exhausted` | The page's repair estimate is over `fences.repair.max_usd_per_page` or over what is left of `fences.repair.max_usd_per_day` today (UTC). A repair run stops with exit 1 naming the spend, the cap, the reset time (next 00:00 UTC) and the pages waiting. | `llm` | yes | Nothing to do: repairs resume after 00:00 UTC. Raising a cap is the user's call: `gbrain config set fences.repair.max_usd_per_day <usd>` (or `fences.repair.max_usd_per_page`). Format: [tiers](fence-format.md#never-guessed). || <a id="fence-no_pricing"></a>`no_pricing` | A spend cap the user set is in force and gbrain has no price for the repair model, so no call was made. Under the default caps an unpriced model runs, metered at an estimated ceiling. | `llm` | no | Look up the model's per-token price and register it on the brain host: `gbrain pricing set <model> --input <usd> --output <usd>` ([registering a model price](../operations/spend-controls.md#registering-a-model-price)). The next run repairs it. Format: [tiers](fence-format.md#never-guessed). || <a id="fence-ledger_unavailable"></a>`ledger_unavailable` | The spend ledger could not be read or written, so no model call was made. | `llm` | yes | Nothing to do: the next run retries. If it keeps happening, check the database with `gbrain doctor --json`. Format: [tiers](fence-format.md#never-guessed). |diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.mdindex 2e7d0ad897..0acf01dbcf 100644--- a/docs/operations/spend-controls.md+++ b/docs/operations/spend-controls.md@@ -153,7 +153,7 @@ line naming the cap, its source and how to remove it, e.g.| Atom auto-drain daily cap | `autopilot.auto_drain.max_usd_per_day` | `2.00` | daily cap on drain **attempts** (`floor(max / 0.30)` = 6), not a dollar ledger | `gbrain config set autopilot.auto_drain.enabled false` | **not** consulted || Connector email/meeting atoms | `cycle.extract_atoms.connector_pages` | on (unset) | Gmail/Calendar `email`/`meeting` pages are extracted like other pages, under the auto-drain cap | `false` | **not** consulted || Life Chronicle event extraction | `chronicle.job_budget_usd` (per page) / `chronicle.auto_daily_limit` (calls per rolling 24 h) | `0.25` / `200` | caps one extraction call; past the daily limit pending pages wait for a free slot | `gbrain config set auto_chronicle false` | **not** consulted |-| [Fence model repair (Tier 3)](#fence-model-repair-tier-3) | `fences.repair.max_usd_per_page` / `fences.repair.max_usd_per_day` | `0.05` / `1.00` | refuses the call: a page whose estimate is over the per-page cap or over today's remainder in the durable USD ledger (`llm_repair`/`fences`, per UTC day across every process) waits as `budget_exhausted`, and `gbrain repair fences --apply` stops there with exit 1. `--max-usd <n>` lowers a run's cap, never raises it | `gbrain config set fences.repair.llm false` (`0` on a cap = no model spend) | **not** consulted |+| [Fence model repair (Tier 3)](#fence-model-repair-tier-3) | `fences.repair.max_usd_per_page` / `fences.repair.max_usd_per_day` | `0.30` / `1.00` | refuses the call: a page whose estimate is over the per-page cap or over today's remainder in the durable USD ledger (`llm_repair`/`fences`, per UTC day across every process) waits as `budget_exhausted`, and `gbrain repair fences --apply` stops there with exit 1. `--max-usd <n>` lowers a run's cap, never raises it | `gbrain config set fences.repair.llm false` (`0` on a cap = no model spend) | **not** consulted || Dream `synthesize` per-run budget | `dream.synthesize.budget_usd` | `5` | defers the transcript and the rest of the run before submission (estimate: prompt size + child output cap, x `max_turns` in agentic mode) | `unlimited` (`0` = submit nothing) | **not** consulted || Dream `synthesize` daily submission cap | `dream.synthesize.max_submissions_per_source_per_day` | `0` (off) | skips whole files; a failed count query submits nothing that run | `0` | **not** consulted || Dream `BudgetMeter` phases (auto_think, drift, propose/grade takes, calibration) | `dream.auto_think.budget`, `dream.drift.budget`, `cycle.<phase>.budget_usd` | per phase | refuses the next submit past the cap | `unlimited` (`0` = spend nothing) | **not** consulted |@@ -176,9 +176,16 @@ paying a model to repair my facts tables."*The maintenance run's `fence_repair` phase and `gbrain repair fences --apply`send a malformed facts or takes fence that only a rewrite can realign to the-configured chat model (`models.fence_repair`). Only the fence header and the-rows it must realign leave the machine, never valid rows or the rest of the-page. Every other fence repair is free.+repair model. Only the fence header and the rows it must realign leave the+machine, never valid rows or the rest of the page. Every other fence repair+is free.++- **Model.** `models.fence_repair` when set (any model, priced or not, always+ runs). Unset, the first model the fence-repair eval measured as accurate+ enough whose provider key the brain has: `openai:gpt-6.1-sol`, then+ `anthropic:claude-fable-5-1`. With neither key, model repair is off by+ default and those fences wait as `no_measured_model`; choosing a model is+ the user's call.- **Ledger.** Each call reserves its estimate in the durable daily USD ledgerbefore it is sent and settles the measured cost after. Failed and retried@@ -187,9 +194,14 @@ page. Every other fence repair is free.on the brain (the maintenance cycle and the CLI), so concurrent runs neverexceed the cap together. When the ledger cannot be read, no call is made(`ledger_unavailable`).-- **Caps.** `fences.repair.max_usd_per_page` (default $0.05) and+- **Caps.** `fences.repair.max_usd_per_page` (default $0.30) and`fences.repair.max_usd_per_day` (default $1.00), validated at- `config set`; `0` means no model spend. A page over either cap waits as+ `config set`; `0` means no model spend. A call's estimate is its worst+ case: the prompt plus the full output ceiling, which leaves a reasoning+ model 2,048 tokens to think before it writes the table. The per-page+ default covers `anthropic:claude-fable-5-1`'s worst case for the largest+ page in the eval (two fences, $0.27); measured spend was about $0.02 per+ repair. A page over either cap waits as`budget_exhausted`; `gbrain repair fences --apply` stops with exit 1,naming the spend, the cap, the reset time (next 00:00 UTC) and the pageswaiting. Raising a cap is the user's call.diff --git a/evals/fence-repair-tier3/README.md b/evals/fence-repair-tier3/README.mdindex 0e6b4177d1..e8c9002b59 100644--- a/evals/fence-repair-tier3/README.md+++ b/evals/fence-repair-tier3/README.md@@ -6,11 +6,11 @@ Measures how well a chat model repairs the facts and takes fences that the free| File | Role ||---|---|-| `cases.ts` | 78 hand-written cases. Each is one page whose fence Tier 1 leaves with a residual reason a model may clear (`short_row`, `no_header`, `row_before_header`, `extra_cells`, `header_unmapped`), with the whole repaired section written by hand. Sets: 66 `repairable` (a correct repair exists and passes every gate), 9 `adversarial` (the only correct outcome is to stay held: 6 `ambiguous` with two readings the gates cannot tell apart, 3 `unrecoverable` missing a required value) and 3 `gate_limited` (a person would repair them, but the gates forbid the correct table; diagnostic). Placeholder names only. |+| `cases.ts` | 78 hand-written cases. Each is one page whose fence the first run's Tier 1 left with a residual reason a model could clear (`short_row`, `no_header`, `row_before_header`, `extra_cells`, `header_unmapped`), with the whole repaired section written by hand. The cases and `fixtures.jsonl` are unchanged since the preregistered run; since then the free tiers decide 17 of them (`FREE_TIER_PATH` in `oracle.ts`): Tier 1 repairs 10 stray-empty-cell rows and holds 7 rows whose extra cells removing empty cells cannot line up. Sets: 66 `repairable` (a correct repair exists and passes every gate), 9 `adversarial` (the only correct outcome is to stay held: 6 `ambiguous` with two readings the gates cannot tell apart, 3 `unrecoverable` missing a required value) and 3 `gate_limited` (a person would repair them, but the gates forbid the correct table; diagnostic). Placeholder names only. || `generate-fixtures.ts` | Deterministic builder: `cases.ts` → `fixtures.jsonl` (committed). Regenerate after editing a case; the keyless test fails on drift. |-| `run-case.ts` | One fixture through the production path: the page becomes a stored-page target, `analyzeFences` runs the free tiers, and `runTier3` makes the model call with the brain's real daily ledger and attempt store (prompt v1, one call per fence, at most one corrective re-ask, gates (a)-(g), Tier 1 fixed point). Nothing re-implements a tier or a gate. |-| `oracle.ts` | The $0 label check: a scripted model answers with each ground truth (or adversarial probe) and the real gates must agree with the label. |-| `score.ts` | Pure scoring: the cell-level match rule, per-model rates, Wilson intervals and the preregistered decision rule. |+| `run-case.ts` | One fixture through the production path: the page becomes a stored-page target, `analyzeFences` runs the free tiers (a page they repair is `repaired` with `tier1: proposal`, one they hold is `not_sent`), and `runTier3` makes the model call with the brain's real daily ledger and attempt store (prompt v2, where the model may answer HOLD, held as `llm_declined`; one call per fence; a corrective re-ask only after a structural failure, gate (a) or (e); gates (a)-(g); Tier 1 fixed point). Nothing re-implements a tier or a gate. |+| `oracle.ts` | The $0 label check: a scripted model answers with each ground truth (or adversarial probe) and the real gates must agree with the label; the free tiers must decide the `FREE_TIER_PATH` fixtures as listed; a HOLD answer to every Tier 3 fixture must be held as `llm_declined`. |+| `score.ts` | Pure scoring: the cell-level match rule, per-model rates over the production path plus the Tier 3-only share (`repairable.tier3`), HOLD counts, Wilson intervals and the preregistered decision rule. || `harness.ts` | Runner: `--oracle`, live (`--model`, `--run`, `--out`) and `--score`. |The keyless test is `test/eval-fence-repair-tier3.test.ts` (fixture freshness and coverage floors, the oracle, scorer arithmetic). It guards the instrument, not the score.@@ -29,13 +29,13 @@ bun evals/fence-repair-tier3/harness.ts --model default --run 1 --out results/debun evals/fence-repair-tier3/harness.ts --score results/*.jsonl --json summary.json```-A live run sets `models.fence_repair` on its brain (unset for `default`), registers list prices gbrain's table lacks in `pricing.overrides` (as `gbrain pricing set` would), and sets `fences.repair.max_usd_per_day` to `--max-usd`, which the daily ledger enforces as a hard ceiling. The per-page cap stays at the production default ($0.05), so a corrective re-ask the cap cannot cover is refused exactly as in production. A provider error is retried twice after a pause, as the next maintenance run would retry it. Each result row records the outcome (repaired, or held with its gate or failure class), the match against the ground truth, per-call tokens, ledger-priced USD, latency and the model's answer text.+A live run sets `models.fence_repair` on its brain (unset for `default`, which resolves to the first measured model with a provider key and refuses to run when there is none), registers list prices gbrain's table lacks in `pricing.overrides` (as `gbrain pricing set` would; none today), and sets `fences.repair.max_usd_per_day` to `--max-usd`, which the daily ledger enforces as a hard ceiling. The per-page cap stays at the production default, so a call the cap cannot cover is refused exactly as in production. A provider error is retried twice after a pause, as the next maintenance run would retry it. Each result row records the outcome (repaired, or held with its gate or failure class), the match against the ground truth, per-call tokens, ledger-priced USD, latency and the model's answer text.Exit codes: 0 done, 1 oracle violation, 2 infrastructure (no key, cap reached, a fixture that no longer reaches Tier 3).## Metrics-- **Gate-pass rate**: repairable fences whose Tier 3 repair passed every gate, over repairable fences run.+- **Gate-pass rate**: repairable fences repaired on the production path (by the free tiers, or by a Tier 3 repair that passed every gate), over repairable fences run. `repairable.tier3` gives the same counts for the fences that reached the model.- **False-accept rate**: repairable fences repaired but not matching the ground truth, over repairable fences run. A match means the same non-empty cell text in the same columns (spacing ignored) and identical text outside the fences.-- **Held correctly**: adversarial fences that stayed held.+- **Held correctly**: adversarial fences that stayed held (`declined` counts the ones the model held with HOLD).- **USD per repair**: ledger-priced spend on repairable fences over repairs. **Latency**: wall time of the Tier 3 step per fence that made a call (p50, p95).diff --git a/evals/fence-repair-tier3/harness.ts b/evals/fence-repair-tier3/harness.tsindex 88d9ad5ae5..19c560e146 100644--- a/evals/fence-repair-tier3/harness.ts+++ b/evals/fence-repair-tier3/harness.ts@@ -16,11 +16,12 @@* [--max-usd 10] [--only id1,id2]* One throwaway PGLite brain per invocation (fresh ledger and attempt* memo). `models.fence_repair` is set to the model (left unset for- * `default`, so gbrain's own resolution picks it), `pricing.overrides`+ * `default`, so gbrain's own resolution picks it: the first measured model+ * with a provider key, refused when there is none), `pricing.overrides`* registers list prices gbrain's table lacks (as `gbrain pricing set`* would), and `fences.repair.max_usd_per_day` is set to --max-usd, which the* daily ledger enforces as a hard ceiling. The per-page cap stays at the- * production default ($0.05). Each fixture goes through `run-case.ts`. A+ * production default. Each fixture goes through `run-case.ts`. A* provider error (`llm_unavailable`) is retried twice after a pause, as the* next maintenance run would; anything else is the outcome.*@@ -39,10 +40,11 @@ const here = import.meta.dir;const args = process.argv.slice(2);const flag = (name: string) => { const i = args.indexOf(name); return i === -1 ? null : args[i + 1] ?? null; };-/** List prices (USD per 1M tokens) for models gbrain's price table lacks, registered on the eval brain like `gbrain pricing set`. */-export const REGISTERED_PRICES: Record<string, { input: number; output: number; source: string }> = {- 'openai:gpt-6.1-sol': { input: 2, output: 10, source: 'gbrain-evals eval/runner/budget-ledger.ts CHAT_PRICE_OVERRIDES (provider pricing page, checked 2026-10-02)' },-};+/**+ * List prices (USD per 1M tokens) for models gbrain's price table lacks, registered on the eval brain like `gbrain pricing set`.+ * Empty: every model this eval has run is in the table (gpt-6.1-sol joined it with the fixes the first run found).+ */+export const REGISTERED_PRICES: Record<string, { input: number; output: number; source: string }> = {};export const CALL_TIMEOUT_MS = Number(process.env.GBRAIN_FENCE_REPAIR_CALL_TIMEOUT_MS) > 0 ? Number(process.env.GBRAIN_FENCE_REPAIR_CALL_TIMEOUT_MS) : 90_000;@@ -107,7 +109,7 @@ if (!modelArg || !outPath || !Number.isInteger(run) || !(maxUsd > 0)) {const { configureEvalGateway } = await import('../../src/eval/shared/gateway-bootstrap.ts');const { isAvailable } = await import('../../src/core/ai/gateway.ts');const { registerChatUsageSink } = await import('../../src/core/ai/chat-usage.ts');-const { resolveFenceRepairModel } = await import('../../src/core/repair/fences.ts');+const { resolveFenceRepairModel } = await import('../../src/core/fence-repair/model.ts');const { readFenceRepairCaps, FENCE_REPAIR_MAX_USD_PER_DAY_KEY } = await import('../../src/core/fence-repair/config.ts');const { loadPricingOverrides } = await import('../../src/core/budget/budget-tracker.ts');const { analyzeFences, tier3Estimate } = await import('../../src/core/fence-repair/repair-tiers.ts');@@ -118,7 +120,12 @@ const { engine, incarnation } = await newBrain();if (modelArg !== 'default') await engine.setConfig('models.fence_repair', modelArg);await engine.setConfig('pricing.overrides', JSON.stringify(Object.fromEntries(Object.entries(REGISTERED_PRICES).map(([m, p]) => [m, { input: p.input, output: p.output }]))));await engine.setConfig(FENCE_REPAIR_MAX_USD_PER_DAY_KEY, String(maxUsd));-const model = await resolveFenceRepairModel(engine);+const resolved = await resolveFenceRepairModel(engine);+if (!resolved) {+ console.error('fence-repair-tier3: --model default resolves to no model: no measured fence-repair model has a provider key here. Set a key, or pass --model.');+ process.exit(2);+}+const model = resolved;const overrides = await loadPricingOverrides(engine);const caps = await readFenceRepairCaps(engine);configureEvalGateway({ chatModel: model });@@ -204,10 +211,6 @@ for (const f of selected) {await new Promise(r => setTimeout(r, attempts * 20_000));}spent += out.spent_usd;- if (out.tier1 !== 'llm') {- console.error(`${f.id}: fixture defect, the free tiers returned ${out.tier1} (${out.reason}); it must reach Tier 3.`);- process.exitCode = 2;- }const match = out.outcome === 'repaired' && f.expected ? compareRepair(out.after!, f.expected) : null;const unregistered = calls.every(c => c.input_tokens !== null)? calls.reduce((s, c) => s + chatCallUsd(model, { inputTokens: c.input_tokens!, outputTokens: c.output_tokens! }).usd, 0) : null;@@ -215,7 +218,7 @@ for (const f of selected) {outcome: out.outcome, reason: out.reason, gate: out.gate, rows: out.rows, match_cells: match ? match.cells : null, match_exact: match ? match.exact : null,calls, spent_usd: out.spent_usd, usd_unregistered: unregistered, latency_ms: latency, attempts, message: out.message, after: out.after };appendFileSync(outPath, JSON.stringify(row) + '\n');- console.error(`${f.id}: ${out.outcome}${out.gate ? ` gate ${out.gate}` : out.reason && out.outcome !== 'repaired' ? ` ${out.reason}` : ''}${match ? (match.cells ? ' match' : ' MISMATCH') : ''} calls=${calls.length} $${out.spent_usd.toFixed(4)} ${latency}ms`);+ console.error(`${f.id}: ${out.tier1 === 'llm' ? '' : `[${out.tier1}] `}${out.outcome}${out.gate ? ` gate ${out.gate}` : out.reason && out.outcome !== 'repaired' ? ` ${out.reason}` : ''}${match ? (match.cells ? ' match' : ' MISMATCH') : ''} calls=${calls.length} $${out.spent_usd.toFixed(4)} ${latency}ms`);if (out.reason === 'budget_exhausted' && /daily/.test(out.message ?? '')) { stopped = `the daily ledger cap ($${maxUsd}) was reached after $${spent.toFixed(4)}`; break; }}globalThis.fetch = realFetch;diff --git a/evals/fence-repair-tier3/oracle.ts b/evals/fence-repair-tier3/oracle.tsindex 56a954082c..d8ce1bdc5a 100644--- a/evals/fence-repair-tier3/oracle.ts+++ b/evals/fence-repair-tier3/oracle.ts@@ -11,12 +11,18 @@* - adversarial/ambiguous: the probe (a wrong guess) must be accepted, which* shows only the model can keep the page held.* - adversarial/unrecoverable: the probe (an invented value) must be rejected.+ * - every fixture that reaches Tier 3: a model answering HOLD is held as+ * `llm_declined` (prompt v2).*- * Every fixture must also reach Tier 3 with the residual reason its class names.+ * Every fixture must reach Tier 3 with the residual reason its class names,+ * except the ones `FREE_TIER_PATH` lists, which the free tiers decide: `tier1`+ * ones Tier 1 repairs to the ground truth byte for byte, `manual` ones it+ * holds before any model call.*/import { __setChatTransportForTests, type ChatResult } from '../../src/core/ai/gateway.ts';import { dailyLedger, FENCE_REPAIR_LEDGER } from '../../src/core/budget/daily-ledger.ts';import { attemptStore } from '../../src/core/fence-repair/attempts.ts';+import { FENCE_REPAIR_DEFAULT_MAX_USD_PER_PAGE } from '../../src/core/fence-repair/config.ts';import { analyzeFences } from '../../src/core/fence-repair/repair-tiers.ts';import { extractRawRows, primaryFence } from '../../src/core/fence-repair/raw-rows.ts';import type { Tier3Request } from '../../src/core/fence-repair/llm.ts';@@ -29,6 +35,19 @@ const REASON_OF: Record<string, string | null> = {extra_cells: 'extra_cells', header_unmapped: 'header_unmapped', mixed: null,};+/**+ * Fixtures the free tiers decide without a model since the eval's fixes+ * (#6188 T4): `tier1` rows have stray empty cells with exactly one valid+ * removal (Tier 1 `stray_empty_cell`); `manual` rows have extra cells that+ * removing empty cells cannot line up (a misplaced text cell, a duplicated+ * value, or a claim cut by an unescaped pipe), held as `extra_cells`.+ */+export const FREE_TIER_PATH: Readonly<Record<string, 'tier1' | 'manual'>> = {+ 'f-ex-01': 'tier1', 'f-ex-02': 'tier1', 'f-ex-03': 'tier1', 'f-ex-04': 'tier1', 'f-ex-06': 'tier1', 'f-ex-07': 'tier1',+ 't-ex-01': 'tier1', 't-ex-02': 'tier1', 't-ex-03': 'tier1', 't-ex-04': 'tier1',+ 'f-ex-05': 'manual', 'f-adv-01': 'manual', 'f-adv-02': 'manual', 'f-adv-03': 'manual', 'f-adv-04': 'manual', 't-adv-01': 'manual', 'f-gl-02': 'manual',+};+export type AnswerFn = (f: Fixture, req: Tier3Request, variant: 'as_written' | 'blank_numbers') => string;/** The scripted answer: the probe, or the expected page's rows at the sent positions under the expected header. */@@ -56,7 +75,7 @@ export async function runOracle(fixtures: readonly Fixture[], answer: AnswerFn):await engine.initSchema();const [src] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");const deps = { ledger: dailyLedger(engine, FENCE_REPAIR_LEDGER), store: attemptStore(engine), model: 'anthropic:claude-opus-4-7', capSource: 'default' as const,- perPageUsd: 0.05, perDayUsd: 1000, timeoutMs: 30_000, now: () => new Date() };+ perPageUsd: FENCE_REPAIR_DEFAULT_MAX_USD_PER_PAGE, perDayUsd: 1000, timeoutMs: 30_000, now: () => new Date() };const violations: string[] = [];try {for (const f of fixtures) {@@ -64,6 +83,16 @@ export async function runOracle(fixtures: readonly Fixture[], answer: AnswerFn):for (const variant of variants) {const run = variant === 'as_written' ? f : { ...f, id: `${f.id}~blank` };const analysis = await analyzeFences(engine, fixtureTarget(run), { pageId: null });+ const path = FREE_TIER_PATH[f.id];+ if (path === 'tier1') {+ if (analysis.status !== 'proposal') violations.push(`${f.id}: the free tiers returned ${analysis.status}; Tier 1 must repair it`);+ else if (analysis.after.compiled_truth !== f.expected!.compiled_truth || analysis.after.timeline !== f.expected!.timeline) violations.push(`${f.id}: the Tier 1 repair differs from expected`);+ continue;+ }+ if (path === 'manual') {+ if (analysis.status !== 'manual') violations.push(`${f.id}: the free tiers returned ${analysis.status}; they must hold it before any model call`);+ continue;+ }if (analysis.status !== 'llm') {violations.push(`${f.id}: the free tiers returned ${analysis.status}${analysis.status === 'manual' ? ` (${analysis.reason})` : ''}; it must reach Tier 3`);continue;@@ -89,6 +118,11 @@ export async function runOracle(fixtures: readonly Fixture[], answer: AnswerFn):} else if (f.adversarial === 'ambiguous') {if (out.outcome !== 'repaired') violations.push(`${tag}: the ambiguous probe was rejected (${out.reason}${out.gate ? `, gate ${out.gate}` : ''}); the gates can already hold it`);} else if (out.outcome === 'repaired') violations.push(`${tag}: the unrecoverable probe was accepted`);+ if (variant === 'as_written') {+ __setChatTransportForTests(async () => result('HOLD'));+ const declined = await runCase(engine, src!.incarnation, { ...f, id: `${f.id}~hold` }, deps);+ if (declined.outcome !== 'held' || declined.reason !== 'llm_declined') violations.push(`${f.id}: a HOLD answer was ${declined.outcome} (${declined.reason}), not held as llm_declined`);+ }}}} finally {diff --git a/evals/fence-repair-tier3/run-case.ts b/evals/fence-repair-tier3/run-case.tsindex b3931563c4..6821580e11 100644--- a/evals/fence-repair-tier3/run-case.ts+++ b/evals/fence-repair-tier3/run-case.ts@@ -4,10 +4,13 @@* The fixture page becomes a database-page target (`mode: 'db'`, the shape* `readFenceTarget` returns for a stored page) on the eval brain's default* source. `analyzeFences` runs the free tiers exactly as `gbrain repair- * fences` does; a page they leave for the model goes through `runTier3` with- * the real daily ledger and attempt store of that brain: prompt v1, one call- * per fence, at most one corrective re-ask, gates (a)-(g) and the Tier 1- * fixed point. Nothing here re-implements a tier or a gate.+ * fences` does: a page they repair is `repaired` with `tier1: 'proposal'`+ * (no call), a page they hold is `not_sent` with its manual reason, and a+ * page they leave for the model goes through `runTier3` with the real daily+ * ledger and attempt store of that brain: prompt v2 (a model may answer HOLD,+ * held as `llm_declined`), one call per fence, a corrective re-ask only after+ * a structural gate failure ((a) or (e)), gates (a)-(g) and the Tier 1 fixed+ * point. Nothing here re-implements a tier or a gate.** `observeCalls` wraps the ledger to record each call's estimate and settled* cost; the harness adds tokens (chat usage sink) and the answer text (a@@ -23,7 +26,7 @@ export interface LedgerCall { estimate_usd: number; usd: number | null }export interface CaseOutcome {id: string;- /** What the free tiers decided: `llm` means the page reached Tier 3. */+ /** What the free tiers decided: `llm` means the page reached Tier 3; `proposal` means they repaired it; `manual` means they held it. */tier1: 'clean' | 'proposal' | 'manual' | 'llm';/** Residual reasons Tier 1 left (location-only codes). */residual: string[];@@ -78,7 +81,7 @@ export async function runCase(engine: BrainEngine, incarnation: string, f: Fixtuconst base = { id: f.id, spent_usd: 0, ledger_calls: [] as LedgerCall[], after: null, gate: null, rows: [] as number[], message: null, requests: 0 };const analysis = await analyzeFences(engine, target, { pageId: null });if (analysis.status === 'clean') return { ...base, tier1: 'clean', residual: [], outcome: 'not_sent', reason: 'clean' };- if (analysis.status === 'proposal') return { ...base, tier1: 'proposal', residual: [], outcome: 'not_sent', reason: analysis.tier, after: analysis.after };+ if (analysis.status === 'proposal') return { ...base, tier1: 'proposal', residual: [], outcome: 'repaired', reason: analysis.tier, after: { compiled_truth: analysis.after.compiled_truth, timeline: analysis.after.timeline } };if (analysis.status === 'manual') {return { ...base, tier1: 'manual', residual: [analysis.reason], outcome: 'not_sent', reason: analysis.reason, gate: analysis.gate ?? null, rows: analysis.rows ?? [] };}diff --git a/evals/fence-repair-tier3/score.ts b/evals/fence-repair-tier3/score.tsindex 334d87ca29..351dd1f38b 100644--- a/evals/fence-repair-tier3/score.ts+++ b/evals/fence-repair-tier3/score.ts@@ -10,10 +10,14 @@* stricter byte-for-byte comparison, reported alongside.** Metrics (preregistered in gbrain-evals, docs/benchmarks/2026-10-06-fence-repair-tier3-preregistration.md):- * - gate-pass rate: repairable items whose Tier 3 repair passed every gate,- * over repairable items run.+ * - gate-pass rate: repairable items repaired on the production path (by the+ * free tiers or by a Tier 3 repair that passed every gate), over repairable+ * items run.* - false-accept rate: repairable items repaired but not matching their* ground truth, over repairable items run.+ * `repairable.tier3` restricts both to the items that reached the model;+ * `tier1_repaired` and `held_before_model` count the free tiers' share, and+ * `declined` counts HOLD answers (`llm_declined`, prompt v2).* - held correctly: adversarial items that stayed held, over adversarial* items run.* - USD per repair: ledger-priced spend on repairable items over repairs.@@ -23,7 +27,7 @@ import { extractRawRows, primaryFence } from '../../src/core/fence-repair/raw-roimport { collapse } from '../../src/core/fence-repair/schema.ts';import type { FencePageText } from './generate-fixtures.ts';-export const SCORER_VERSION = 1;+export const SCORER_VERSION = 2;type Section = 'compiled_truth' | 'timeline';@@ -111,8 +115,9 @@ export interface ModelSummary {model: string;runs: number;repairable: { n: number; repaired: number; gate_pass: number; gate_pass_ci: [number, number] | null; false_accepts: number; false_accept: number; false_accept_ci: [number, number] | null;- exact_matches: number; per_run_gate_pass: number[]; reask_used: number; reask_rescued: number; held_by: Record<string, number> };- adversarial: { n: number; held: number; held_rate: number; ambiguous_n: number; ambiguous_held: number; unrecoverable_n: number; unrecoverable_held: number; accepted_ids: string[] };+ exact_matches: number; per_run_gate_pass: number[]; reask_used: number; reask_rescued: number; held_by: Record<string, number>;+ tier1_repaired: number; held_before_model: number; declined: number; tier3: { n: number; repaired: number; false_accepts: number } };+ adversarial: { n: number; held: number; held_rate: number; ambiguous_n: number; ambiguous_held: number; unrecoverable_n: number; unrecoverable_held: number; declined: number; accepted_ids: string[] };gate_limited: { n: number; held: number; accepted_ids: string[] };cost: { usd_total: number; usd_repairable: number; usd_per_repair: number | null; usd_per_item: number; usd_unregistered_per_repair: number | null; input_tokens: number; output_tokens: number; calls: number };latency_ms: { p50: number | null; p95: number | null };@@ -145,11 +150,14 @@ export function summarize(rows: readonly ResultRow[]): ModelSummary[] {exact_matches: repaired.filter(r => r.match_exact).length,per_run_gate_pass: runs.map(run => { const x = rep.filter(r => r.run === run); return x.length ? x.filter(r => r.outcome === 'repaired').length / x.length : 0; }),reask_used: reask.length, reask_rescued: reask.filter(r => r.outcome === 'repaired').length, held_by: heldBy,+ tier1_repaired: rep.filter(r => r.tier1 === 'proposal').length, held_before_model: rep.filter(r => r.tier1 === 'manual').length,+ declined: rep.filter(r => r.reason === 'llm_declined').length,+ tier3: { n: rep.filter(r => r.tier1 === 'llm').length, repaired: repaired.filter(r => r.tier1 === 'llm').length, false_accepts: falseAccepts.filter(r => r.tier1 === 'llm').length },},adversarial: {n: adv.length, held: adv.filter(r => r.outcome !== 'repaired').length, held_rate: adv.length ? adv.filter(r => r.outcome !== 'repaired').length / adv.length : 0,ambiguous_n: amb.length, ambiguous_held: amb.filter(r => r.outcome !== 'repaired').length,- unrecoverable_n: unr.length, unrecoverable_held: unr.filter(r => r.outcome !== 'repaired').length,+ unrecoverable_n: unr.length, unrecoverable_held: unr.filter(r => r.outcome !== 'repaired').length, declined: adv.filter(r => r.reason === 'llm_declined').length,accepted_ids: [...new Set(adv.filter(r => r.outcome === 'repaired').map(r => r.id))].sort(),},gate_limited: { n: gl.length, held: gl.filter(r => r.outcome !== 'repaired').length, accepted_ids: [...new Set(gl.filter(r => r.outcome === 'repaired').map(r => r.id))].sort() },diff --git a/llms-full.txt b/llms-full.txtindex 127f6e9951..0c4a09c49c 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -11841,18 +11841,25 @@ Each candidate gets the cheapest tier that repairs it exactly:| Tier | What it does | Cost || --- | --- | --- |-| `deterministic` | The lossless rules every write already runs (missing end marker, row numbers, header aliases and order, enum and kind synonyms, assistant holders, percent confidences). | Free. |+| `deterministic` | The lossless rules every write already runs (missing end marker, stray empty cells with one valid removal, row numbers, header aliases and order, enum and kind synonyms, assistant holders, percent confidences). | Free. || `resolver` | A holder written as a display name becomes the `people/` or `companies/` page it names, only on an exact match (slug, unique slug basename or alias; never a guess, never a private page on a world-visible page). | Free. |-| `llm` | Rows only a rewrite can realign (no header, a header column with no canonical name, rows above the header, short rows, extra cells). The configured chat model (`models.fence_repair`) sees only the fence header and those rows, never valid rows of a row-level problem and never the rest of the page, with no tools. | Paid, within `fences.repair.max_usd_per_page` ($0.05) and `fences.repair.max_usd_per_day` ($1.00). |-| `manual` | Anything gbrain never guesses (a stray end marker, an unknown takes kind, a weight out of range, a holder no page matches). The preview names the exact edit. | Your edit. |+| `llm` | Rows only a rewrite can realign (no header, a header column with no canonical name, rows above the header, short rows). The repair model sees only the fence header and those rows, never valid rows of a row-level problem and never the rest of the page, with no tools, and answers HOLD instead of guessing when a row has two readings. | Paid, within `fences.repair.max_usd_per_page` ($0.30) and `fences.repair.max_usd_per_day` ($1.00). |+| `manual` | Anything gbrain never guesses (a stray end marker, an unknown takes kind, a weight out of range, a holder no page matches, extra cells that removing empty cells cannot line up, a sentence in the facts `kind` column). The preview names the exact edit. | Your edit. |Every proposal, whichever tier made it, must pass the validation[gates (a) to (g)](fence-format.md#gates) against the bytes as read (claims,existing row numbers and valid cells unchanged, no row more visible, nothing thefence hid shown) and be a normalizer fixed point, or it is not written. A model-proposal a gate rejects gets one corrective re-ask naming the gate and rows;-if that fails too the file stays held with the gate, and the same bytes are-never sent again until the file, the model or the rules change.+proposal that does not parse or changes the row count (gates (a) and (e)) gets+one corrective re-ask naming the gate and rows; any other gate rejection, a+HOLD, or a failed re-ask leaves the file held, and the same bytes are never+sent again until the file, the model or the rules change.++The repair model is `models.fence_repair` when set. Unset, it is the first+model the fence-repair eval measured as accurate enough whose provider key the+brain has: `openai:gpt-6.1-sol`, then `anthropic:claude-fable-5-1`. With+neither key, model-tier fences wait as `no_measured_model` until the user+picks a model.The session below is real output (volatile ids, hashes and times shown as`<id>`, `<hash>`, `<time>`; `test/fence-walkthrough.test.ts` runs these@@ -11902,15 +11909,15 @@ exists). An older gbrain blocked the source on the first fence it refused.```console$ gbrain repair fences --source notes- cost: 2 request ID(s), 32768 receipt bytes, 2 page(s) to re-embed, paid model ~$0.0112 ($1.0000 left under today's cap)- llm: notes:companies/acme-example.md (no_header; rewritten by openai:gpt-5.5 at apply time, gated by (a)-(g); est. $0.0112)+ cost: 2 request ID(s), 32768 receipt bytes, 2 page(s) to re-embed, paid model ~$0.0273 ($1.0000 left under today's cap)+ llm: notes:companies/acme-example.md (no_header; rewritten by openai:gpt-6.1-sol at apply time, gated by (a)-(g); est. $0.0273)resolver: notes:projects/widget-launch.md (holder_verified; rows 1)- tiers: deterministic=0, resolver=1, llm=1, held=0; model openai:gpt-5.5- model caps: $0.05/page, $1.00/day ($1.0000 left today)+ tiers: deterministic=0, resolver=1, llm=1, held=0; model openai:gpt-6.1-sol+ model caps: $0.30/page, $1.00/day ($1.0000 left today)-| 1 | The launch slips a week | bet | Alice Example | 0.6 | 2026-04 | standup |+| 1 | The launch slips a week | bet | people/alice-example | 0.6 | 2026-04 | standup |next: gbrain repair fences --source notes --apply --expect <hash>- Kinds that may call a paid model: fences (estimated $0.0112; $1.0000 left under today's cap).+ Kinds that may call a paid model: fences (estimated $0.0273; $1.0000 left under today's cap).```5. Apply exactly the previewed set. A file that changed since the preview is@@ -11919,7 +11926,7 @@ exists). An older gbrain blocked the source on the first fence it refused.```console$ gbrain repair fences --source notes --apply --expect <hash>- cost: 2 request ID(s), 32768 receipt bytes, 2 page(s) to re-embed, paid model $0.0072 spent ($0.9928 left under today's cap)+ cost: 2 request ID(s), 32768 receipt bytes, 2 page(s) to re-embed, paid model $0.0039 spent ($0.9961 left under today's cap)applied 2, skipped 0, completerepaired 2; nothing left in this selectionrepaired: notes:companies/acme-example tier=llm, classes=no_header, slug=companies/acme-example, mode=managed, path=companies/acme-example.md, imported=created, hold_cleared=true, committed=queued@@ -11948,7 +11955,7 @@ exists). An older gbrain blocked the source on the first fence it refused.```One command got the source syncing again (the sync), and two repaired the rest-(preview, apply), for $0.0072 of model spend.+(preview, apply), for $0.0039 of model spend.Selection and output:@@ -12009,9 +12016,9 @@ the next maintenance run, so pause first if you want to keep the original.| --- | --- | --- || `fences.repair.enabled` | `true` | `false` pauses the maintenance run's repair; `gbrain repair fences --apply` still works. || `fences.repair.llm` | `true` | `false` keeps every repair to the free tiers; model-tier holds stay `llm_disabled`. |-| `fences.repair.max_usd_per_page` | `0.05` | The most one page may spend on the model (one call plus one corrective re-ask). `0` means no model spend. |+| `fences.repair.max_usd_per_page` | `0.30` | The most one page may spend on the model, checked against each call's worst case (the prompt plus the full output ceiling, with 2,048 tokens for a reasoning model to think). `0` means no model spend. || `fences.repair.max_usd_per_day` | `1.00` | The most all processes together spend per UTC day, through a durable ledger. `0` means no model spend. |-| `models.fence_repair` | the `deep` tier | The model Tier 3 calls (`gbrain models` shows it). A model gbrain has no price for runs under the default caps at an estimated ceiling (the highest chat rate gbrain knows; `gbrain pricing set` makes it exact) and waits for its price under a cap you set. |+| `models.fence_repair` | unset: the first measured model with a key (`openai:gpt-6.1-sol`, then `anthropic:claude-fable-5-1`), else none | The model Tier 3 calls (`gbrain models` shows it). A model you set always runs; one gbrain has no price for runs under the default caps at an estimated ceiling (the highest chat rate gbrain knows; `gbrain pricing set` makes it exact) and waits for its price under a cap you set. || `fences.normalize` | `true` | `false` stops the inline rewrite on writes and syncs: a fixable fence is held or refused like any other. |## Resumediff --git a/scripts/build-fence-format.ts b/scripts/build-fence-format.tsindex b30f5225e9..f038077a3f 100644--- a/scripts/build-fence-format.ts+++ b/scripts/build-fence-format.ts@@ -82,7 +82,7 @@ const GATE_TEXT = {const TIER_TEXT: Record<Exclude<FenceTier, 'deterministic'>, string> = {resolver: 'Tier 2, verified holder lookup, free',- llm: 'Tier 3, the configured chat model rewrites only the named rows',+ llm: 'Tier 3, the repair model rewrites only the named rows, or answers HOLD when a row has two readings',manual: 'a person edits the fence; gbrain never guesses',};@@ -187,11 +187,12 @@ function normalizedTable(): string {const text = {close_fence: 'A fence with no end marker gets one directly after its table, when nothing but blank lines follows the last row up to the end of the section.',marker_form: 'Two-dash takes markers (`<!-- gbrain:takes:begin -->`) directly above a takes table become the three-dash markers. Two-dash facts markers are not a fence and are left alone.',+ stray_empty_cell: 'A row with more cells than its header loses empty cells, only when exactly one choice of empty cells to remove leaves every checked column (`#`, kind, confidence, visibility, notability, `claim_value`; takes kind, holder, weight) valid. Otherwise the row is `extra_cells` and a person fixes it.',renumber: 'A row number that is zero, negative, not a number or a duplicate gets a new number (see [row numbers](#row-numbers)).',column_default: `A required facts column missing from the whole header gets its write default: ${Object.entries(COLUMN_DEFAULTS.facts).map(([c, v]) => `${code(c)} ${code(v)}`).join(', ')}. Takes have no defaults; a takes fence with no weight is \`weight_missing\`.`,header_alias: 'A header whose every column has a known spelling (see [header spellings](#header-spellings)) becomes the canonical header, and each row\'s cells move into canonical order unchanged.',enum_synonym: `Facts notability ${synonymLines(NOTABILITY_SYNONYMS)}; visibility ${codes(PRIVATE_SYNONYMS)} → \`private\`, and \`public\` → \`world\` only on a world-visible page (\`private\` otherwise); case and spacing variants of a canonical value. Any other word is \`enum_unmapped\`.`,- kind_map: `Facts: ${synonymLines(FACT_KIND_SYNONYMS)}; any other word → \`fact\`, with the word kept in \`context\` (for example ${code(appendOriginalKind('', 'partnership'))}). Takes: ${synonymLines(TAKE_KIND_SYNONYMS)}; any other word is \`takes_kind_unsupported\`, because gbrain never chooses a takes kind.`,+ kind_map: `Facts: ${synonymLines(FACT_KIND_SYNONYMS)}; any other word → \`fact\`, with the word kept in \`context\` (for example ${code(appendOriginalKind('', 'partnership'))}). A facts kind cell longer than three words, or with sentence punctuation, a link or strikethrough, is not read as a kind: it is \`claim_split\`, usually the end of a claim an unescaped \`|\` cut in two. Takes: ${synonymLines(TAKE_KIND_SYNONYMS)}; any other word is \`takes_kind_unsupported\`, because gbrain never chooses a takes kind.`,holder_alias: `Takes holder ${codes(brainWords)} (any case) → \`brain\`.`,confidence_format: `A percent or a number with stray spaces in \`confidence\` or \`weight\` becomes a decimal: \`85%\` → ${code(confidenceFormat('85%')!)}, \`0. 8\` → ${code(confidenceFormat('0. 8')!)}. A number outside 0 to 1 is \`confidence_out_of_range\`.`,holder_verified: 'Tier 2, not Tier 1: a takes holder written as a name becomes the one `people/` or `companies/` page it resolves to exactly. On a world-visible page a private page never matches. Anything less certain stays `holder_unresolved`.',diff --git a/skills/migrations/v0.60.101.0.md b/skills/migrations/v0.60.101.0.mdindex 73b2698f73..7e56d65b43 100644--- a/skills/migrations/v0.60.101.0.md+++ b/skills/migrations/v0.60.101.0.md@@ -43,13 +43,22 @@ leave spend decisions to them (step 3).makes them hold such a fence instead.3. **Spend and what leaves the machine.** Most repairs are free rules. A- fence only a rewrite can realign goes to the configured chat provider- (`models.fence_repair`): only the fence header and the rows it must- realign are sent, never valid rows and never the rest of the page. Spend is- capped at $0.05 per page (`fences.repair.max_usd_per_page`) and $1.00 per- UTC day (`fences.repair.max_usd_per_day`) across every process, through a- durable ledger. A repair model gbrain has no price for still runs under- these default caps, metered at an estimated ceiling (the highest chat rate+ fence only a rewrite can realign goes to the repair model: only the fence+ header and the rows it must realign are sent, never valid rows and never+ the rest of the page, and the model answers HOLD instead of guessing when+ a row has two readings. With `models.fence_repair` unset, the repair model+ is the first model the fence-repair eval measured as accurate enough whose+ provider key the brain has: `openai:gpt-6.1-sol` (OpenAI key), then+ `anthropic:claude-fable-5-1` (Anthropic key). With neither key, model+ repair stays off and those fences wait as `no_measured_model`; which model+ to trust is the user's call (`gbrain config set models.fence_repair <provider:model>`;+ a model set there always runs). Spend is capped at $0.30 per page+ (`fences.repair.max_usd_per_page`) and $1.00 per UTC day+ (`fences.repair.max_usd_per_day`) across every process, through a durable+ ledger; each call reserves its worst case (the prompt plus the full output+ ceiling, with room for a reasoning model to think) and settles what it+ really cost. A repair model gbrain has no price for still runs under these+ default caps, metered at an estimated ceiling (the highest chat rategbrain knows); under a cap the user set it waits until its price isregistered with `gbrain pricing set`. Every proposed rewrite passes thevalidation gates before it is written. To keep fence rows away from the@@ -65,7 +74,9 @@ leave spend decisions to them (step 3).gbrain sources status <id> # each fence hold: reason, fence, section, rows, next attempt```A hold whose reason is `manual` is something gbrain never guesses (a stray- end marker, an unknown takes kind, a weight out of range, ...). Show the user+ end marker, an unknown takes kind, a weight out of range, extra cells that+ removing empty cells cannot line up, a sentence in the facts `kind`+ column: often a claim cut in two by an unescaped `|`). Show the userthe location, edit only that fence in the file, commit, then`gbrain sync --source <id> --no-pull`. A hold waiting on the daily cap(`budget_exhausted`) resumes after 00:00 UTC. Each reason's fix:@@ -100,7 +111,8 @@ leave spend decisions to them (step 3).their choice.- Raising a cap (`fences.repair.max_usd_per_day`,`fences.repair.max_usd_per_page`), turning model repair back on- (`fences.repair.llm true`), registering a model price, the content of+ (`fences.repair.llm true`), choosing a repair model+ (`models.fence_repair`), registering a model price, the content ofevery `manual` edit, and undoing a repair are the user's calls.- Relay the one-time `behavior_changes` notice when gbrain prints it(`gbrain doctor --only behavior_changes` shows it again).diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 5229fd0c80..8ac2bcd39b 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -153,7 +153,7 @@"migrations/v0.59.10.0.md": "e0268a05ab184d5518f88747313e772629b2af91db59eacbba728f2ebd9db3cd","migrations/v0.59.2.0.md": "b6d61af8ef48c154a26e8d427dd6f6570e99efb82b891728426046eea493247b","migrations/v0.60.100.0.md": "63583a73e957c5421bb826f2be48ac1aafaaa994392c1a05f26d1516b48c8573",- "migrations/v0.60.101.0.md": "6782981f3a318c6d8c22ef76333e7a1322a21a82ab8211368f0a669d7cda3ea8",+ "migrations/v0.60.101.0.md": "4ee7e2929f8d4545e3adf40ef662aa0cca6b56d81e49cd3814d3c40834955e5d","migrations/v0.60.11.0.md": "1e503113f591c5cd142b78ab4472bbdbceb890c6cbac2fbdf8aa61cd087200b8","migrations/v0.60.20.0.md": "9266863a9f76164c64a72b1be17b8ddb3bb97e1c3c5db9f666b69ebc7a228fdd","migrations/v0.60.26.0.md": "30d761ef5a2361bad66053f97b7b659304a591274be33e281f4f6df0d7d5566e",diff --git a/src/commands/models.ts b/src/commands/models.tsindex 8c0c585211..1ecb1b8279 100644--- a/src/commands/models.ts+++ b/src/commands/models.ts@@ -43,6 +43,7 @@ import {type ResolveSource,} from '../core/model-config.ts';import { resolveExtractAtomsModelWithSource } from '../core/cycle/extract-atoms.ts';+import { resolveFenceRepairModelWithSource } from '../core/fence-repair/model.ts';import {NIGHTLY_PROBE_EXTRACTOR_ROUTE,NIGHTLY_PROBE_READER_ROUTE,@@ -80,7 +81,7 @@ interface PerTaskModelRoute {* chain visible rather than implying full resolveModel() coverage — can* never disagree with the resolved value.*/- narrowResolver?: (engine: BrainEngine) => Promise<{ model: string; source: 'config' | 'tier_default' }>;+ narrowResolver?: (engine: BrainEngine) => Promise<{ model: string; source: 'config' | 'tier_default' | 'measured' }>;}const PER_TASK_KEYS: PerTaskModelRoute[] = [@@ -102,7 +103,12 @@ const PER_TASK_KEYS: PerTaskModelRoute[] = [{ key: 'models.drift', tier: 'reasoning', description: 'Drift LLM judge (v0.29 scaffold)' },{ key: 'models.auto_think', tier: 'deep', description: 'Auto-think question answering' },{ key: 'models.think', tier: 'deep', description: '`gbrain think` synthesis op' },- { key: 'models.fence_repair', tier: 'deep', description: 'Model repair (Tier 3) of malformed facts/takes fence rows' },+ {+ key: 'models.fence_repair',+ tier: 'deep',+ description: 'Model repair (Tier 3) of malformed facts/takes fence rows; unset: the first measured model with a key, else none (off)',+ narrowResolver: async engine => { const r = await resolveFenceRepairModelWithSource(engine); return { model: r.model ?? 'none', source: r.source }; },+ },{ key: 'models.subagent', tier: 'subagent', description: '`gbrain agent run` subagent loop' },{ key: 'facts.extraction_model', tier: 'reasoning', description: 'Real-time facts extraction during sync' },{ key: 'models.eval.longmemeval', tier: 'reasoning', description: 'LongMemEval benchmark answer-gen' },@@ -224,7 +230,7 @@ async function buildReport(engine: BrainEngine): Promise<ModelsReport> {// so the label can never disagree with what `resolved` actually// reflects (previously a separate getConfig truthiness re-check).const { model: resolved, source: narrowSource } = await narrowResolver(engine);- const source = narrowSource === 'config' ? `config: ${key}` : `tier.${tier} (caller-specific)`;+ const source = narrowSource === 'config' ? `config: ${key}` : narrowSource === 'measured' ? 'measured default' : `tier.${tier} (caller-specific)`;const newer = narrowSource === 'config' ? newerAvailable(resolved, key) : undefined;per_task.push({ key, tier, resolved, source, description, ...(newer ? { newer_available: newer } : {}) });continue;diff --git a/src/core/ai/openai-latest.ts b/src/core/ai/openai-latest.tsindex 1f5abd4f08..2d8bef6c27 100644--- a/src/core/ai/openai-latest.ts+++ b/src/core/ai/openai-latest.ts@@ -115,6 +115,13 @@ export function parseOpenAIChatId(id: string): ParsedOpenAIChatId | null {return { id, family: [Number(m[1]), Number(m[2] ?? 0)], suffix };}+/**+ * Priced for exact metering where a feature names the model (the #6188 fence+ * repair default), but not eligible as a discovered tier default: one priced+ * member of a newer family would otherwise become every tier's default.+ */+const METERED_ONLY: ReadonlySet<string> = new Set(['gpt-6.1-sol']);+function familyCmp(a: [number, number], b: [number, number]): number {return a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1];}@@ -135,7 +142,7 @@ function pickBySuffix(members: ParsedOpenAIChatId[], order: readonly string[]):*/export function rankOpenAIChatModels(ids: string[],- priced: (id: string) => boolean = (id) => canonicalLookup(`openai:${id}`) !== undefined,+ priced: (id: string) => boolean = (id) => canonicalLookup(`openai:${id}`) !== undefined && !METERED_ONLY.has(id),): { tiers: OpenAITierPick | null; newestUnpriced?: string } {const parsed = ids.map(parseOpenAIChatId).filter((p): p is ParsedOpenAIChatId => p !== null);if (parsed.length === 0) return { tiers: null };diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 994e5c7ee4..40484936d7 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -65,6 +65,7 @@ import {type ChatFallbackPlane,} from './ai/chat-fallback-planes.ts';import { mergedProviderEnv } from './ai/provider-env.ts';+import { FENCE_REPAIR_MEASURED } from './fence-repair/measured.ts';/** The measured re-ingest page multiplier, as prose (scripts/measure-transcript-split-cost.ts: 4 → 27 pages on a 1 MB session). */export const TRANSCRIPT_REINGEST_MULTIPLIER = 'about 6.75x';@@ -220,9 +221,6 @@ const DOCTOR_ARGV = ['gbrain', 'doctor', '--only', BEHAVIOR_NOTICE_CODE, '--jsontype ChangeText = string | ((chain: ChainDisclosure | null, remote: boolean) => string | null);-/** #6188 T4: replace with the measured Tier 3 gate-pass and false-accept rates when the fence-repair eval lands. */-const FENCE_REPAIR_MEASURED = 'How often the model\'s rewrites are accepted is not yet measured.';-/** Every disclosed behavior change, with the release that introduced it. Append new rows; never edit a shipped `since`. */export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }> = [{ since: '0.60.68.0', text: (chain, remote) => {@@ -261,7 +259,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },{ since: '0.60.100.0', text: '`gbrain doctor` has a new `fence_integrity` check: it counts malformed facts and takes fences still waiting (held files, stored pages, unsynced checkout files) by the tier that would fix them, and warns when a source had 20 or more fences normalized in 7 days. Each doctor run scans stored pages and source checkouts for up to 10 seconds (`GBRAIN_DOCTOR_FENCE_TIMEOUT_MS`) and resumes where it stopped; until a scan finishes the check reports partial instead of ok. New settings `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00) cap model fence repair.' },- { since: '0.60.101.0', text: `Malformed facts and takes fences are now repaired automatically: the maintenance run repairs held files and stored pages on the owner host, and its first run after upgrading repairs every malformed fence it finds in each source, rewriting and committing those files (\`gbrain doctor --only fence_integrity\` counts them; \`gbrain repair fences\` previews the plan). A fence only a rewrite can realign sends just its header and those rows, never the rest of the page, to the configured chat model, within $0.05 per page and $1.00 per day (\`fences.repair.max_usd_per_page\`, \`fences.repair.max_usd_per_day\`); every rewrite passes validation gates before it is written. ${FENCE_REPAIR_MEASURED} \`gbrain config set fences.repair.llm false\` keeps fence rows away from the model; \`gbrain config set fences.repair.enabled false\` pauses automatic repair. On a managed source each repaired file is committed, so \`git revert\` undoes it (page history keeps the earlier version); turning these settings off stops future repairs and does not undo past ones.` },+ { since: '0.60.101.0', text: `Malformed facts and takes fences are now repaired automatically: the maintenance run repairs held files and stored pages on the owner host, and its first run after upgrading repairs every malformed fence it finds in each source, rewriting and committing those files (\`gbrain doctor --only fence_integrity\` counts them; \`gbrain repair fences\` previews the plan). A fence only a rewrite can realign sends just its header and those rows, never the rest of the page, to the repair model, within $0.30 per page and $1.00 per day (\`fences.repair.max_usd_per_page\`, \`fences.repair.max_usd_per_day\`); every rewrite passes validation gates before it is written. With \`models.fence_repair\` unset, the repair model is the first model the fence-repair eval measured as accurate enough that has a provider key on the brain host (\`gbrain models\` names it); with none, model repair stays off until the user sets \`models.fence_repair\`. ${FENCE_REPAIR_MEASURED} \`gbrain config set fences.repair.llm false\` keeps fence rows away from the model; \`gbrain config set fences.repair.enabled false\` pauses automatic repair. On a managed source each repaired file is committed, so \`git revert\` undoes it (page history keeps the earlier version); turning these settings off stops future repairs and does not undo past ones.` },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/fence-repair/config.ts b/src/core/fence-repair/config.tsindex 1ebefc415a..573232cf18 100644--- a/src/core/fence-repair/config.ts+++ b/src/core/fence-repair/config.ts@@ -12,7 +12,7 @@* fence rows to the configured chat model (Tier 3); false keeps it to the* free tiers everywhere and holds Tier 3 candidates with `llm_disabled`.*- * `fences.repair.max_usd_per_page` (default $0.05) and+ * `fences.repair.max_usd_per_page` (default $0.30) and* `fences.repair.max_usd_per_day` (default $1.00) cap model (Tier 3) fence* repair: per page, and per UTC day across every process through the daily* USD ledger. 0 means no Tier 3 spend. They are validated at `config set`@@ -27,7 +27,7 @@ export const FENCE_REPAIR_LLM_KEY = 'fences.repair.llm';export const FENCE_REPAIR_MAX_USD_PER_PAGE_KEY = 'fences.repair.max_usd_per_page';export const FENCE_REPAIR_MAX_USD_PER_DAY_KEY = 'fences.repair.max_usd_per_day';/** Defaults of the Tier 3 caps (USD). */-export const FENCE_REPAIR_DEFAULT_MAX_USD_PER_PAGE = 0.05;+export const FENCE_REPAIR_DEFAULT_MAX_USD_PER_PAGE = 0.3;export const FENCE_REPAIR_DEFAULT_MAX_USD_PER_DAY = 1;const USD_KEYS: readonly string[] = [FENCE_REPAIR_MAX_USD_PER_PAGE_KEY, FENCE_REPAIR_MAX_USD_PER_DAY_KEY];/** Every `fences.*` key `gbrain config set` accepts. */diff --git a/src/core/fence-repair/hold-fix.ts b/src/core/fence-repair/hold-fix.tsindex 1a123c552c..e77afed557 100644--- a/src/core/fence-repair/hold-fix.ts+++ b/src/core/fence-repair/hold-fix.ts@@ -23,6 +23,7 @@ import type { BrainEngine } from '../engine.ts';import type { Action, ActionInput } from '../agent-output.ts';import type { GitHoldRecord } from '../persistence/sync-holds.ts';import { FENCE_REPAIR_ENABLED_KEY, FENCE_REPAIR_LLM_KEY } from './config.ts';+import { FENCE_REPAIR_MEASURED_MODELS } from './measured.ts';import { FENCE_REASONS, renderFenceFix, type FenceMessageLocation } from './reasons.ts';import { fenceWhere } from './refusal.ts';import type { FenceReason, FenceTier } from './types.ts';@@ -76,7 +77,7 @@ export interface FenceHoldStatus {next_attempt_after: string | null;}-const PAID: readonly FenceReason[] = ['budget_exhausted', 'llm_disabled', 'no_pricing'];+const PAID: readonly FenceReason[] = ['budget_exhausted', 'llm_disabled', 'no_pricing', 'no_measured_model'];const OWNER: readonly FenceReason[] = ['owner_unavailable', 'owner_cli_required'];type HoldMeta = Pick<GitHoldRecord['meta'], 'reason' | 'line' | 'fence' | 'fence_repair'>;@@ -147,6 +148,8 @@ function paidStep(reason: FenceReason): { argv: string[]; inputs?: ActionInput[]if (reason === 'budget_exhausted') return { argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<usd>'],inputs: [{ name: 'usd', how: 'The daily cap in USD the user agreed to; read the current one with gbrain config get fences.repair.max_usd_per_day.' }] };if (reason === 'llm_disabled') return { argv: ['gbrain', 'config', 'set', 'fences.repair.llm', 'true'] };+ if (reason === 'no_measured_model') return { argv: ['gbrain', 'config', 'set', 'models.fence_repair', '<model>'],+ inputs: [{ name: 'model', how: `The provider:model the user chooses to trust with fence repair. Measured accurate enough: ${FENCE_REPAIR_MEASURED_MODELS.join(', ')}; each needs its provider's key.` }] };return { argv: ['gbrain', 'pricing', 'set', '<model>', '--input', '<usd>', '--output', '<usd>'],inputs: [{ name: 'model', how: 'The fence repair model: models.fence_repair in gbrain models --json.' },{ name: 'usd', how: "The provider's price in USD per 1M input tokens after --input and per 1M output tokens after --output, from its pricing page." }] };@@ -156,6 +159,7 @@ function paidStep(reason: FenceReason): { argv: string[]; inputs?: ActionInput[]function paidWait(reason: FenceReason): string {if (reason === 'budget_exhausted') return "today's fence repair budget (fences.repair.max_usd_per_day) is spent";if (reason === 'llm_disabled') return 'model repair is off (fences.repair.llm false)';+ if (reason === 'no_measured_model') return 'no model measured accurate enough for fence repair has a provider key here and models.fence_repair is unset';return 'a fence repair spend cap is set but gbrain has no price for the repair model, so it will not call it';}diff --git a/src/core/fence-repair/llm.ts b/src/core/fence-repair/llm.tsindex 20de683c81..a4b0f3f886 100644--- a/src/core/fence-repair/llm.ts+++ b/src/core/fence-repair/llm.ts@@ -18,32 +18,44 @@* consumed), `llm_empty`, `llm_refused` (refusal or content-filter stop, or a* prose refusal), `llm_malformed` (no single table, wrong header, prose),* `llm_truncated` (any stop other than a normal end, rejected even if the- * text parses). A table with the wrong number of rows is a gate (e) failure,- * so it earns the one corrective re-ask like any other gate failure.+ * text parses), `llm_declined` (the single word HOLD: a row has more than one+ * reasonable reading, so the model declines instead of guessing). A table+ * with the wrong number of rows is a gate (e) failure.*- * The corrective re-ask repeats the conversation with the model's own answer- * and names the failed gate letter and row numbers only.+ * The corrective re-ask (only after a structural failure, gate (a) or (e))+ * repeats the conversation with the model's own answer and names the failed+ * gate letter and row numbers only.+ *+ * The output ceiling is the table's size plus, for a model whose reasoning a+ * call cannot switch off, a reasoning allowance; the cost estimate uses the+ * ceiling the gateway will actually send, so the caps reserve the worst case.** Pure helpers (`tier3Requests`, `buildTier3Prompt`, `extractSingleTable`,* `spliceTier3`) do no I/O; `callTier3` is the one gateway call, testable* through the gateway's chat transport seam (`__setChatTransportForTests`).*/-import { chat, type ChatMessage, type ChatResult } from '../ai/gateway.ts';+import { chat, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS, type ChatMessage, type ChatResult } from '../ai/gateway.ts';+import { thinkingOffMaxOutputTokens, thinkingOffNamespace } from '../ai/thinking-off.ts';import { isSeparatorRow, parseRowCells } from '../fence-shared.ts';import { sectionsOf } from './page-checks.ts';import { extractRawRows, primaryFence, type RawFence, type RawRow } from './raw-rows.ts';import { ALLOWED, BASE_WIDTH, CANONICAL_HEADER, COLUMNS, COLUMN_DEFAULTS } from './schema.ts';-import { GATE_REASONS } from './reasons.ts';+import { FENCE_REASON_CODES, FENCE_REASONS, GATE_REASONS } from './reasons.ts';import type { FenceIssue, FenceKind, FencePage, FenceReason, FenceSection, GateLetter } from './types.ts';/** Bump when the prompt text changes: it is part of the attempt-memo key, so a new prompt retries rejected pages. */-export const FENCE_REPAIR_PROMPT_VERSION = 1;+export const FENCE_REPAIR_PROMPT_VERSION = 2;-/** Residual reasons a model may clear (everything else is manual or the resolver's). */-export const TIER3_REASONS: ReadonlySet<FenceReason> = new Set(['header_unmapped', 'no_header', 'row_before_header', 'short_row', 'extra_cells']);+/** Residual reasons a model may clear: the screen reasons whose tier is `llm` (everything else is manual or the resolver's). */+export const TIER3_REASONS: ReadonlySet<FenceReason> = new Set(FENCE_REASON_CODES.filter(reason => FENCE_REASONS[reason].stage === 'screen' && FENCE_REASONS[reason].tier === 'llm'));const FENCE_LEVEL: ReadonlySet<FenceReason> = new Set(['header_unmapped', 'no_header']);-export type Tier3Failure = 'llm_unavailable' | 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_truncated';+export type Tier3Failure = 'llm_unavailable' | 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_truncated' | 'llm_declined';++/** The whole answer a model gives to decline (prompt rule 8). */+export const TIER3_DECLINE = 'HOLD';+/** Output tokens a reasoning model may spend thinking before it writes the table. */+export const TIER3_REASONING_TOKENS = 2048;/** One fence the model is asked to repair. */export interface Tier3Request {@@ -100,11 +112,11 @@ export function tier3Requests(page: FencePage, issues: readonly FenceIssue[], pareturn { requests, ineligible };}-/** Wide when the header names a wide-layout column, or (no header) when the rows that parse carry more than the narrow width. */+/** Wide when the header names a wide-layout column, or (no header) when a row as written has more cells than the narrow width. */function wideLayout(kind: FenceKind, fence: RawFence): boolean {const base = BASE_WIDTH[kind];if (fence.header) return fence.columns.some(column => column !== null && COLUMNS[kind].indexOf(column) >= base);- return fence.rows.some(row => row.accepted && row.cells.length > base);+ return fence.rows.some(row => row.cells.length > base);}/** Non-blank lines inside the fence that are neither the header, a separator nor a data row: rebuilding the table would drop them. */@@ -140,7 +152,7 @@ export function buildTier3Prompt(req: Tier3Request): { system: string; user: strconst system = [`You repair one malformed markdown table from a gbrain ${req.kind} fence. You move cells into the right columns and supply the canonical header; you never change what a cell says.`,'',- 'Return exactly one markdown table and nothing else: no prose, no explanation, no code fence.',+ `Return exactly one markdown table and nothing else (or the single word ${TIER3_DECLINE}, rule 8): no prose, no explanation, no code fence.`,'The table starts with this header and separator, unchanged:',header,separator,@@ -155,6 +167,7 @@ export function buildTier3Prompt(req: Tier3Request): { system: string; user: str'5. Never invent, translate, summarize or correct a value. A cell you cannot place goes in the column it was written under.',`6. This page is ${req.pageVisibility}-visible. A row's visibility may be world only when that row already says world or public and the page is world-visible; otherwise keep what the row says or leave it empty.`,'7. Write a literal | inside a cell as \\|.',+ `8. If any row has more than one reasonable reading (two values for one column, or a cell that fits more than one column), return only the single word ${TIER3_DECLINE} instead of a table.`,'','Allowed values per column:',vocabulary(req.kind),@@ -173,18 +186,32 @@ export function buildTier3Prompt(req: Tier3Request): { system: string; user: strreturn { system, user };}-/** The follow-up after a gate rejection: the gate letter, its reason code and row numbers only. */+/** The follow-up after a structural gate rejection: the gate letter, its reason code and row numbers only. */export function correctionMessage(gate: GateLetter, rows: readonly number[]): string {return `Your table was rejected by validation gate (${gate}) ${GATE_REASONS[gate]}${rows.length ? ` at row(s) ${rows.join(', ')}` : ''}: ${GATE_TEXT[gate]}. `- + 'Return the corrected full table following every rule above. Output only the table.';+ + `Return the corrected full table following every rule above, or ${TIER3_DECLINE} if a row has more than one reasonable reading. Output only the table or ${TIER3_DECLINE}.`;+}++/** The model may reason whatever the call asks: a thinking-by-default model, or a route with no per-call thinking switch. */+function mayReason(model: string): boolean {+ return isThinkingModel(model) || !thinkingOffNamespace(model);}-/** Token bounds for one call: the prompt's size and an output ceiling sized from the rows sent. */-export function tier3TokenBudget(req: Tier3Request, prior?: { answer: string }): { inputTokens: number; maxOutputTokens: number } {+/**+ * Token bounds for one call: the prompt's size, and the output ceiling the+ * gateway will send: the table's size (from the rows sent), plus+ * TIER3_REASONING_TOKENS for a model that may reason, raised to the+ * gateway's thinking headroom where a thinking model's route cannot switch+ * thinking off. Estimates and the caps use this ceiling, so they reserve the+ * worst case.+ */+export function tier3TokenBudget(req: Tier3Request, model: string, prior?: { answer: string }): { inputTokens: number; maxOutputTokens: number } {const prompt = buildTier3Prompt(req);const rowChars = req.rows.reduce((sum, row) => sum + row.text.length, 0) + headerOf(req).header.length * 2;const inputChars = prompt.system.length + prompt.user.length + (prior ? prior.answer.length + 400 : 0);- return { inputTokens: Math.ceil(inputChars / 3) + 64, maxOutputTokens: Math.min(4096, Math.max(512, Math.ceil(rowChars * 1.5 / 3) + 256)) };+ const table = Math.min(4096, Math.max(512, Math.ceil(rowChars * 1.5 / 3) + 256));+ const requested = table + (mayReason(model) ? TIER3_REASONING_TOKENS : 0);+ return { inputTokens: Math.ceil(inputChars / 3) + 64, maxOutputTokens: thinkingOffMaxOutputTokens(model, requested, isThinkingModel(model), THINKING_MODEL_MAX_OUTPUT_TOKENS) };}export interface Tier3Table { header: string; separator: string; rows: string[] }@@ -195,11 +222,12 @@ const REFUSAL = /\b(cannot|can['’]t|unable to|won['’]t|will not|refuse|not a* The single table in a model answer, or why there is none. A single* wrapping code fence is stripped; any other non-table line is prose.*/-export function extractSingleTable(text: string, req: Pick<Tier3Request, 'kind' | 'layout'>): { ok: true; table: Tier3Table } | { ok: false; reason: 'llm_empty' | 'llm_refused' | 'llm_malformed' } {+export function extractSingleTable(text: string, req: Pick<Tier3Request, 'kind' | 'layout'>): { ok: true; table: Tier3Table } | { ok: false; reason: 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_declined' } {let body = text.trim();if (!body) return { ok: false, reason: 'llm_empty' };const fenced = /^```[\w-]*\n([\s\S]*?)\n```$/.exec(body);if (fenced) body = fenced[1]!.trim();+ if (body.replace(/[.*_`]/g, '').trim() === TIER3_DECLINE) return { ok: false, reason: 'llm_declined' };const lines = body.split('\n').map(line => line.trim()).filter(Boolean);if (!lines.some(line => line.startsWith('|'))) return { ok: false, reason: REFUSAL.test(body) ? 'llm_refused' : 'llm_malformed' };if (lines.some(line => !line.startsWith('|')) || lines.length < 2) return { ok: false, reason: 'llm_malformed' };@@ -245,12 +273,12 @@ export interface Tier3CallOptions {signal?: AbortSignal;}-/** One gateway call (no tools, no fallback model, thinking off; no temperature, which reasoning models refuse), classified. */+/** One gateway call (no tools, no fallback model, thinking off where the route allows; no temperature, which reasoning models refuse), classified. */export async function callTier3(req: Tier3Request, opts: Tier3CallOptions): Promise<Tier3Answer> {const prompt = buildTier3Prompt(req);const messages: ChatMessage[] = [{ role: 'user', content: prompt.user }];if (opts.correction) messages.push({ role: 'assistant', content: opts.correction.answer }, { role: 'user', content: correctionMessage(opts.correction.gate, opts.correction.rows) });- const budget = tier3TokenBudget(req, opts.correction ? { answer: opts.correction.answer } : undefined);+ const budget = tier3TokenBudget(req, opts.model, opts.correction ? { answer: opts.correction.answer } : undefined);let result: ChatResult;try {result = await chat({ model: opts.model, system: prompt.system, messages, maxTokens: budget.maxOutputTokens, allowFallback: false,diff --git a/src/core/fence-repair/measured.ts b/src/core/fence-repair/measured.tsnew file mode 100644index 0000000000..25a83a596d--- /dev/null+++ b/src/core/fence-repair/measured.ts@@ -0,0 +1,17 @@+/**+ * What the Tier 3 fence-repair eval measured (#6188 T4,+ * evals/fence-repair-tier3/; verdicts in gbrain-evals). The next eval run+ * updates both constants together.+ *+ * `FENCE_REPAIR_MEASURED_MODELS`: the models that met the preregistered+ * rule (gate-pass at least 80%, false accepts at most 1%), best first. With+ * `models.fence_repair` unset, model repair uses the first one the brain has+ * a provider key for; with none, model repair stays off by default+ * (`no_measured_model`). An explicit `models.fence_repair` always runs.+ *+ * `FENCE_REPAIR_MEASURED`: the sentence the behavior-change notice prints+ * about how often the model's rewrites are accepted.+ */+export const FENCE_REPAIR_MEASURED_MODELS: readonly string[] = ['openai:gpt-6.1-sol', 'anthropic:claude-fable-5-1'];++export const FENCE_REPAIR_MEASURED = 'How often the model\'s rewrites are accepted is not yet measured.';diff --git a/src/core/fence-repair/model.ts b/src/core/fence-repair/model.tsnew file mode 100644index 0000000000..29ff7df635--- /dev/null+++ b/src/core/fence-repair/model.ts@@ -0,0 +1,35 @@+/**+ * #6188: the Tier 3 fence-repair model. An explicit `models.fence_repair`+ * always runs (new and unpriced models included). Unset, it is the first+ * model the fence-repair eval measured as accurate enough+ * (`FENCE_REPAIR_MEASURED_MODELS`) whose provider key the brain has+ * (environment or config file; `env` replaces both, for tests), and none when+ * there is no such key, so model repair stays off (`no_measured_model`) until+ * the user picks a model.+ */+import type { BrainEngine } from '../engine.ts';+import { loadConfig, type GBrainConfig } from '../config.ts';+import { mergedProviderEnv } from '../ai/provider-env.ts';+import { providerKeyReady, resolveModel, TIER_DEFAULTS } from '../model-config.ts';+import { FENCE_REPAIR_MEASURED_MODELS } from './measured.ts';++export const FENCE_REPAIR_MODEL_KEY = 'models.fence_repair';++export async function resolveFenceRepairModelWithSource(engine: Pick<BrainEngine, 'getConfig'>, env?: Record<string, string | undefined>): Promise<{ model: string | null; source: 'config' | 'measured' }> {+ const explicit = await engine.getConfig(FENCE_REPAIR_MODEL_KEY).catch(() => null);+ if (explicit?.trim()) return { model: await resolveModel(engine, { configKey: FENCE_REPAIR_MODEL_KEY, tier: 'deep', fallback: TIER_DEFAULTS.deep }), source: 'config' };+ const keys = env ? Object.fromEntries(Object.entries(env).filter((e): e is [string, string] => !!e[1])) : mergedProviderEnv(fileConfig(), process.env);+ return { model: FENCE_REPAIR_MEASURED_MODELS.find(model => providerKeyReady(model, keys)) ?? null, source: 'measured' };+}++export async function resolveFenceRepairModel(engine: Pick<BrainEngine, 'getConfig'>, env?: Record<string, string | undefined>): Promise<string | null> {+ return (await resolveFenceRepairModelWithSource(engine, env)).model;+}++function fileConfig(): GBrainConfig | null {+ try {+ return loadConfig();+ } catch {+ return null;+ }+}diff --git a/src/core/fence-repair/normalize.ts b/src/core/fence-repair/normalize.tsindex 908ce25831..7ccc68f8e3 100644--- a/src/core/fence-repair/normalize.ts+++ b/src/core/fence-repair/normalize.ts@@ -2,9 +2,10 @@* Tier 1 fence normalizer (#6188): pure, deterministic, free.** `normalizeFences(page, ctx)` fixes what has one obvious meaning (a missing- * end marker with nothing after the table, two-dash takes markers, row-number- * repairs, header aliases and order, header-level write defaults, enum,- * kind and holder synonyms, percent confidences) and reports the rest as+ * end marker with nothing after the table, two-dash takes markers, stray+ * empty cells with exactly one valid deletion, row-number repairs, header+ * aliases and order, header-level write defaults, enum, kind and holder+ * synonyms, percent confidences) and reports the rest as* location-only residual issues. A page whose fences already compile is* returned unchanged (the same object), and every other byte outside the* edited cells, markers and headers is kept verbatim. The result is a fixed@@ -16,11 +17,12 @@import { contentPass } from './content.ts';import { sectionsOf, strictFailures, strictPageClean } from './page-checks.ts';import { extractRawRows, rowNumOf } from './raw-rows.ts';+import { strayCellPass } from './stray-cells.ts';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 = 1;+export const FENCE_RULES_VERSION = 2;export interface NormalizeResult<T extends FencePage> {page: T;@@ -40,8 +42,9 @@ export function normalizeFences<T extends FencePage>(page: T, ctx: FenceCtx): Noconst texts: Record<FenceSection, string> = { body: '', timeline: '' };for (const [section, text] of sectionsOf(page)) {const pass = structuralPass(text, section);- texts[section] = pass.text;- fixes.push(...pass.fixes);+ const stray = strayCellPass(pass.text, section);+ texts[section] = stray.text;+ fixes.push(...pass.fixes, ...stray.fixes);residual.push(...pass.residual);}const content = contentPass(texts, ctx, () => Math.max(nextFreeRowNum(page, ctx.storedRows), maxHidden(ctx) + 1));diff --git a/src/core/fence-repair/reasons.ts b/src/core/fence-repair/reasons.tsindex 5ffa1ffb7f..06302277c7 100644--- a/src/core/fence-repair/reasons.ts+++ b/src/core/fence-repair/reasons.ts@@ -11,6 +11,7 @@* never quote a cell.*/import type { Actor } from '../agent-output.ts';+import { FENCE_REPAIR_MEASURED_MODELS } from './measured.ts';import type { FenceIssue, FenceKind, FenceReason, FenceSection, FenceTier, GateLetter } from './types.ts';export interface FenceReasonSpec {@@ -54,7 +55,8 @@ const SPECS: Record<FenceReason, Omit<FenceReasonSpec, 'docs'>> = {no_header: entry(tier3, 'The {fence} fence in the {section} at line {line} has rows but no header row. Add the canonical header as the first table line. ' + REPAIR),row_before_header: entry(tier3, 'Row(s) {rows} of the {fence} fence in the {section} sit above the header (line {line}). Move them below the header. ' + REPAIR),short_row: entry(tier3, 'Row(s) {rows} of the {fence} fence in the {section} (line {line}) are missing a cell in the middle of the row, so its columns are ambiguous. Add the missing cell so every column lines up. ' + REPAIR),- extra_cells: entry(tier3, 'Row(s) {rows} of the {fence} fence in the {section} (line {line}) have more cells than the header, often an unescaped `|` in a cell. Escape it as `\\|` or remove the extra cell. ' + REPAIR),+ extra_cells: entry(manual, 'Row(s) {rows} of the {fence} fence in the {section} (line {line}) have more cells than the header, and removing empty cells does not line them up. Often an unescaped `|` cut a cell, usually the claim, in two: write it as `\\|` to join the cell again, or remove the extra cell. gbrain does not guess which cell moved.'),+ claim_split: entry(manual, 'Column `kind` of row(s) {rows} in the {fence} fence ({section}, line {line}) holds text, not a kind word: often the end of a claim an unescaped `|` cut in two, with the kind cell missing. Join that text back into the claim with `\\|` and write the kind, one of {allowed}.'),holder_unresolved: entry({ stage: 'screen', tier: 'resolver', manualOnly: false, autoRetry: true },'Column `who` of row(s) {rows} in the {fence} fence ({section}, line {line}) is not a holder gbrain recognizes. Write `world`, `brain`, `people/<slug>` or `companies/<slug>`.'),missing_begin: entry(manual, 'The {fence} fence in the {section} has an end marker at line {line} with no begin marker before it. Add the begin marker above the table, or delete the stray end marker.'),@@ -83,7 +85,9 @@ const SPECS: Record<FenceReason, Omit<FenceReasonSpec, 'docs'>> = {llm_refused: entry(run(false), 'The repair model declined to repair the {fence} fence. Fix row(s) {rows} by hand; ' + BY_HAND),llm_malformed: entry(run(false), 'The repair model did not return a single table for the {fence} fence. Fix row(s) {rows} by hand; ' + BY_HAND),llm_truncated: entry(run(false), 'The repair model stopped before finishing the {fence} fence. Fix row(s) {rows} by hand; ' + BY_HAND),+ llm_declined: entry(run(false), 'The repair model found a row of the {fence} fence with more than one reasonable reading and declined to guess. Fix row(s) {rows} by hand; ' + BY_HAND),llm_disabled: entry(run(false), 'Model repair is off (`fences.repair.llm`). Fix row(s) {rows} by hand (' + BY_HAND + '), or ask the user before running `gbrain config set fences.repair.llm true`.', { paid: true }),+ no_measured_model: entry(run(false), `No model measured accurate enough for fence repair (${FENCE_REPAIR_MEASURED_MODELS.join(', ')}) has a provider key on this brain and \`models.fence_repair\` is unset, so row(s) {rows} stay held. Fix them by hand (${BY_HAND}), or ask the user which model to trust before setting it: \`gbrain config set models.fence_repair <provider:model>\`.`, { paid: true }),budget_exhausted: entry(run(true), 'The daily fence-repair budget is spent; repairs resume after 00:00 UTC. Raising it is the user\'s call: `gbrain config set fences.repair.max_usd_per_day <usd>`.', { paid: true }),no_pricing: entry(run(false), 'A spend cap is set but gbrain has no price for the repair model. Look up its price and run `gbrain pricing set <model> --input <usd> --output <usd>` on the brain host.', { paid: true }),ledger_unavailable: entry(run(true), 'The spend ledger could not be read, so no model call was made. The next repair run retries.'),diff --git a/src/core/fence-repair/repair-tiers.ts b/src/core/fence-repair/repair-tiers.tsindex 828aaf5ff8..1f0e78f8a0 100644--- a/src/core/fence-repair/repair-tiers.ts+++ b/src/core/fence-repair/repair-tiers.ts@@ -117,13 +117,13 @@ function scanIssue(page: FencePage): Pick<FenceIssue, 'fence' | 'section' | 'reareturn { fence: defect.fence, section: defect.section, reason: defect.reason, line: defect.line };}-/** The first call's estimate for every request of a page (the per-page cap also covers one corrective re-ask). */+/** The first call's worst-case estimate for every request of a page. */export function tier3Estimate(requests: readonly Tier3Request[], pricing: { model: string; overrides?: PricingOverrides; capSource: CapSource }):{ ok: true; usd: number; estimated: boolean } | { ok: false; reason: 'no_pricing'; guidance: NoPricingGuidance } {let usd = 0;let estimated = false;for (const req of requests) {- const budget = tier3TokenBudget(req);+ const budget = tier3TokenBudget(req, pricing.model);const quote = estimateChatCallUsd({ model: pricing.model, inputTokens: budget.inputTokens, maxOutputTokens: budget.maxOutputTokens, overrides: pricing.overrides, capSource: pricing.capSource });if (!quote.ok) return quote;usd += quote.quote.usd;@@ -165,7 +165,8 @@ export function tier3Memo(target: FenceTarget, model: string): string {/*** Tier 3 for one candidate: claim the attempt (a rejected memo returns its* stored verdict and spends nothing), call the model per fence under the- * ledger, splice, normalize, validate, and re-ask once with the failed gate.+ * ledger, splice, normalize, validate, and re-ask once after a structural+ * failure (gate (a) or (e)); any other gate, or a HOLD, is final.* On success the claim is left `settled`: the caller publishes it after the* write lands, or marks it transient when the write could not run.*/@@ -196,7 +197,7 @@ export async function runTier3(target: FenceTarget, analysis: Extract<FenceAnalyfor (const index of indexes) {const req = analysis.requests[index]!;const prior = correction ? tables.get(index)!.text : undefined;- const budget = tier3TokenBudget(req, prior !== undefined ? { answer: prior } : undefined);+ const budget = tier3TokenBudget(req, deps.model, prior !== undefined ? { answer: prior } : undefined);const quote = estimateChatCallUsd({ model: deps.model, inputTokens: budget.inputTokens, maxOutputTokens: budget.maxOutputTokens, overrides: deps.overrides, capSource: deps.capSource });if (!quote.ok) return transient('no_pricing', `A spend cap is set but gbrain has no price for ${deps.model}; no call was made.`, { guidance: quote.guidance });const estimate = quote.quote.usd;@@ -233,6 +234,7 @@ export async function runTier3(target: FenceTarget, analysis: Extract<FenceAnalyconst done = await deps.store.settled(claim);if (done.ok) claim = done.claim;if (!answer.ok && answer.reason === 'llm_unavailable') return transient('llm_unavailable', `The repair model was unavailable (${answer.error ?? 'provider error'}); the next run retries.`);+ if (!answer.ok && answer.reason === 'llm_declined') return reject('llm_declined', 'The repair model declined: a row has more than one reasonable reading, so it needs a person.');if (!answer.ok && answer.reason !== 'row_count_changed') return reject(answer.reason, `The repair model's answer was unusable (${answer.reason}).`);tables.set(index, { table: answer.table, text: answer.text });}@@ -258,7 +260,8 @@ export async function runTier3(target: FenceTarget, analysis: Extract<FenceAnalyconst cleared = [...new Set(analysis.residual.map(i => i.reason))].sort();return { ok: true, after, spentUsd: spent, claim, cleared };}- if (round === 0) { correction = failure; continue; }+ // Only a structural failure earns the re-ask: naming gate (f) steers a model toward whatever placement the gates allow.+ if (round === 0 && (failure!.gate === 'a' || failure!.gate === 'e')) { correction = failure; continue; }return reject(GATE_REASONS[failure!.gate], `LLM repair rejected by gate ${failure!.gate}; needs a manual edit${failure!.rows.length ? ` at row(s) ${failure!.rows.join(', ')}` : ''}.`, failure!.gate, failure!.rows);}return reject('still_invalid', 'LLM repair did not settle.');diff --git a/src/core/fence-repair/rules.ts b/src/core/fence-repair/rules.tsindex 80ed48cc13..2a509cc61c 100644--- a/src/core/fence-repair/rules.ts+++ b/src/core/fence-repair/rules.ts@@ -63,6 +63,10 @@ function residual(plan: RowPlan, kind: FenceKind, column: string, reason: FenceR}function planFactsKind(plan: RowPlan, kindCell: CellText, contextCell: CellText | undefined): void {+ if (!kindWord(kindCell.text)) {+ plan.issues.push({ column: 'kind', reason: 'claim_split', allowed: ALLOWED.facts.kind });+ return;+ }const before = contextCell?.text ?? '';const after = appendOriginalKind(before, kindCell.text);if (supersededRef(before) !== supersededRef(after) || forgotten(before) !== forgotten(after)) {@@ -73,6 +77,17 @@ function planFactsKind(plan: RowPlan, kindCell: CellText, contextCell: CellTextif (after !== before) plan.changes.push({ column: 'context', raw: appendOriginalKind(contextCell?.raw ?? '', kindCell.raw), class: 'kind_map' });}+/**+ * A facts kind cell `kind_map` may read: at most three words, no sentence+ * punctuation, no markdown link or strikethrough. Anything longer is more+ * likely the end of a claim an unescaped `|` cut in two (with the kind cell+ * missing, the row keeps its width), so it is never stored as a kind note.+ */+export function kindWord(text: string): boolean {+ const word = text.trim();+ return word.split(/\s+/).length <= 3 && !/[.,;:!?]/.test(word) && !/\[[^\]]*\]\(|~~/.test(word);+}+function forgotten(context: string): boolean {return /^forgotten\s*:/i.test(context.trim());}@@ -102,7 +117,7 @@ function residualReason(kind: FenceKind, column: string, text: string): FenceReaexport function ruleOutputs(kind: FenceKind, column: string, text: string, ctx: FenceCtx): Array<{ text: string; class: FixClass }> {switch (column) {case 'kind': {- const mapped = kind === 'facts' ? factsKindMap(text) : takesKindMap(text, ctx.takesPackKinds);+ const mapped = kind === 'facts' ? (kindWord(text) ? factsKindMap(text) : null) : takesKindMap(text, ctx.takesPackKinds);return mapped ? [{ text: mapped, class: 'kind_map' }] : [];}case 'visibility':diff --git a/src/core/fence-repair/stray-cells.ts b/src/core/fence-repair/stray-cells.tsnew file mode 100644index 0000000000..e285608aee--- /dev/null+++ b/src/core/fence-repair/stray-cells.ts@@ -0,0 +1,80 @@+/**+ * Tier 1 `stray_empty_cell` (#6188): a row with more cells than its fence's+ * layout loses empty cells, but only when exactly one choice of empty cells+ * to delete leaves every validated column (`#`, kind, confidence,+ * visibility, notability, claim_value; takes kind, holder, weight) valid.+ * No choice, or two that differ, leaves the row as written, so it stays+ * residual `extra_cells` (manual): a person decides, because no gate can tell+ * a claim cut in two by an unescaped `|` from a misplaced cell.+ *+ * Only rows read by position qualify: a balanced primary fence whose header+ * is the canonical layout. Each deletion removes the empty cell's slot+ * (its leading pipe and whitespace), so every other byte of the row stays.+ */+import { extractRawRows, rowNumOf, type RawCell, type RawFence, type RawRow } from './raw-rows.ts';+import { BASE_WIDTH, cellValid, COLUMNS } from './schema.ts';+import { applyEdits, fenceBlocked, type Edit } from './structure.ts';+import type { FenceFix, FenceKind, FenceSection } from './types.ts';++/** Rows with more extra cells than this are left alone (the choices grow combinatorially). */+const MAX_EXTRA = 4;++export function strayCellPass(text: string, section: FenceSection): { text: string; fixes: FenceFix[] } {+ const raw = extractRawRows(text, section);+ const edits: Edit[] = [];+ const fixes: FenceFix[] = [];+ for (const fence of raw.fences) {+ if (!fence.primary || !fence.end || fence.begin.nearMiss || fence.end.nearMiss || !fence.header || fence.needsRewrite || fenceBlocked(raw, fence)) continue;+ for (const row of fence.rows) {+ if (row.beforeHeader || row.shape !== 'extra_cells') continue;+ const removed = uniqueDeletion(fence, row);+ if (!removed) continue;+ edits.push(...removed.map(cell => slotOf(text, row, cell)));+ fixes.push({ fence: fence.kind, section, row: rowNumOf(fence, row), column: null, line: row.line, class: 'stray_empty_cell' });+ }+ }+ return { text: edits.length ? applyEdits(text, edits) : text, fixes };+}++/** The empty cells to delete, when exactly one distinct result makes every validated column valid. */+function uniqueDeletion(fence: RawFence, row: RawRow): RawCell[] | null {+ const kind = fence.kind;+ const headerLen = fence.columns.length;+ const widths = new Set([Math.max(headerLen, BASE_WIDTH[kind])]);+ if (kind === 'facts' && headerLen < COLUMNS.facts.length && row.cells.length > COLUMNS.facts.length) widths.add(COLUMNS.facts.length);+ const empty = row.cells.flatMap((cell, i) => (cell.raw ? [] : [i]));+ const valid = new Map<string, number[]>();+ for (const width of widths) {+ const extra = row.cells.length - width;+ if (extra < 1 || extra > MAX_EXTRA || extra > empty.length) continue;+ for (const drop of combinations(empty, extra)) {+ const kept = row.cells.filter((_, i) => !drop.includes(i)).map(cell => cell.text);+ if (!kept.every((cell, j) => columnValid(fence, kind, j, cell))) continue;+ const key = JSON.stringify(kept);+ if (!valid.has(key)) valid.set(key, drop);+ }+ }+ if (valid.size !== 1) return null;+ const [drop] = valid.values();+ return drop!.map(i => row.cells[i]!);+}++/** The cell at index `j` passes its column's strict check (a cell with no column, or a free-text one, passes). */+function columnValid(fence: RawFence, kind: FenceKind, j: number, text: string): boolean {+ const column = kind === 'takes' && j >= BASE_WIDTH.takes ? fence.columns[j] ?? null : COLUMNS[kind][j] ?? null;+ return column === null || cellValid(kind, column, text);+}++function combinations(items: readonly number[], k: number): number[][] {+ if (k === 0) return [[]];+ return items.flatMap((item, i) => combinations(items.slice(i + 1), k - 1).map(rest => [item, ...rest]));+}++/** The whole slot of an empty cell: from its leading pipe up to (not including) the next pipe or the row end. */+function slotOf(text: string, row: RawRow, cell: RawCell): Edit {+ let start = cell.start;+ while (start > row.start && text[start - 1] !== '|') start--;+ let end = cell.start;+ while (end < row.end && text[end] !== '|') end++;+ return { start: start - 1, end, text: '' };+}diff --git a/src/core/fence-repair/types.ts b/src/core/fence-repair/types.tsindex 9513eecb59..82b7f9de3c 100644--- a/src/core/fence-repair/types.ts+++ b/src/core/fence-repair/types.ts@@ -24,6 +24,7 @@ export type GateLetter = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g';export type FixClass =| 'close_fence'| 'marker_form'+ | 'stray_empty_cell'| 'renumber'| 'column_default'| 'header_alias'@@ -36,18 +37,18 @@ export type FixClass =/** Every fence reason; `FENCE_REASONS` (reasons.ts) holds one entry per code. */export type FenceReason =// Screen residual, Tier 3.- | 'header_unmapped' | 'no_header' | 'row_before_header' | 'short_row' | 'extra_cells'+ | 'header_unmapped' | 'no_header' | 'row_before_header' | 'short_row'// Screen residual, Tier 2 then manual.| 'holder_unresolved'// Screen residual, manual only.- | 'missing_begin' | 'split_rows' | 'unclosed_trailing_content' | 'marker_near_miss' | 'repeated_marker'+ | 'extra_cells' | 'claim_split' | 'missing_begin' | 'split_rows' | 'unclosed_trailing_content' | 'marker_near_miss' | 'repeated_marker'| 'takes_in_facts' | 'superseded_ambiguous' | 'enum_unmapped' | 'weight_missing' | 'holder_missing'| 'confidence_out_of_range' | 'claim_value_invalid' | 'takes_kind_unsupported'// Preparation and publication.| 'unparseable' | 'row_collision' | 'quoted_fence_rows' | 'stored_row_collision'| 'withdrawn_claim_in_malformed_fence' | 'target_fence_malformed' | 'prepare_time' | 'normalizer_failed'// Repair runs.- | 'llm_unavailable' | 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_truncated' | 'llm_disabled'+ | 'llm_unavailable' | 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_truncated' | 'llm_declined' | 'llm_disabled' | 'no_measured_model'| 'budget_exhausted' | 'no_pricing' | 'ledger_unavailable' | 'owner_unavailable' | 'owner_cli_required'| 'sync_in_progress' | 'time_budget' | 'changed_since_read' | 'changed_since_preview'// Validator gates.diff --git a/src/core/model-pricing.ts b/src/core/model-pricing.tsindex 235f3daaa5..005d7fda88 100644--- a/src/core/model-pricing.ts+++ b/src/core/model-pricing.ts@@ -143,6 +143,11 @@ export const CANONICAL_PRICING: Record<string, ModelPricing> = {'openai:gpt-5.6-sol': { input: 5.00, output: 30.00 },'openai:gpt-5.6-terra': { input: 2.50, output: 15.00 },'openai:gpt-5.6-luna': { input: 0.20, output: 1.20 },+ // gpt-6.1-sol: list rate from platform.openai.com/docs/models/gpt-6.1-sol+ // (checked 2026-10-06; short-context standard tier). Priced so the fence+ // repair default (#6188) meters exactly; it is NOT a tier default yet+ // (openai-latest.ts METERED_ONLY keeps discovery on the gpt-5.6 family).+ 'openai:gpt-6.1-sol': { input: 2.00, output: 10.00 },// ── Google ─────────────────────────────────────────────────────────────// `gemini-1.5-pro` was retired by Google (#3510); kept so historicaldiff --git a/src/core/repair/fences.ts b/src/core/repair/fences.tsindex 58c69ba97b..bf4cfb362e 100644--- a/src/core/repair/fences.ts+++ b/src/core/repair/fences.ts@@ -37,7 +37,8 @@ import type { OperationContext } from '../ops/contract.ts';import { trustedCliRequired } from '../ops/op-fix.ts';import { shellQuote, type Action } from '../agent-output.ts';import { parseMarkdown } from '../markdown.ts';-import { resolveModel, TIER_DEFAULTS } from '../model-config.ts';+import { FENCE_REPAIR_MEASURED_MODELS } from '../fence-repair/measured.ts';+import { FENCE_REPAIR_MODEL_KEY, resolveFenceRepairModel } from '../fence-repair/model.ts';import { loadPricingOverrides } from '../budget/budget-tracker.ts';import { dailyLedger, FENCE_REPAIR_LEDGER, nextUtcMidnight } from '../budget/daily-ledger.ts';import { pricingSetCommand } from '../budget/no-pricing.ts';@@ -109,8 +110,10 @@ const SCAN_MS = () => { const n = parseInt(process.env.GBRAIN_FENCE_REPAIR_SCAN_const CALL_TIMEOUT_MS = () => { const n = parseInt(process.env.GBRAIN_FENCE_REPAIR_CALL_TIMEOUT_MS ?? '', 10); return Number.isFinite(n) && n > 0 ? n : 90_000; };const ROTATION_OP = 'fence-repair-rotation';-export async function resolveFenceRepairModel(engine: Pick<BrainEngine, 'getConfig'>): Promise<string> {- return resolveModel(engine, { configKey: 'models.fence_repair', tier: 'deep', fallback: TIER_DEFAULTS.deep });+/** Held because no measured model has a key: the exact choice the user makes. */+function noMeasuredModel(rows: readonly number[]): string {+ return `No model measured accurate enough for fence repair has a provider key here (${FENCE_REPAIR_MEASURED_MODELS.join(', ')}) and ${FENCE_REPAIR_MODEL_KEY} is unset, `+ + `so row(s) ${rows.join(', ') || '?'} stay held. Fix them by hand, or ask the user which model to trust, then: gbrain config set ${FENCE_REPAIR_MODEL_KEY} <provider:model>.`;}function previewArgv(scope: RepairScope, selection: Selection): string[] {@@ -141,7 +144,7 @@ function afterBytes(target: FenceTarget, after: FencePage): { sha: string; text:}interface Settings {- llmEnabled: boolean; model: string; overrides: Awaited<ReturnType<typeof loadPricingOverrides>>; capSource: CapSource;+ llmEnabled: boolean; model: string | null; overrides: Awaited<ReturnType<typeof loadPricingOverrides>>; capSource: CapSource;perPageUsd: number; perDayUsd: number; dayRemaining: number | null; runMaxUsd: number | null;}@@ -296,6 +299,8 @@ export const fencesRepair: RepairHandler = {+ 'Fix them by hand, or ask the user before turning model repair on: gbrain config set fences.repair.llm true.');continue;}+ const model = s.model;+ if (!model) { await llmHeld('no_measured_model', noMeasuredModel(at.rows)); continue; }if (target.mode === 'managed' && target.snapshot && !target.snapshot.page.deleted_at) {const fileTags = new Set(parseMarkdown(target.content ?? '', target.path ?? 'page.md').tags);if (target.snapshot.tags.some(tag => !fileTags.has(tag))) {@@ -303,14 +308,14 @@ export const fencesRepair: RepairHandler = {continue;}}- const estimate = tier3Estimate(analysis.requests, { model: s.model, overrides: s.overrides, capSource: s.capSource });+ const estimate = tier3Estimate(analysis.requests, { model, overrides: s.overrides, capSource: s.capSource });if (!estimate.ok) {- await llmHeld('no_pricing', `A spend cap is set but gbrain has no price for ${s.model}. ${estimate.guidance.lookup} Register it with: ${estimate.guidance.register_command}`);+ await llmHeld('no_pricing', `A spend cap is set but gbrain has no price for ${model}. ${estimate.guidance.lookup} Register it with: ${estimate.guidance.register_command}`);continue;}if (estimate.estimated && !unpricedWarned) {unpricedWarned = true;- warnings.push(`gbrain has no price for the fence repair model ${s.model}; model repair runs under the default caps and is metered at an estimated ceiling (the highest chat rate gbrain knows). Make it exact with: ${pricingSetCommand(s.model, 'chat')}`);+ warnings.push(`gbrain has no price for the fence repair model ${model}; model repair runs under the default caps and is metered at an estimated ceiling (the highest chat rate gbrain knows). Make it exact with: ${pricingSetCommand(model, 'chat')}`);}if (s.perPageUsd === 0 || s.perDayUsd === 0) {await llmHeld('budget_exhausted', `Model repair spend is set to 0 (fences.repair.max_usd_per_${s.perPageUsd === 0 ? 'page' : 'day'}), so these rows stay held. Raising it is the user's call: gbrain config set fences.repair.max_usd_per_${s.perPageUsd === 0 ? 'page' : 'day'} <usd>.`);@@ -321,9 +326,9 @@ export const fencesRepair: RepairHandler = {continue;}const memo = await store.read(attemptCandidate(target, src.incarnation));- if (memo && memo.memo === tier3Memo(target, s.model) && memo.state === 'rejected') {+ if (memo && memo.memo === tier3Memo(target, model) && memo.state === 'rejected') {const reason = (memo.reason ?? 'still_invalid') as FenceReason;- await keep({ item: name, reason, tier: 'manual', resolution: `${s.model}'s repair of these exact bytes was rejected (${reason}${memo.gate ? `, gate ${memo.gate}` : ''}); it is not retried until the file, the model or the rules change. `+ await keep({ item: name, reason, tier: 'manual', resolution: `${model}'s repair of these exact bytes was rejected (${reason}${memo.gate ? `, gate ${memo.gate}` : ''}); it is not retried until the file, the model or the rules change. `+ `Fix row(s) ${(memo.rows ?? at.rows).join(', ') || '?'} by hand.`, ...(memo.gate ? { gate: memo.gate as GateLetter } : {}), ...(memo.rows ? { rows: memo.rows } : {}) });continue;}@@ -449,10 +454,12 @@ async function tier3(ctx: OperationContext, src: FenceSource, target: FenceTargeconst s = await settings(engine, { noLlm: opts.noLlm, ...(opts.allowanceUsd !== undefined ? { maxLlmUsd: opts.allowanceUsd } : {}) });const rows = fixLocation(analysis.fixes, analysis.residual).rows;if (!s.llmEnabled) return held('llm_disabled', `Model repair is off; row(s) ${rows.join(', ')} stay held.`, { rows, tier: 'llm' });+ const model = s.model;+ if (!model) return held('no_measured_model', noMeasuredModel(rows), { rows, tier: 'llm' });if (s.perPageUsd === 0 || s.perDayUsd === 0) return held('budget_exhausted', 'Model repair spend is set to 0.', { rows, tier: 'llm' });const now = () => new Date();const timeoutMs = Math.max(5_000, Math.min(CALL_TIMEOUT_MS(), opts.deadline !== undefined ? opts.deadline - Date.now() : Infinity));- const result = await runTier3(target, analysis, src.incarnation, { ledger: dailyLedger(engine, FENCE_REPAIR_LEDGER), store: attemptStore(engine), model: s.model, overrides: s.overrides,+ const result = await runTier3(target, analysis, src.incarnation, { ledger: dailyLedger(engine, FENCE_REPAIR_LEDGER), store: attemptStore(engine), model, overrides: s.overrides,capSource: s.capSource, perPageUsd: s.perPageUsd, perDayUsd: s.perDayUsd, ...(opts.allowanceUsd !== undefined ? { allowanceUsd: opts.allowanceUsd } : {}), timeoutMs, now });if (!result.ok) {if (result.reason === 'claimed_elsewhere') return { applied: false, outcome: 'skipped', reason: 'claimed_elsewhere', detail: { path: target.path, slug: target.slug, message: result.message } };@@ -472,7 +479,7 @@ 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: s.model, cost: result.spentUsd },+ 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 store = attemptStore(engine);if (written.applied) await store.publish(result.claim);diff --git a/test/doctor-fence-integrity.test.ts b/test/doctor-fence-integrity.test.tsindex c4cb370147..48b4078def 100644--- a/test/doctor-fence-integrity.test.ts+++ b/test/doctor-fence-integrity.test.ts@@ -110,7 +110,7 @@ describe('fence_integrity doctor check', () => {expect(details.sources.find((c: any) => c.source_id === s.id)).toMatchObject({ total: 4, holds: { manual: 1, total: 1 }, pages: { resolver: 1, deterministic: 1, total: 2 },files: { llm: 1, total: 1 }, by_tier: { deterministic: 1, resolver: 1, llm: 1, manual: 1, total: 4 } });expect(check.message).toContain(`${s.id}: 1 held file(s), 2 stored page(s), 1 unsynced file(s) (by tier: deterministic 1, resolver 1, llm 1, manual 1); oldest hold`);- expect(check.message).toContain('Model repair caps: $0.05 per page, $1.00 per day ($0.00 spent today).');+ expect(check.message).toContain('Model repair caps: $0.30 per page, $1.00 per day ($0.00 spent today).');// No maintenance run has completed on this brain: never "repaired automatically", the preview then the apply.expect(check.message).toContain('not repaired automatically (no maintenance run has completed in the last 24 h)');expect(check.message).toContain(`Preview: gbrain repair fences --source ${s.id}`);diff --git a/test/eval-fence-repair-tier3.test.ts b/test/eval-fence-repair-tier3.test.tsindex c80d567a36..1f900afd17 100644--- a/test/eval-fence-repair-tier3.test.ts+++ b/test/eval-fence-repair-tier3.test.ts@@ -7,11 +7,12 @@* kinds of adversarial fence; every label holds under the production gates* (the $0 oracle: each repairable ground truth passes every gate and comes* out byte-identical, each gate-limited one is rejected, each ambiguous- * probe is accepted, each unrecoverable probe is rejected); and the scorer's- * match rule and rates. Fails when: a fixture is hand-edited without- * regenerating, a Tier 1 or gate change moves a fixture out of Tier 3 or- * makes a ground truth unreachable, or the scorer stops counting a moved- * cell as a mismatch. It guards the instrument, not the score: the live run+ * probe is accepted, each unrecoverable probe is rejected, the free tiers+ * decide the fixtures the oracle lists as theirs, and a HOLD answer is held as+ * `llm_declined`); and the scorer's match rule and rates. Fails when: a fixture+ * is hand-edited without regenerating, a Tier 1 or gate change moves a+ * fixture off its listed path or makes a ground truth unreachable, or the+ * scorer stops counting a moved cell as a mismatch. It guards the instrument, not the score: the live run* (harness.ts --model ...) spends tokens and is never part of CI.* Why new: the eval is new with T4.* Seams: the gateway's chat transport stub (oracle.ts), which production never sets.@@ -75,9 +76,11 @@ describe('scorer', () => {match_cells: match, match_exact: match, calls: [{ latency_ms: 1000, input_tokens: 500, output_tokens: 100, estimate_usd: 0.02, usd: 0.01, stop: 'end_turn', text: '' }],spent_usd: 0.01, usd_unregistered: 0.01, latency_ms: 1000, attempts: 1 });const rows = [...Array.from({ length: 8 }, (_, i) => row(`r${i}`, 'repairable', 'repaired', true)), row('r8', 'repairable', 'repaired', false), row('r9', 'repairable', 'held', null), row('a0', 'adversarial', 'held', null)];+ rows[0] = { ...rows[0]!, tier1: 'proposal', calls: [] };+ rows[10] = { ...rows[10]!, reason: 'llm_declined', gate: null };const [s] = summarize(rows);- expect(s!.repairable).toMatchObject({ n: 10, repaired: 9, gate_pass: 0.9, false_accepts: 1, false_accept: 0.1 });- expect(s!.adversarial).toMatchObject({ n: 1, held: 1 });+ expect(s!.repairable).toMatchObject({ n: 10, repaired: 9, gate_pass: 0.9, false_accepts: 1, false_accept: 0.1, tier1_repaired: 1, tier3: { n: 9, repaired: 8, false_accepts: 1 } });+ expect(s!.adversarial).toMatchObject({ n: 1, held: 1, declined: 1 });expect(s!.cost.usd_per_repair).toBeCloseTo(0.1 / 9, 10);expect(meetsRule(s!)).toBe(false);expect(meetsRule({ ...s!, repairable: { ...s!.repairable, gate_pass: 0.8, false_accept: 0.01 } })).toBe(true);diff --git a/test/fence-repair-config.test.ts b/test/fence-repair-config.test.tsindex b69be6194a..e95e77acc7 100644--- a/test/fence-repair-config.test.ts+++ b/test/fence-repair-config.test.ts@@ -1,7 +1,7 @@/*** #6188 PR3 fence repair caps (src/core/fence-repair/config.ts).*- * Protects: `fences.repair.max_usd_per_page` (default 0.05) and+ * Protects: `fences.repair.max_usd_per_page` (default 0.30) and* `fences.repair.max_usd_per_day` (default 1.00) are registered keys that* `gbrain config set` accepts as non-negative USD amounts (0 = no model* spend) and refuses otherwise with nothing written; the reader keeps the@@ -44,13 +44,13 @@ describe('fence repair caps', () => {});test('the reader keeps the defaults until the user sets a cap, and reports whose cap it is', async () => {- expect(await readFenceRepairCaps(engine)).toEqual({ perPageUsd: 0.05, perDayUsd: 1, perPageSource: 'default', perDaySource: 'default' });+ expect(await readFenceRepairCaps(engine)).toEqual({ perPageUsd: 0.3, perDayUsd: 1, perPageSource: 'default', perDaySource: 'default' });await engine.setConfig(FENCE_REPAIR_MAX_USD_PER_DAY_KEY, '0');await engine.setConfig(FENCE_REPAIR_MAX_USD_PER_PAGE_KEY, '0.2');expect(await readFenceRepairCaps(engine)).toEqual({ perPageUsd: 0.2, perDayUsd: 0, perPageSource: 'user', perDaySource: 'user' });await engine.setConfig(FENCE_REPAIR_MAX_USD_PER_PAGE_KEY, 'garbage');- expect((await readFenceRepairCaps(engine)).perPageUsd).toBe(0.05);+ expect((await readFenceRepairCaps(engine)).perPageUsd).toBe(0.3);const failing = { getConfig: async () => { throw new Error('config table unavailable'); } };- expect(await readFenceRepairCaps(failing)).toEqual({ perPageUsd: 0.05, perDayUsd: 1, perPageSource: 'default', perDaySource: 'default' });+ expect(await readFenceRepairCaps(failing)).toEqual({ perPageUsd: 0.3, perDayUsd: 1, perPageSource: 'default', perDaySource: 'default' });});});diff --git a/test/fence-repair-llm.test.ts b/test/fence-repair-llm.test.tsindex 7e5c1d7699..fb3128557e 100644--- a/test/fence-repair-llm.test.ts+++ b/test/fence-repair-llm.test.ts@@ -7,18 +7,30 @@* (llm_unavailable, llm_empty, llm_refused, llm_malformed, llm_truncated) and* a truncated answer is rejected even when it parses; a wrong row count is a* gate (e) failure; the corrective re-ask carries the model's own answer plus- * the gate letter and row numbers only; the splice rebuilds only the fence;- * the prompt bytes are pinned (a change must bump FENCE_REPAIR_PROMPT_VERSION).+ * the gate letter and row numbers only, and runs only after a structural+ * failure (gate (a) or (e)), never after gate (f); a HOLD answer is+ * `llm_declined` and consumes the attempt memo; a headerless fence of typed+ * rows gets the wide header; the output ceiling leaves a reasoning model room+ * to think and the estimate reserves the ceiling the gateway sends; the splice+ * rebuilds only the fence; the prompt bytes are pinned (a change must bump+ * FENCE_REPAIR_PROMPT_VERSION).* Fails when: valid rows or page prose leak into the prompt, a tool or a* fallback chain reaches the call, a refusal or truncation is treated as an- * answer, or the re-ask quotes anything beyond its own answer.+ * answer, the re-ask quotes anything beyond its own answer or follows a gate+ * (f) rejection, a decline is retried or written, or the budget starves a+ * reasoning model.* Why new: the Tier 3 module is new in PR4.* Seams: the gateway's chat transport seam (__setChatTransportForTests).*/-import { afterAll, afterEach, describe, expect, test } from 'bun:test';+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';import { createHash } from 'node:crypto';import { __setChatTransportForTests, configureGateway, resetGateway, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';-import { buildTier3Prompt, callTier3, correctionMessage, extractSingleTable, FENCE_REPAIR_PROMPT_VERSION, spliceTier3, tier3Requests } from '../src/core/fence-repair/llm.ts';+import { dailyLedger, FENCE_REPAIR_LEDGER } from '../src/core/budget/daily-ledger.ts';+import { attemptStore } from '../src/core/fence-repair/attempts.ts';+import { buildTier3Prompt, callTier3, correctionMessage, extractSingleTable, FENCE_REPAIR_PROMPT_VERSION, spliceTier3, tier3Requests, tier3TokenBudget, TIER3_REASONING_TOKENS } from '../src/core/fence-repair/llm.ts';+import { pageSha, type FenceTarget } from '../src/core/fence-repair/repair-io.ts';+import { analyzeFences, runTier3, type FenceAnalysis } from '../src/core/fence-repair/repair-tiers.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { safeNormalizeFences } from '../src/core/fence-repair/normalize.ts';import { validateFenceRepair } from '../src/core/fence-repair/validate.ts';@@ -29,8 +41,8 @@ const SEP = '|---|-------|------|------------|------------|------------|--------const VALID = 'Validrowclaimzq9 stays private';const PROSE = 'Pageproseqz9 is never sent';const BROKEN = 'Brokenrowclaimzq9 ships';-/** One valid row and one row with an extra empty cell in the middle (extra_cells, row-level). */-const rowLevel = `${PROSE}\n\n${FB}\n${FH}\n| 1 | ${VALID} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |\n| 2 | ${BROKEN} | | fact | 0.8 | private | low | 2026-02-01 | | chat | ctx |\n${FBE}\n`;+/** One valid row and one row missing its trailing cells (short_row, row-level). */+const rowLevel = `${PROSE}\n\n${FB}\n${FH}\n| 1 | ${VALID} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |\n| 2 | ${BROKEN} | fact | 0.8 | private | low | 2026-02-01 |\n${FBE}\n`;/** A fence with rows but no header (no_header, fence-level). */const noHeader = `${PROSE}\n\n${FB}\n| 1 | ${BROKEN} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |\n${FBE}\n`;@@ -60,7 +72,7 @@ afterAll(() => resetGateway());describe('Tier 3 requests and prompt', () => {test('a row-level issue sends the header and that row only; a fence-level issue sends every row; page prose never', () => {const row = residualOf(rowLevel);- expect(row.normalized.residual.map(i => i.reason)).toEqual(['extra_cells']);+ expect(row.normalized.residual.map(i => i.reason)).toEqual(['short_row']);expect(row.requests).toHaveLength(1);const req = row.requests[0]!;expect(req.rows.map(r => r.occurrence)).toEqual([1]);@@ -69,7 +81,7 @@ describe('Tier 3 requests and prompt', () => {expect(all).toContain(BROKEN);expect(all).not.toContain(VALID);expect(all).not.toContain(PROSE);- expect(prompt.user).toContain('extra_cells: row(s) 2');+ expect(prompt.user).toContain('short_row: row(s) 2');const fence = residualOf(noHeader);expect(fence.requests[0]!.header).toBeNull();expect(fence.requests[0]!.rows).toHaveLength(1);@@ -79,7 +91,24 @@ describe('Tier 3 requests and prompt', () => {test('prompt bytes are pinned; a prompt change must bump FENCE_REPAIR_PROMPT_VERSION', () => {const prompt = buildTier3Prompt(residualOf(noHeader).requests[0]!);const digest = createHash('sha256').update(`${prompt.system}\u0000${prompt.user}`).digest('hex');- expect({ version: FENCE_REPAIR_PROMPT_VERSION, digest }).toEqual({ version: 1, digest: PROMPT_DIGEST });+ expect({ version: FENCE_REPAIR_PROMPT_VERSION, digest }).toEqual({ version: 2, digest: PROMPT_DIGEST });+ expect(prompt.system).toContain('return only the single word HOLD instead of a table');+ });++ test('a headerless fence of typed 14-cell rows is sent with the wide header', () => {+ const typed = `${FB}\n| 1 | Typedrowzq9 revenue | fact | 0.9 | private | high | 2026-05-01 | | deck | | revenue | 120k | USD | monthly |\n${FBE}\n`;+ const req = residualOf(typed).requests[0]!;+ expect(req.layout).toBe('wide');+ expect(buildTier3Prompt(req).system).toContain('| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |');+ expect(residualOf(noHeader).requests[0]!.layout).toBe('narrow');+ });++ test('the output ceiling adds room to reason only where the call cannot turn reasoning off, and reserves what the gateway sends', () => {+ const req = residualOf(rowLevel).requests[0]!;+ const table = tier3TokenBudget(req, 'anthropic:claude-opus-4-7').maxOutputTokens;+ expect(tier3TokenBudget(req, 'anthropic:claude-fable-5-1').maxOutputTokens).toBe(table + TIER3_REASONING_TOKENS);+ expect(tier3TokenBudget(req, 'openai:gpt-6.1-sol').maxOutputTokens).toBe(table + TIER3_REASONING_TOKENS);+ expect(tier3TokenBudget(req, 'claude-cli:claude-fable-5-1').maxOutputTokens).toBe(32000);});test('a fence with a stray text line inside is not eligible (rebuilding the table would drop it)', () => {@@ -100,10 +129,15 @@ describe('extracting the answer', () => {expect(extractSingleTable(' ', req)).toEqual({ ok: false, reason: 'llm_empty' });expect(extractSingleTable("I can't help rewrite that table.", req)).toEqual({ ok: false, reason: 'llm_refused' });});++ test('the single word HOLD (plain, bold or in a code fence) is a decline', () => {+ for (const text of ['HOLD', ' **HOLD** ', '```\nHOLD\n```', 'HOLD.']) expect(extractSingleTable(text, req)).toEqual({ ok: false, reason: 'llm_declined' });+ expect(extractSingleTable('HOLD: row 2 has two kinds', req)).toEqual({ ok: false, reason: 'llm_malformed' });+ });});describe('the gateway call', () => {- const realigned = `${NARROW}\n${SEP}\n| 2 | ${BROKEN} | fact | 0.8 | private | low | 2026-02-01 | | chat | ctx |`;+ const realigned = `${NARROW}\n${SEP}\n| 2 | ${BROKEN} | fact | 0.8 | private | low | 2026-02-01 | | | |`;test('no tools, no fallback, the configured model; a realigned answer splices into a page that passes every gate', async () => {configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', chat_fallback_chain: ['openai:gpt-6-luna'] } as never);@@ -116,6 +150,7 @@ describe('the gateway call', () => {expect(calls[0]!.allowFallback).toBe(false);expect(calls[0]!.model).toBe('anthropic:claude-fable-5');expect(calls[0]!.thinking).toBe('off');+ expect(calls[0]!.maxTokens).toBe(tier3TokenBudget(requests[0]!, 'anthropic:claude-fable-5').maxOutputTokens);const spliced = spliceTier3(normalized.page, requests[0]!, (answer as Extract<typeof answer, { ok: true }>).table)!;expect(spliced.compiled_truth.startsWith(`${PROSE}\n\n${FB}\n${NARROW}\n${SEP}\n| 1 | ${VALID} |`)).toBe(true);const final = safeNormalizeFences(spliced, { pageVisibility: 'private' });@@ -132,6 +167,7 @@ describe('the gateway call', () => {[result(realigned, 'content_filter'), 'llm_refused'],[result('Sure! I fixed it.'), 'llm_malformed'],[result(realigned, 'length'), 'llm_truncated'],+ [result('HOLD'), 'llm_declined'],[result(`${realigned}\n| 3 | Extra row | fact | 1 | private | high | | | | |`), 'row_count_changed'],];for (const [answer, reason] of cases) expect(await reasonOf(req, answer)).toBe(reason);@@ -145,7 +181,58 @@ describe('the gateway call', () => {expect(messages.map(m => m.role)).toEqual(['user', 'assistant', 'user']);expect(messages[1]!.content).toBe('PRIOR-ANSWER');expect(messages[2]!.content).toBe(correctionMessage('f', [2]));- expect(String(messages[2]!.content)).toBe("Your table was rejected by validation gate (f) cell_changed at row(s) 2: a cell's text changed, or a valid cell moved out of its column. Return the corrected full table following every rule above. Output only the table.");+ expect(String(messages[2]!.content)).toBe("Your table was rejected by validation gate (f) cell_changed at row(s) 2: a cell's text changed, or a valid cell moved out of its column. Return the corrected full table following every rule above, or HOLD if a row has more than one reasonable reading. Output only the table or HOLD.");+ });+});++describe('runTier3: the re-ask and the decline', () => {+ let engine: PGLiteEngine;+ let incarnation: string;+ const model = 'anthropic:claude-opus-4-7';+ const fixed = `${NARROW}\n${SEP}\n| 2 | ${BROKEN} | fact | 0.8 | private | low | 2026-02-01 | | | |`;+ const cellChanged = `${NARROW}\n${SEP}\n| 2 | ${BROKEN} | fact | 0.8 | private | low | 2026-02-02 | | | |`;+ const extraRow = `${fixed}\n| 3 | Inventedrowzq9 | fact | 1.0 | private | low | | | | |`;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const [src] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ incarnation = src!.incarnation;+ });+ afterAll(async () => { await engine.disconnect(); });++ async function attempt(slug: string, answers: ChatResult[]) {+ const page = { compiled_truth: rowLevel, timeline: '' };+ const target: FenceTarget = { mode: 'db', sourceId: 'default', key: slug, slug, path: null, sourcePath: null, page, content: null, before: pageSha(page), snapshot: null, hold: null,+ ctx: { pageVisibility: 'private' } } as FenceTarget;+ const analysis = await analyzeFences(engine, target, { pageId: null });+ expect(analysis.status).toBe('llm');+ const calls = stub(answers);+ const out = await runTier3(target, analysis as Extract<FenceAnalysis, { status: 'llm' }>, incarnation, { ledger: dailyLedger(engine, FENCE_REPAIR_LEDGER), store: attemptStore(engine),+ model, capSource: 'default', perPageUsd: 1, perDayUsd: 10, timeoutMs: 30_000, now: () => new Date() });+ return { out, calls };+ }++ test('a gate (f) rejection is final: no re-ask, so the gates cannot steer the model to an allowed but wrong placement', async () => {+ const { out, calls } = await attempt('t3/cell', [result(cellChanged), result(fixed)]);+ expect(calls).toHaveLength(1);+ expect(out).toMatchObject({ ok: false, reason: 'cell_changed', gate: 'f' });+ });++ test('a structural failure (wrong row count, gate e) still earns one re-ask', async () => {+ const { out, calls } = await attempt('t3/rows', [result(extraRow), result(fixed)]);+ expect(calls).toHaveLength(2);+ expect(out.ok).toBe(true);+ });++ test('HOLD is held as llm_declined and consumes the memo: the same bytes are never sent again', async () => {+ const first = await attempt('t3/hold', [result('HOLD')]);+ expect(first.calls).toHaveLength(1);+ expect(first.out).toMatchObject({ ok: false, reason: 'llm_declined' });+ const again = await attempt('t3/hold', [result(fixed)]);+ expect(again.calls).toHaveLength(0);+ expect(again.out).toMatchObject({ ok: false, reason: 'llm_declined', memoHit: true, spentUsd: 0 });});});@@ -155,4 +242,4 @@ async function reasonOf(req: Parameters<typeof callTier3>[0], answer: ChatResultreturn out.ok ? 'ok' : out.reason;}-const PROMPT_DIGEST = '9f3cf734abd6aac8b28ee094b226c4c654ab0e85e07a0c6aed6235eb97221114';+const PROMPT_DIGEST = '71cf09e5a19efc76b1c8b2b02d20074fcc3cfed172f43ba654de124d202dba3e';diff --git a/test/fence-repair-normalize.test.ts b/test/fence-repair-normalize.test.tsindex 64c33f3c8e..3ca11ebb1f 100644--- a/test/fence-repair-normalize.test.ts+++ b/test/fence-repair-normalize.test.ts@@ -432,3 +432,55 @@ describe('containment and the allocator', () => {expect(Number.isInteger(FENCE_RULES_VERSION) && FENCE_RULES_VERSION > 0).toBe(true);});});++describe('stray empty cells and split claims (#6188 T4)', () => {+ const wide = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |';+ const wideSep = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|';++ test('one empty cell inserted after the claim is removed; every other byte of the row stays', () => {+ const r = run(facts(factsRow(1, 'Omicron four'), '| 2 | Rho four opened a lab | | event | 0.7 | private | low | 2026-05-01 | | site visit | |'));+ expect(classes(r)).toEqual(['stray_empty_cell']);+ expect(r.page.compiled_truth).toContain('| 2 | Rho four opened a lab | event | 0.7 | private | low | 2026-05-01 | | site visit | |');+ expectRepaired(r);+ expect(parseFactsFence(r.page.compiled_truth).facts[1]).toMatchObject({ kind: 'event', source: 'site visit' });+ });++ test('two empty cells, a typed wide row and a takes row with an empty cell after the holder line up the same way', () => {+ const two = run(facts('| 3 | Sigma four cut prices 15% | | event | | 0.8 | private | medium | 2026-06-01 | | price list | |'));+ expect(two.page.compiled_truth).toContain('| 3 | Sigma four cut prices 15% | event | 0.8 | private | medium | 2026-06-01 | | price list | |');+ expectRepaired(two);+ const typed = run(['## Facts', '', FB, wide, wideSep, '| 4 | Tau four margin | | fact | 0.9 | private | high | 2026-06-30 | | report | | margin | 0.4 | ratio | quarterly |', FE, ''].join('\n'));+ expect(typed.page.compiled_truth).toContain('| 4 | Tau four margin | fact | 0.9 | private | high | 2026-06-30 | | report | | margin | 0.4 | ratio | quarterly |');+ expectRepaired(typed);+ const take = run(takes(takesRow(1, 'Upsilon four'), '| 2 | Phi four ships late | bet | people/sample-person | | 0.3 | 2026-02-02 | standup |'));+ expect(take.page.compiled_truth).toContain('| 2 | Phi four ships late | bet | people/sample-person | 0.3 | 2026-02-02 | standup |');+ expectRepaired(take);+ });++ test('extra cells no empty-cell deletion can line up are manual extra_cells and the row is untouched', () => {+ const duplicate = '| 5 | Chi four expands | fact | 0.6 | 0.9 | private | medium | 2026-01-01 | | memo | |';+ const text = '| 6 | Psi four moved | (relocated) | event | 0.8 | private | medium | 2026-01-10 | | email | |';+ for (const row of [duplicate, text]) {+ const r = run(facts(row));+ expect(reasons(r)).toEqual(['extra_cells']);+ expect(r.fixes).toEqual([]);+ expect(r.page.compiled_truth).toContain(row);+ }+ expect(FENCE_REASONS.extra_cells).toMatchObject({ tier: 'manual', manualOnly: true });+ });++ test('kind_map reads only a kind word: a claim tail in the kind column is manual claim_split, never a kind note', () => {+ const tails = ['after a long search, per the board', 'and then the whole team left the office', 'see [the memo](https://example.com/m)', '~~struck~~ words'];+ for (const tail of tails) {+ const row = `| 7 | Omega four hired a CFO | ${tail} | 0.8 | private | high | 2026-03-01 | | memo | |`;+ const r = run(facts(row));+ expect(reasons(r)).toEqual(['claim_split']);+ expect(r.fixes).toEqual([]);+ expect(r.page.compiled_truth).toContain(row);+ }+ expect(FENCE_REASONS.claim_split).toMatchObject({ tier: 'manual', manualOnly: true });+ const phrase = run(facts(factsRow(8, 'Alpha five', { kind: 'strategic partnership update' })));+ expect(classes(phrase)).toEqual(['kind_map']);+ expectRepaired(phrase);+ });+});diff --git a/test/fence-repair-reasons.test.ts b/test/fence-repair-reasons.test.tsindex 785523acb9..c9c44f94ca 100644--- a/test/fence-repair-reasons.test.ts+++ b/test/fence-repair-reasons.test.ts@@ -15,12 +15,17 @@ const SPEC_MANUAL: FenceReason[] = [];/** Manual-only residuals this module adds where the spec says "residual" without naming one. */const ADDED_MANUAL: FenceReason[] = ['unclosed_trailing_content', 'marker_near_miss', 'holder_missing'];-const SPEC_TIER3: FenceReason[] = ['header_unmapped', 'no_header', 'row_before_header', 'short_row', 'extra_cells'];+/**+ * Manual since the Tier 3 eval (#6188 T4): a row whose extra cells empty-cell removal cannot line up, and a facts kind+ * cell that holds text rather than a kind word; no gate can tell a claim cut by an unescaped `|` from a misplaced cell.+ */+const EVAL_MANUAL: FenceReason[] = ['extra_cells', 'claim_split'];+const SPEC_TIER3: FenceReason[] = ['header_unmapped', 'no_header', 'row_before_header', 'short_row'];const SPEC_OTHERS: FenceReason[] = ['holder_unresolved','unparseable', 'row_collision', 'quoted_fence_rows', 'stored_row_collision', 'withdrawn_claim_in_malformed_fence','target_fence_malformed', 'prepare_time', 'normalizer_failed',- 'llm_unavailable', 'llm_empty', 'llm_refused', 'llm_malformed', 'llm_truncated', 'llm_disabled', 'budget_exhausted',+ 'llm_unavailable', 'llm_empty', 'llm_refused', 'llm_malformed', 'llm_truncated', 'llm_declined', 'llm_disabled', 'no_measured_model', 'budget_exhausted','no_pricing', 'ledger_unavailable', 'owner_unavailable', 'owner_cli_required', 'sync_in_progress', 'time_budget','changed_since_read', 'changed_since_preview','still_invalid', 'claim_changed', 'row_number_changed', 'visibility_loosened', 'row_count_changed', 'cell_changed', 'protection_loosened',@@ -28,11 +33,11 @@ const SPEC_OTHERS: FenceReason[] = [describe('FENCE_REASONS', () => {test('holds exactly the reasons the spec names (plus the documented additions)', () => {- expect([...FENCE_REASON_CODES].sort()).toEqual([...SPEC_MANUAL, ...ADDED_MANUAL, ...SPEC_TIER3, ...SPEC_OTHERS].sort());+ expect([...FENCE_REASON_CODES].sort()).toEqual([...SPEC_MANUAL, ...ADDED_MANUAL, ...EVAL_MANUAL, ...SPEC_TIER3, ...SPEC_OTHERS].sort());});test('screen residual classes carry the spec\'s tier and manual-only flag', () => {- for (const reason of [...SPEC_MANUAL, ...ADDED_MANUAL]) {+ for (const reason of [...SPEC_MANUAL, ...ADDED_MANUAL, ...EVAL_MANUAL]) {expect([reason, FENCE_REASONS[reason].tier, FENCE_REASONS[reason].manualOnly, FENCE_REASONS[reason].autoRetry]).toEqual([reason, 'manual', true, false]);}for (const reason of SPEC_TIER3) expect([reason, FENCE_REASONS[reason].tier, FENCE_REASONS[reason].manualOnly]).toEqual([reason, 'llm', false]);@@ -62,7 +67,7 @@ describe('FENCE_REASONS', () => {});test('paid reasons are exactly the ones whose fix raises spend or enables the model', () => {- expect(FENCE_REASON_CODES.filter(r => FENCE_REASONS[r].paid).sort()).toEqual(['budget_exhausted', 'llm_disabled', 'no_pricing']);+ expect(FENCE_REASON_CODES.filter(r => FENCE_REASONS[r].paid).sort()).toEqual(['budget_exhausted', 'llm_disabled', 'no_measured_model', 'no_pricing']);});});diff --git a/test/fence-walkthrough.test.ts b/test/fence-walkthrough.test.tsindex a40f7f6df4..331e66f646 100644--- a/test/fence-walkthrough.test.ts+++ b/test/fence-walkthrough.test.ts@@ -8,7 +8,9 @@* guide shows appears in the real output (hashes, ids, times, costs and the* checkout path normalized) and that every command exits 0. The model is a* local stand-in for the provider's Responses API (OPENAI_BASE_URL), so the- * spawned CLI makes its genuine provider call and no network or key is used.+ * spawned CLI makes its genuine provider call and no network or key is used;+ * `models.fence_repair` is unset, so the repair uses the measured default for+ * an OpenAI key (openai:gpt-6.1-sol).** Protects: the documented journey (post-upgrade notice, converting sync,* sources status, preview, apply, commit subjects, doctor ok) and its command@@ -41,7 +43,7 @@ const provider = Bun.serve({const url = new URL(req.url);if (!url.pathname.endsWith('/responses')) return new Response(JSON.stringify({ data: [{ id: 'gpt-5.5' }] }), { headers: { 'Content-Type': 'application/json' } });requests++;- return new Response(JSON.stringify({ id: 'resp_walkthrough', object: 'response', created_at: 1, model: 'gpt-5.5', status: 'completed', error: null, incomplete_details: null,+ return new Response(JSON.stringify({ id: 'resp_walkthrough', object: 'response', created_at: 1, model: 'gpt-6.1-sol', status: 'completed', error: null, incomplete_details: null,output: [{ type: 'message', id: 'msg_walkthrough', status: 'completed', role: 'assistant', content: [{ type: 'output_text', text: `${NARROW}\n${SEP}\n${ACME_ROW}`, annotations: [] }] }],usage: { ...usage, total_tokens: usage.input_tokens + usage.output_tokens } }), { headers: { 'Content-Type': 'application/json' } });},@@ -128,7 +130,6 @@ test('docs/guides/repair.md "Fences": every command runs and prints every line tawait commit('init');await ok(['gbrain', 'init', '--pglite', '--no-embedding']);await ok(['gbrain', 'config', 'set', 'self_upgrade.mode', 'off']);- await ok(['gbrain', 'config', 'set', 'models.fence_repair', 'openai:gpt-5.5']);await ok(['gbrain', 'sources', 'add', 'notes', '--path', checkout]);await ok(['gbrain', 'sync', '--source', 'notes', '--no-pull']);diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 2d76105a98..770b0c450b 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1648,7 +1648,7 @@"docs": "docs/guides/write-refusals.md#invalid_fence","model_repair": {"max_usd_per_day": 1,- "max_usd_per_page": 0.05,+ "max_usd_per_page": 0.3,"reserved_today_usd": 0,"spent_today_usd": 0},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 4fb420b5d2..dc79792a07 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1725,7 +1725,7 @@"docs": "docs/guides/write-refusals.md#invalid_fence","model_repair": {"max_usd_per_day": 1,- "max_usd_per_page": 0.05,+ "max_usd_per_page": 0.3,"reserved_today_usd": 0,"spent_today_usd": 0},diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex f2e601e27f..1de7397528 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1715,7 +1715,7 @@"docs": "docs/guides/write-refusals.md#invalid_fence","model_repair": {"max_usd_per_day": 1,- "max_usd_per_page": 0.05,+ "max_usd_per_page": 0.3,"reserved_today_usd": 0,"spent_today_usd": 0},diff --git a/test/model-pricing.test.ts b/test/model-pricing.test.tsindex 7c161544ee..df131fb2ab 100644--- a/test/model-pricing.test.ts+++ b/test/model-pricing.test.ts@@ -55,6 +55,10 @@ describe('CANONICAL_PRICING — table integrity', () => {expect(CANONICAL_PRICING['anthropic:claude-sonnet-5-5']).toMatchObject({ input: 2.0, output: 10.0, cache_read: 0.2 });});+ test('gpt-6.1-sol present at its $2/$10 list rate (the fence repair default meters exactly, #6188)', () => {+ expect(CANONICAL_PRICING['openai:gpt-6.1-sol']).toMatchObject({ input: 2.0, output: 10.0 });+ });+test('Fable 5 present at $10/$50', () => {expect(CANONICAL_PRICING['anthropic:claude-fable-5']).toMatchObject({ input: 10.0, output: 50.0 });});diff --git a/test/openai-latest.serial.test.ts b/test/openai-latest.serial.test.tsindex 698ec07d41..9fa2a9b48c 100644--- a/test/openai-latest.serial.test.ts+++ b/test/openai-latest.serial.test.ts@@ -153,6 +153,11 @@ describe('rankOpenAIChatModels — newest PRICED family, tier ladder', () => {const { tiers } = rankOpenAIChatModels(['gpt-9.9', 'gpt-5.6']);expect(tiers?.deep).toBe('openai:gpt-5.6');});++ test('gpt-6.1-sol is priced for metering only: it never becomes a discovered tier default', () => {+ const { tiers } = rankOpenAIChatModels(['gpt-6.1-sol', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna']);+ expect(tiers).toMatchObject({ utility: 'openai:gpt-5.6-luna', reasoning: 'openai:gpt-5.6-terra', deep: 'openai:gpt-5.6-sol' });+ });});describe('refresh + cache + resolution overlay', () => {diff --git a/test/repair-fences.test.ts b/test/repair-fences.test.tsindex 6a9f792f54..9598c4b130 100644--- a/test/repair-fences.test.ts+++ b/test/repair-fences.test.ts@@ -54,7 +54,7 @@ import { fencesRepair, type FencesPreviewDetails } from '../src/core/repair/fencimport { readUncommittedFenceRepairs } from '../src/core/fence-repair/uncommitted.ts';import { parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';import { runModels } from '../src/commands/models.ts';-import { resolveFenceRepairModel } from '../src/core/repair/fences.ts';+import { resolveFenceRepairModel } from '../src/core/fence-repair/model.ts';import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';@@ -224,7 +224,7 @@ test('preview lists every tier with its cost and calls no model; the printed appconst receipts = await engine.executeRaw<{ outcome: Record<string, any> }>("SELECT outcome FROM persistence_requests WHERE source_id=$1 AND outcome ? 'fence_repair' ORDER BY sequence", [s.id]);expect(receipts.map(r => r.outcome.fence_repair.tier).sort()).toEqual(['deterministic', 'llm', 'resolver']);const llmReceipt = receipts.find(r => r.outcome.fence_repair.tier === 'llm')!.outcome.fence_repair;- expect(llmReceipt).toMatchObject({ actor: 'fence-repair', classes: ['no_header'], model: 'anthropic:claude-opus-4-7' });+ expect(llmReceipt).toMatchObject({ actor: 'fence-repair', classes: ['no_header'], model: 'anthropic:claude-fable-5-1' });expect(llmReceipt.cost_usd).toBeGreaterThan(0);expectNoSecrets([holds, receipts.map(r => r.outcome.fence_repair), surfaceOf(applied), git(s.root, 'log', '--format=%B')]);}), 240_000);@@ -235,8 +235,8 @@ test('every model proposal rejected: the hold keeps its gate, nothing is reportetransport(() => answer('A different claim'));const first = await s.run({ apply: true });expect(first).toMatchObject({ applied: 0, repaired: 0, remaining: { claim_changed: 1 }, outcomes: { held: 1 } });- expect(calls).toHaveLength(2);- expect(String(calls[1]!.messages[2]!.content)).toContain('gate (b) claim_changed');+ // Gate (b) is not structural, so there is no corrective re-ask.+ expect(calls).toHaveLength(1);expect((await s.holds())[0]!.meta.fence_repair).toMatchObject({ reason: 'claim_changed', gate: 'b' });expect(first.cost.llm_usd).toBeGreaterThan(0);const human = await cli(engine, ['fences', '--source', s.id, '--apply']);@@ -244,7 +244,7 @@ test('every model proposal rejected: the hold keeps its gate, nothing is reporteexpect(human).not.toContain('repaired 1');// The memo: the same bytes, model, rules and prompt are never sent again.const again = await s.run({ apply: true });- expect(calls).toHaveLength(2);+ expect(calls).toHaveLength(1);expect(again).toMatchObject({ applied: 0, repaired: 0, remaining: { claim_changed: 1 } });expect(again.cost.llm_usd).toBe(0);const preview = await s.run();@@ -474,7 +474,7 @@ test('doctor --remediate: the plan counts the fences model estimate as paid, andexpect(s.read('people/model.md')).toBe(md('Model', noHeader()));}), 240_000);-test('models.fence_repair: gbrain models lists it on the deep tier, and setting it changes the model the repair calls', async () => withEnv(env, async () => {+test('models.fence_repair: unset, the first measured model with a key (else none); set, it always runs; gbrain models reports which', async () => withEnv(env, async () => {const engine = legacyEngine;const report = async () => {const chunks: string[] = [];@@ -483,16 +483,32 @@ test('models.fence_repair: gbrain models lists it on the deep tier, and settingtry { await runModels(engine, ['--json']); } finally { process.stdout.write = write; }return JSON.parse(chunks.join('')) as { per_task: Array<{ key: string; tier: string; resolved: string; source: string }> };};+ expect(await resolveFenceRepairModel(engine, { ANTHROPIC_API_KEY: 'k' })).toBe('anthropic:claude-fable-5-1');+ expect(await resolveFenceRepairModel(engine, { ANTHROPIC_API_KEY: 'k', OPENAI_API_KEY: 'k' })).toBe('openai:gpt-6.1-sol');+ expect(await resolveFenceRepairModel(engine, { GEMINI_API_KEY: 'k' })).toBeNull();const before = (await report()).per_task.find(row => row.key === 'models.fence_repair')!;- expect(before.tier).toBe('deep');- expect(before.resolved).toBe(await resolveFenceRepairModel(engine));+ expect(before).toMatchObject({ tier: 'deep', resolved: 'anthropic:claude-fable-5-1', source: 'measured default' });await engine.setConfig('models.fence_repair', 'anthropic:claude-sonnet-5-5');const after = (await report()).per_task.find(row => row.key === 'models.fence_repair')!;- expect(after.resolved).toBe('anthropic:claude-sonnet-5-5');- expect(await resolveFenceRepairModel(engine)).toBe('anthropic:claude-sonnet-5-5');+ expect(after).toMatchObject({ resolved: 'anthropic:claude-sonnet-5-5', source: 'config: models.fence_repair' });+ expect(await resolveFenceRepairModel(engine, {})).toBe('anthropic:claude-sonnet-5-5');await engine.executeRaw("DELETE FROM config WHERE key='models.fence_repair'");}), 60_000);+test('no measured model has a key and models.fence_repair is unset: model candidates are held no_measured_model and nothing calls a model', () => each(async engine => {+ const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) });+ await s.sync();+ transport(() => answer(CLAIM));+ await withEnv({ ANTHROPIC_API_KEY: undefined }, async () => {+ const preview = await s.run();+ expect(details(preview).held[0]).toMatchObject({ reason: 'no_measured_model', tier: 'llm' });+ expect(details(preview).held[0]!.resolution).toContain('gbrain config set models.fence_repair <provider:model>');+ expect(await s.run({ apply: true })).toMatchObject({ repaired: 0, remaining: { no_measured_model: 1 } });+ expect((await s.holds())[0]!.meta.fence_repair).toMatchObject({ reason: 'no_measured_model', tier: 'llm' });+ });+ expect(calls).toHaveLength(0);+}), 240_000);+test('a run past its deadline stops with time_budget before any item and calls no model', () => each(async engine => {const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) });await s.sync();@@ -512,8 +528,9 @@ test('two concurrent appliers at the daily cap: one model call, the other stopsconst day = new Date().toISOString().slice(0, 10);const [before] = await engine.executeRaw<{ spent: string | null }>("SELECT (reserved_usd + committed_usd)::text AS spent FROM budget_ledger WHERE scope='llm_repair' AND resolver_id='fences' AND local_date=$1::date", [day]);const spent = Number(before?.spent ?? 0);- // Room for exactly one call today (each estimate is about $0.017 and settles at about $0.005).- await engine.setConfig('fences.repair.max_usd_per_day', (spent + 0.02).toFixed(4));+ // Room for exactly one call today: one worst-case estimate, while a call settles at its real (much smaller) cost.+ const estimate = details(await a.run()).llm_items[0]!.estimate_usd;+ await engine.setConfig('fences.repair.max_usd_per_day', (spent + estimate + 0.001).toFixed(4));const results = await Promise.all([a.run({ apply: true }), b.run({ apply: true })]);expect(calls).toHaveLength(1);expect(results.map(r => r.repaired).sort()).toEqual([0, 1]);@@ -531,7 +548,8 @@ test('the maintenance phase repairs held fences with the real kind, and the dailtransport(() => answer(CLAIM));const day = new Date().toISOString().slice(0, 10);const [before] = await engine.executeRaw<{ spent: string | null }>("SELECT (reserved_usd + committed_usd)::text AS spent FROM budget_ledger WHERE scope='llm_repair' AND resolver_id='fences' AND local_date=$1::date", [day]);- await engine.setConfig('fences.repair.max_usd_per_day', (Number(before?.spent ?? 0) + 0.02).toFixed(4));+ const estimate = details(await a.run()).llm_items[0]!.estimate_usd;+ await engine.setConfig('fences.repair.max_usd_per_day', (Number(before?.spent ?? 0) + estimate + 0.001).toFixed(4));const tick = () => runFenceRepairPhase(engine, { dryRun: false, deadlineAtMs: Date.now() + 600_000 });const first = await tick();expect(first.details).toMatchObject({ mode: 'apply', stopped_reason: 'budget_exhausted' });