Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(fences): fence format reference, repair guidance, migration note and the automatic-repair behavior row (#6188)
garrytanba9321bf1587
diff --git a/AGENTS.md b/AGENTS.mdindex 2cf50325f0..408c1e6c3c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -128,10 +128,14 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contfiles through `put_page`/`capture` or a YAML serializer and check generatedcontent with `gbrain frontmatter validate --stdin --path <p>`. Walkthrough:[held files](docs/guides/repair.md#held-files). A hold with code- `invalid_fence` is a facts or takes table, not frontmatter: read the page- (`gbrain get --source <id> -- <slug>`), edit only the fence the hold names,- commit, then `gbrain sync --source <id> --no-pull`- ([fence holds](docs/guides/write-refusals.md#invalid_fence)).+ `invalid_fence` is a facts or takes table, not frontmatter, and clears+ automatically on the next maintenance run. `gbrain repair fences --source <id>`+ previews the repair and its printed apply command runs it now, with no+ extra consent; a `manual` reason needs the edit the hold names (read the+ page with `gbrain get --source <id> -- <slug>`, edit only that fence,+ commit, `gbrain sync --source <id> --no-pull`). Raising spend+ (`fences.repair.max_usd_per_day`, `fences.repair.llm true`) is the user's+ call ([fence holds](docs/guides/write-refusals.md#invalid_fence)).- **Migrate / upgrade:** `gbrain upgrade` (binary self-update + schema migrations + post-upgrade prompts),[`docs/UPGRADING_DOWNSTREAM_AGENTS.md`](./docs/UPGRADING_DOWNSTREAM_AGENTS.md),[`skills/migrations/`](./skills/migrations/), `gbrain apply-migrations --yes --no-autopilot-install` (manual migration orchestration without service installation).diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 3287118a73..a78597d77f 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -25,7 +25,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`.- `Operation.cliOnly` + `cliOnlyRefusal` (`src/core/ops/callable.ts`) — F5: owner-only ops (they refuse every MCP caller) are never listed on MCP; a call gets `trusted_local_only` (error `permission_denied`) with the exact CLI command.-- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). `BEHAVIOR_CHANGES` is the one table of disclosed changes, each with the release that introduced it; `BEHAVIOR_NOTICE_SINCE` is the newest row's release (never `VERSION`), so the notice id `behavior_changes@<since>` moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to `HTTP_SHOWN_CAP` client ids, each with the release it was shown, in the `notices.behavior_changes.http` config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads every row newer than the baseline without writing. Pinned by `test/behavior-change-notice.test.ts` (both engines, plus upgrade steps in processes pinned to a `VERSION`) and `test/behavior-change-notice-cli.test.ts`.+- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). `BEHAVIOR_CHANGES` is the one table of disclosed changes, each with the release that introduced it (`FENCE_REPAIR_MEASURED` is the automatic fence repair row's measurement sentence, replaced by the Tier 3 eval's measured rates); `BEHAVIOR_NOTICE_SINCE` is the newest row's release (never `VERSION`), so the notice id `behavior_changes@<since>` moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to `HTTP_SHOWN_CAP` client ids, each with the release it was shown, in the `notices.behavior_changes.http` config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads every row newer than the baseline without writing. Pinned by `test/behavior-change-notice.test.ts` (both engines, plus upgrade steps in processes pinned to a `VERSION`) and `test/behavior-change-notice-cli.test.ts`.- `src/core/post-upgrade-notice.ts` — F7 `post_upgrade` safety notice (contract_version + behavior-table URL): `gbrain post-upgrade` writes it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME). `src/cli/op-notices.ts` renders op notices on the local CLI (`--json` objects gain `notices`; human output on stderr).- `src/core/ops/op-fix.ts` — Lane B builders for filled, surface-correct op errors (type-only agent-output import: ops sit in the snapshot-schema closure). `opTransport(ctx)` (cli/stdio/http from `remote`+`transport`), `paramUse(ctx, param, value?)` (`--no-pull` vs `no_pull: true`), `readFix` (diagnostic step, `mcp` + `argv`), `hostFix`/`hostOnlyError` (B6: host-only command, actor agent on CLI / user on stdio / host_admin on http with relay `user_message`), `invalidParam` (B2/B3: param, choices or type+description, one example; never echoes the raw value), `scopeDeniedError` (B5: `insufficient_scope`, frozen `error` via `legacy_error`, client id + current scopes in `why`, the exact `gbrain auth rescope`/`rescope-token` command, consent `credentials`). Test: `test/op-fix.test.ts`, `test/scope-denial-contract.test.ts`.- `src/core/persistence/page-identity.ts` — B4: `pageIdentityError(present, msg)` (a deleted page throws canonical `page_not_found` with the frozen wire/journal `error` `page_identity_changed`; a replaced page keeps `page_identity_changed`), `isMissingPageMessage` (replays recover the distinction from the stored message; no schema change), `yamlLocator` (content-free ` at line L, column C`). Replays (`writeResponse` in `persistence/service.ts`) set `OperationError.receiptFields` (never serialized); `toAgentError` fills the registry fix template (`{slug}`/`{source_id}`/`{request_id}`/`{operation}`, strict per-field patterns, unfillable → dropped) and applies the principal-aware receipt rule (CLI principal → `gbrain write-request`; same-principal MCP → `get_write_request` when callable; otherwise host inspection, actor host_admin). Test: `test/write-receipt-remediation.test.ts`.diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 19349e8ec5..b35d7c023b 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -5,7 +5,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELManaged connector ingestion, connector item holds, sync checkpoint validation and the no-op kernel. Also the persistence verb types and errors, database-write and manual links, write attribution, purge-deleted and loop-fact retirement.- `src/core/fence-repair/refusal.ts` — #6188 the one fence check coordinated writers share. `scanCanonicalFences` decides from the strict parsers what the canonical projection refuses (a repeated marker outside code, any parser warning, a row number used twice on the page) and locates each defect from the raw-row view (`raw-rows.ts`, `schema.ts`), never from parser warning strings, which embed row text; reasons and messages come from `reasons.ts` (`FENCE_REASONS`, `fenceMessage`, `issueLocation`). `fenceOperationError` is the typed refusal (`invalid_fence`, wire `invalid_params`, or `take_row_collision` for a stored-row collision). `fenceFailureDetail` is the bounded, versioned `error_detail.fence` a failed receipt keeps through compaction; `fenceReceiptLocation` reads a receipt back from that detail, the message grammar or an older release's exact message, and never from an arbitrary `invalid_params`. `completeFenceLocation` names the section of a legacy receipt from the refused bytes. Tests: `test/fence-refusal.test.ts`, `test/fence-hold-surfaces.test.ts`, `test/persistence-sync-fence-holds.test.ts` (PGLite and Postgres).-- `src/core/fence-repair/{types,schema,raw-rows,reasons}.ts` — #6188 the shared fence vocabulary, all location-only. `types.ts`: `FenceIssue`, `FenceFix`, `FenceCtx`, `FenceReason`, `FixClass`. `schema.ts`: canonical columns, accepted widths (facts 9/10/14, takes 6/7/13), header aliases, enum and kind synonym tables, cell validity. `raw-rows.ts`: `extractRawRows` reads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row is `accepted` exactly when the strict parser returns it. `reasons.ts`: `FENCE_REASONS` (tier, auto-retry, actor, fix template, docs anchor per reason; the registry's `invalid_fence.reasons`) and `fenceMessage`. Tests: `test/fence-repair-raw-rows.test.ts`, `test/fence-repair-reasons.test.ts`.+- `src/core/fence-repair/{types,schema,raw-rows,reasons}.ts` — #6188 the shared fence vocabulary, all location-only. `types.ts`: `FenceIssue`, `FenceFix`, `FenceCtx`, `FenceReason`, `FixClass`. `schema.ts`: canonical columns, accepted widths (facts 9/10/14, takes 6/7/13), header aliases, enum and kind synonym tables (exported for the format reference), cell validity. `raw-rows.ts`: `extractRawRows` reads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row is `accepted` exactly when the strict parser returns it. `reasons.ts`: `FENCE_REASONS` (tier, auto-retry, actor, fix template, docs anchor per reason; the registry's `invalid_fence.reasons`) and `fenceMessage`. Tests: `test/fence-repair-raw-rows.test.ts`, `test/fence-repair-reasons.test.ts`.+- `scripts/build-fence-format.ts` — #6188 renders the generated region of `docs/guides/fence-format.md` (between `BEGIN/END GENERATED fence-format`) from the fence constants: markers, the column tables and layouts from `schema.ts` (`COLUMNS`, `BASE_WIDTH`, `MIN_CELLS`, `CANONICAL_HEADER`, `ALLOWED`, `COLUMN_DEFAULTS`, `NAMED_COLUMNS`, `TOLERATED_TRAILING`, `HEADER_ALIASES`), holder outcomes computed with `isValidHolder`/`holderAlias`, the Tier 1 rule table from the synonym tables (bound to `FixClass` by `satisfies`), screen reasons grouped by tier and the gate table from `reasons.ts`. It parses both synthetic examples with the strict parsers and throws on any warning. `--check` exits 1 when the committed region is stale. Drift test: `test/fence-format-reference.test.ts` (the region, the examples, the reference's links, and one `fence-<reason>` row per reason in `write-refusals.md` with the reason table's tier and auto-retry and a link into the reference).- `src/core/fence-repair/{normalize,structure,content,rules}.ts` — #6188 Tier 1. `normalizeFences(page, ctx)` returns a page that compiles plus location-only fixes and residual issues; a page whose fences compile comes back as the same object, and only edited cells, markers and headers change (no table is re-rendered). `structure.ts` closes a fence only when nothing but blank lines follows its last row and fixes two-dash takes markers; `content.ts` rewrites headers into canonical order with header-level defaults and renumbers prior-aware across both sections (`nextFreeRowNum`: above every fence and stored number; hidden rows never move); `rules.ts` holds the cell rules (kind map with the original word kept in `context`, enum and holder synonyms, percent confidence). `safeNormalizeFences` turns a throw into residual `normalizer_failed`. Tests: `test/fence-repair-normalize.test.ts`, `test/fence-repair-fixtures.test.ts`.- `src/core/fence-repair/{validate,validate-cells,page-checks}.ts` — #6188 the one gate every tier's output passes before a write: (a) compiles, (e) row count and containment, (b) claims, (c) existing row numbers, (d) visibility only tightens, (f) per-row cell preservation with rule-produced changes only, (g) nothing the privacy boundary hid is shown; gates (b), (c), (e) and (f) read the raw-row view. `isFenceFixedPoint` is E14. `page-checks.ts` holds `strictFailures` (gate a, the projection's three checks) and `exposedLines` (gate g). Tests: `test/fence-repair-validate.test.ts`.- `src/core/fence-repair/{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`.diff --git a/docs/guides/fence-format.md b/docs/guides/fence-format.mdnew file mode 100644index 0000000000..7f55c1282f--- /dev/null+++ b/docs/guides/fence-format.md@@ -0,0 +1,237 @@+# Facts and takes fence format++A page keeps its structured rows in two kinds of fenced Markdown tables: a+**facts** fence (what is true about the page's subject) and a **takes** fence+(who believes what, and how strongly). This page is the exact format gbrain+accepts, what it fixes in a malformed fence by itself, and what it never+guesses. Everything between the generated markers below is rendered from the+parser and repair code, so it matches the running gbrain.++**Say to your agent:** *"Why was my facts table held? Show me what the fence+should look like."*++**Say to your agent:** *"Add this as a take held by alice-example, not by hand+in the table."*++Prefer the structured writers to hand-written tables: `remember` adds a fact+row and `takes_add` adds a take row, each with a valid row number, kind and+holder, so the fence never needs repair. Write a table by hand only when the+user asks for it, and follow the format below.++When a fence does not follow this format, gbrain fixes what has one exact+meaning in the same write and holds or refuses the rest with an+`invalid_fence` reason ([what each reason means](write-refusals.md#invalid_fence)).+On the brain host, `gbrain repair fences` previews and applies the remaining+repairs, and the maintenance run applies them automatically+([fence repair](repair.md#fences)).++<!-- BEGIN GENERATED fence-format (bun run scripts/build-fence-format.ts; drift test: test/fence-format-reference.test.ts) -->+<a id="markers"></a>+## Markers++A facts fence sits between `<!--- gbrain:facts:begin -->` and `<!--- gbrain:facts:end -->`; a takes fence between `<!--- gbrain:takes:begin -->` and `<!--- gbrain:takes:end -->` (three dashes after `<!`). The body and the timeline section of a page each hold at most one fence of each kind. A marker inside a code block or an inline code span is an example, not a fence. Inside the fence the first table line is the header, which names `claim` and `kind`, then a separator line, then one line per row. A `|` inside a cell is written `\|`.++<a id="facts-columns"></a>+## Facts columns++Facts cells are read by position.++| Position | Column | Values | May be left off the row end | Default when the header lacks it | Meaning |+| --- | --- | --- | --- | --- | --- |+| 1 | `#` | a positive whole number | no | - | Row number. |+| 2 | `claim` | free text | no | - | The statement, free text. `~~claim~~` marks a row that is no longer active. |+| 3 | `kind` | `event`, `preference`, `commitment`, `belief`, `fact`, `idea` | no | - | What the claim is. |+| 4 | `confidence` | a number from 0 to 1 | no | `1.0` | How sure the brain is. |+| 5 | `visibility` | `private`, `world` | no | `private` | Who may read the row. |+| 6 | `notability` | `high`, `medium`, `low` | no | `medium` | How much it matters. |+| 7 | `valid_from` | free text | no | - | When it became true (`YYYY-MM-DD`), or empty. |+| 8 | `valid_until` | free text | no | - | When it stopped being true, or empty. |+| 9 | `source` | free text | no | - | Where it came from, free text. |+| 10 | `context` | free text | yes | - | Free text. `superseded by #N` names the row that replaced a struck row; `forgotten: ...` marks a row withdrawn with `forget`. |+| 11 | `claim_metric` | free text | yes | - | Metric of a typed claim (`mrr`, `team_size`, ...), or empty. |+| 12 | `claim_value` | a number, optionally with 1,234 separators or a k/M/B suffix | yes | - | Value of a typed claim. |+| 13 | `claim_unit` | free text | yes | - | Unit (`USD`, `people`, ...), or empty. |+| 14 | `claim_period` | free text | yes | - | Period (`monthly`, `annual`, ...), or empty. |++<a id="facts-layouts"></a>+- **Narrow, 10 cells** (what gbrain writes unless a row needs a wide column):++ ```text+ | # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+ |---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+ ```++- **Wide, 14 cells** (adds `claim_metric`, `claim_value`, `claim_unit`, `claim_period`):++ ```text+ | # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |+ |---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|+ ```++- **Shortest row, 9 cells:** the narrow row without `context`. A row that is short anywhere else is `short_row`.++<a id="takes-columns"></a>+## Takes columns++Takes cells are read by position, except `resolved`, `quality`, `evidence`, `value`, `unit`, `by`, which are read by header name.++| Position | Column | Values | May be left off the row end | Default when the header lacks it | Meaning |+| --- | --- | --- | --- | --- | --- |+| 1 | `#` | a positive whole number | no | - | Row number. |+| 2 | `claim` | free text | no | - | The position, free text. `~~claim~~` marks a row that is no longer active. |+| 3 | `kind` | `fact`, `take`, `bet`, `hunch` | no | - | What the take is. |+| 4 | `who` | `world`, `brain`, `people/<slug>`, `companies/<slug>` | no | - | Who holds the position (see [holders](#holders)): who said or clearly implied it, not who it is about. |+| 5 | `weight` | a number from 0 to 1 | no | - | How strongly it is held; stored on the 0.05 grid. There is no default. |+| 6 | `since` | free text | no | - | When the holder took the position (`YYYY-MM-DD` or `YYYY-MM`; `start → end` for a range). |+| 7 | `source` | free text | yes | - | Where it came from. `superseded by #N` names the row that replaced a struck row. |+| 8 | `resolved` | free text | yes | - | When the take was resolved. Read by header name. |+| 9 | `quality` | free text | yes | - | How the take turned out. Read by header name. |+| 10 | `evidence` | free text | yes | - | What resolved it. Read by header name. |+| 11 | `value` | free text | yes | - | Resolved value. Read by header name. |+| 12 | `unit` | free text | yes | - | Unit of the resolved value. Read by header name. |+| 13 | `by` | free text | yes | - | Who resolved it. Read by header name. |++<a id="takes-layouts"></a>+- **Narrow, 7 cells** (what gbrain writes unless a row needs a wide column):++ ```text+ | # | claim | kind | who | weight | since | source |+ |---|-------|------|-----|--------|-------|--------|+ ```++- **Wide, 13 cells** (adds `resolved`, `quality`, `evidence`, `value`, `unit`, `by`):++ ```text+ | # | claim | kind | who | weight | since | source | resolved | quality | evidence | value | unit | by |+ |---|-------|------|-----|--------|-------|--------|----------|---------|----------|-------|------|----|+ ```++- **Shortest row, 6 cells:** the narrow row without `source`. A row that is short anywhere else is `short_row`.++<a id="holders"></a>+## Holders++A takes `who` cell is one of `world`, `brain`, `people/<slug>`, `companies/<slug>`. Slugs are lowercase.++| Written | Valid | What gbrain does |+| --- | --- | --- |+| `world` | yes | Accepted. |+| `brain` | yes | Accepted. |+| `people/alice-example` | yes | Accepted. |+| `companies/acme-example` | yes | Accepted. |+| `alice-example` | yes | Accepted (an older bare-slug form); write `people/<slug>` or `companies/<slug>` instead. |+| `System` | no | Rewritten to `brain` (`holder_alias`). |+| `Alice Example` | no | Not a holder: `holder_unresolved`. Tier 2 resolves it only to one verified page; otherwise a person fixes it. |+| `people/Alice-Example` | no | Not a holder: `holder_unresolved`. Tier 2 resolves it only to one verified page; otherwise a person fixes it. |+| `world/alice-example` | no | Not a holder: `holder_unresolved`. Tier 2 resolves it only to one verified page; otherwise a person fixes it. |+| `users/alice-example` | no | Not a holder: `holder_unresolved`. Tier 2 resolves it only to one verified page; otherwise a person fixes it. |++<a id="row-numbers"></a>+## Row numbers++- `#` is a positive whole number, unique per fence kind across the whole page: the body and the timeline count together.+- A struck row keeps its number, and `superseded by #N` must name a row on the page.+- gbrain renumbers a row whose number is zero, negative, not a number or a duplicate. When two rows share a number, the row that matches the stored row keeps it. A new number is one above every number on the page (live and struck, both sections) and every stored row number of the page, so a freed number is not reused. A number whose only trace was deleted before this release is not known and could be reused.+- gbrain does not renumber a duplicate that a `superseded by #N` reference names (`superseded_ambiguous`), or rows hidden from a remote caller.++<a id="examples"></a>+## Examples++A valid facts fence (narrow layout; row 2 was superseded by row 3):++```markdown+<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | Acme Example plans to open its widget API in 2026 | event | 0.9 | private | high | 2026-03-01 | | meetings/2026-04-03 | |+| 2 | ~~Acme Example has 12 engineers~~ | fact | 1.0 | private | medium | 2025-06-01 | 2026-01-15 | companies/acme-example | superseded by #3 |+| 3 | Acme Example has 18 engineers | fact | 1.0 | private | medium | 2026-01-15 | | companies/acme-example | |+<!--- gbrain:facts:end -->+```++A valid takes fence (narrow layout):++```markdown+<!--- gbrain:takes:begin -->+| # | claim | kind | who | weight | since | source |+|---|-------|------|-----|--------|-------|--------|+| 1 | Acme Example reaches profitability in 2027 | bet | people/alice-example | 0.65 | 2026-04 | meetings/2026-04-03 |+| 2 | Widget pricing drives most churn | take | brain | 0.55 | 2026-04 | |+| 3 | Acme Example sells developer tools | fact | world | 1.0 | 2026-01 | companies/acme-example |+<!--- gbrain:takes:end -->+```++<a id="normalized"></a>+## What gbrain fixes by itself++These rules run on every write path for free. They edit or move cell text and never re-render a table. A fence they fix completely is written back in fixed form; each fix is reported by its class, row and column.++| Class | What it rewrites |+| --- | --- |+| `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. |+| `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. |+| `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`. |++<a id="header-spellings"></a>+### Header spellings++Header cells are compared case-insensitively, with spaces, `_` and `-` treated alike. A column not listed accepts only its own name.++| facts column | Also accepted in a header |+| --- | --- |+| `#` | `row`, `row #`, `row num`, `row number`, `no`, `no.`, `num` |+| `claim` | `fact`, `statement` |+| `kind` | `type`, `category` |+| `confidence` | `conf`, `weight` |+| `visibility` | `vis` |+| `notability` | `importance` |+| `valid_from` | `valid from`, `since`, `date`, `from` |+| `valid_until` | `valid until`, `until`, `to` |+| `source` | `src` |+| `context` | `notes`, `note` |+| `claim_metric` | `claim metric`, `metric` |+| `claim_value` | `claim value`, `value` |+| `claim_unit` | `claim unit`, `unit` |+| `claim_period` | `claim period`, `period` |++| takes column | Also accepted in a header |+| --- | --- |+| `#` | `row`, `row #`, `row num`, `row number`, `no`, `no.`, `num` |+| `claim` | `take`, `statement` |+| `kind` | `type` |+| `who` | `holder` |+| `weight` | `confidence`, `conf` |+| `since` | `date`, `as of` |+| `source` | `src` |++<a id="never-guessed"></a>+## What gbrain never guesses++A 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).+- **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).++<a id="gates"></a>+### Gates every repair passes++No tier writes a fence until all of these hold, and the result is one the rules above would leave unchanged. A Tier 3 proposal that fails one stays held with the gate and rows named.++| Gate | Reason when it fails | What must hold |+| --- | --- | --- |+| (a) | [`still_invalid`](write-refusals.md#fence-still_invalid) | The result parses with no warning: no repeated marker, unique row numbers. |+| (b) | [`claim_changed`](write-refusals.md#fence-claim_changed) | Every claim cell is unchanged (struck claims included). |+| (c) | [`row_number_changed`](write-refusals.md#fence-row_number_changed) | Every row number that was valid and unique still names the same claim. |+| (d) | [`visibility_loosened`](write-refusals.md#fence-visibility_loosened) | No row becomes more visible: `private` never turns `world`. |+| (e) | [`row_count_changed`](write-refusals.md#fence-row_count_changed) | No row is added or dropped, and every row of the fence stays inside it. |+| (f) | [`cell_changed`](write-refusals.md#fence-cell_changed) | A cell valid in its column keeps its text; a misaligned cell may only move, and text changes only through a named rule. |+| (g) | [`protection_loosened`](write-refusals.md#fence-protection_loosened) | Text the privacy boundary hid before the repair stays hidden after it. |+<!-- END GENERATED fence-format -->diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex ef2ebd8f48..8f3fd406e0 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -276,11 +276,12 @@ vars — incident-time escape hatches, not everyday knobs.repaired. A hold clears when the file changes, is deleted, or a newergbrain can read it; `gbrain sync --dry-run` lists would-be holds(`would_hold`) without writing anything. The backlog fix is one previewed,- hash-bound command:+ hash-bound command per kind of hold:```bashgbrain sources status <source-id> # what is held and why- gbrain repair frontmatter --source <source-id> # preview; writes nothing+ gbrain repair frontmatter --source <source-id> # frontmatter holds: preview; writes nothing+ gbrain repair fences --source <source-id> # fence holds: preview; writes nothing, no model call```A fence whose meaning is unambiguous (a missing end marker after the@@ -289,13 +290,19 @@ vars — incident-time escape hatches, not everyday knobs.reports `fences_normalized` (`gbrain sync --dry-run` lists`would_normalize`; `gbrain config set fences.normalize false` turns it off).A fence hold (`invalid_fence`) names the fence, section, reason and row- numbers, never a cell. Fix it by reading the page- (`gbrain get --source <source-id> -- <slug>`), editing that fence in the- file, committing, and running `gbrain sync --source <source-id> --no-pull`;- frontmatter repair does not touch fences. A fence refused only while being- prepared against the stored page (for example a takes row number a stored- take already uses) is held in the same run as `prepare_time`. See- [fence holds](write-refusals.md#invalid_fence).+ numbers, never a cell, and clears by itself: the maintenance run's+ `fence_repair` phase repairs it on the owner host (exact rules first, then+ the configured chat model for rows only a rewrite can realign, within+ the daily spend cap) and commits the file.+ `gbrain repair fences --source <source-id>` previews the same repair and+ prints its apply command, which needs no extra consent; frontmatter repair+ does not touch fences. A hold whose reason is `manual` needs a person: read+ the page (`gbrain get --source <source-id> -- <slug>`), edit that fence in+ the file, commit, and run `gbrain sync --source <source-id> --no-pull`. A+ fence refused only while being prepared against the stored page (for+ example a takes row number a stored take already uses) is held in the same+ run as `prepare_time`. See [fence holds](write-refusals.md#invalid_fence)+ and [fence repair](repair.md#fences).Walkthrough with real output: [held files](repair.md#held-files); codes:[content refusals](write-refusals.md#held-files-and-content-refusals).@@ -303,7 +310,11 @@ vars — incident-time escape hatches, not everyday knobs.holds; for fences, legacy sync stores the normalized fence in the database(it never rewrites the file), keeps importing a page whose fence cannot benormalized with its bad rows skipped (reported in `fence_issues`), and- never holds it. Holds never count toward the+ never holds it. The fence repair still repairs such a file: on a legacy+ source it re-reads the file, backs it up under `~/.gbrain/backups/`,+ writes and imports it, and leaves the change for you to commit+ (`gbrain sources status` names the `git add`/`git commit` command until+ you do). Holds never count toward thelegacy auto-skip streak below. A source blocked by such a file before thisrelease recovers on its next sync, or now with`gbrain sync --source <source-id> --no-pull`. Teams that want fail-closeddiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 8136d0fe4f..4efbf9bebb 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -819,6 +819,23 @@ step. Per-file outcomes report `written`, `imported`, `hold_cleared` and`committed`. Repair stays explicit-only: `gbrain repair --all` and`gbrain doctor --remediate` never run it.+<a id="fences"></a>+### Fences++`gbrain repair fences` repairs malformed facts and takes fences: files sync+held with `invalid_fence`, stored pages whose fence does not parse, and+checkout files not yet synced. The maintenance run applies the same repair+automatically (phase `fence_repair`), so a fence hold usually clears with no+command. The preview is read-only and makes no model call; applying needs no+extra consent. What each reason means and who acts:+[fence holds](write-refusals.md#invalid_fence); the format and every rule:+[fence format](fence-format.md).++```bash+gbrain repair fences --source <id> # preview: tiers, rows, estimated model cost, apply command+gbrain repair fences --source <id> --apply --expect <hash> # apply exactly the previewed set+```+## ResumeRuns are resumable. After each page commits, the position is saved under thediff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 5c97176c17..eecc41deb8 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -22,7 +22,7 @@| [Doctor residue (`timeline_history`, `derived_visibility`, `safe_index_pending`)](#doctor-residue) | preview `gbrain doctor --remediation-plan --json` or `gbrain repair`; then `gbrain repair <kind> --apply` | brain host, after the user agrees | `destructive` (rewrites derived rows) | `gbrain doctor --only timeline_history,derived_visibility,safe_index_pending --json` || Low health score | preview `gbrain doctor --remediation-plan --json`; then `gbrain doctor --remediate --yes --target-score 90 --max-usd 5` | agent, after the user agrees | `paid`; `destructive` with `--include-repairs` (approve with `--expect <plan_hash>` from the preview) | `gbrain doctor --json` || [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` |-| [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | `gbrain sources status <id>` names the fence, section, rows and reason; read the page with `gbrain get --source <id> -- <slug>`, edit that fence in the file, commit, then `gbrain sync --source <id> --no-pull` | agent (the user's file; editing the named fence is the requested fix) | none | `gbrain sources status <id> --json` (the hold is gone) |+| [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` || [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` || [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` || [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |@@ -41,7 +41,7 @@<a id="held-files"></a>**Sync held a file (`Held <path>: invalid_frontmatter …`, doctor `git_held_files`, `get_page` shows `file_held`)?** The sync succeeded; only that file waits, and its page (if any) keeps its last good revision and refuses `put_page` until the file is repaired. Run `gbrain sources status <id>`, preview `gbrain repair frontmatter --source <id>`, and after the user agrees run the printed apply. A source a broken file blocked before upgrading recovers on its next sync (`gbrain sync --source <id> --no-pull` does it now). See [held files](repair.md#held-files).-<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell. Read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. A fence with one obvious meaning is never held: sync rewrites it losslessly, commits the file and reports `fences_normalized`; a `fence_normalized` notice on a write means re-read the page before editing it. `gbrain doctor --only fence_integrity` counts every malformed fence still waiting (held, stored or unsynced) by tier. See [fence holds](write-refusals.md#invalid_fence).+<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell, and most holds clear by themselves: the maintenance run's `fence_repair` phase repairs the fence on the owner host and commits the file. To see the plan or do it now, run `gbrain repair fences --source <id>` (a read-only preview with no model call), then the apply command it prints; applying needs no extra consent. Model repair spends only within `fences.repair.max_usd_per_page` and `fences.repair.max_usd_per_day`; raising them, or pausing automatic repair with `gbrain config set fences.repair.enabled false`, is the user's call. A hold whose reason is `manual` needs a person: read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. A fence with one obvious meaning is never held: sync rewrites it losslessly, commits the file and reports `fences_normalized`; a `fence_normalized` notice on a write means re-read the page before editing it. `gbrain doctor --only fence_integrity` counts every malformed fence still waiting (held, stored or unsynced) by tier. See [fence holds](write-refusals.md#invalid_fence), [fence repair](repair.md#fences) and the [fence format](fence-format.md).<a id="held-connector-items"></a>**A Google or GitHub item is held after repeated failures (doctor `connector_held_items`, `gbrain waiting` says coverage is partial)?** Run `gbrain sources status <id>`, fix the cause, then after the user agrees run `gbrain sources retry-held <id>` and `gbrain sync --source <id>`. See [held items](google-connect.md#held-items).diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 33edb07396..86c215802c 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -151,23 +151,42 @@ with each file and fix the ones that need no guessing."*| <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. || <a id="parser_regression"></a>`parser_regression` | With `sync.parser_regression=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. || <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `sync.parser_regression=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull --retry-failed`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). |-| <a id="changed_since_preview"></a>`changed_since_preview` | A `gbrain repair frontmatter --apply` found a file, its proposed change or its page different from what the preview showed, so that file was not written. | Preview again, show the user the new diff and approve its new hash. |+| <a id="changed_since_preview"></a>`changed_since_preview` | A hash-bound repair apply (`gbrain repair frontmatter --apply --expect <hash>`, `gbrain repair fences --apply --expect <hash>`) found a file, its proposed change or its page different from what the preview showed, so that item was not written; the rest of the approved set still applied. | Preview again with the same selection and apply the new hash. For frontmatter, show the user the new diff first; a fence repair needs no extra consent ([fence reason](#fence-changed_since_preview)). |<a id="invalid_fence"></a>### Fence holds (`invalid_fence`)-A page's facts and takes fences are its structured rows. A coordinated write-(managed sync, managed `gbrain import`, `put_page` on a managed brain, managed-file repair) refuses a fence it cannot import without dropping or guessing-rows: code `invalid_fence`, wire `error` `invalid_params` (`take_row_collision`-for a stored-row collision). During managed sync the file is **held** instead-and the rest of the source syncs. The message reads+A page's facts and takes fences are its structured rows+([format](fence-format.md)). A coordinated write (managed sync, managed+`gbrain import`, `put_page` on a managed brain, managed file repair) refuses a+fence it cannot import without dropping or guessing rows: code+`invalid_fence`, wire `error` `invalid_params` (`take_row_collision` for a+stored-row collision). During managed sync the file is **held** instead and+the rest of the source syncs. The message reads`Fence <reason>: in the <facts|takes> fence (<body|timeline>), row(s) N, column(s) C, at line L.`(the parts that apply; the line counts within the section), then the fix. Itnames fence, section, row numbers, column names and lines only, never a claim,-holder or cell. Holds carry the same location as-`fence: { reason, fence, section, rows, columns, line }`; a failed receipt-keeps it in `write_error_detail.fence` (row numbers stay on the brain host).+holder or cell. A failed receipt keeps the location in+`write_error_detail.fence` (row numbers stay on the brain host).++<a id="fence-hold"></a>**What a fence hold carries.** Every surface that shows+a hold (`gbrain sources status <source>`, doctor `git_held_files`,+`get_page.file_held`, the sync result) gives the same location-only fields:++- `fence`: `reason`, `fence` (`facts` or `takes`), `section` (`body` or+ `timeline`), `rows` (row numbers), `columns` (column names) and `line` (the+ first bad line, counted within the section).+- The reason's `tier`, the repair that clears it (`deterministic`,+ `resolver`, `llm` or `manual`), and `auto_retry`, whether the maintenance+ run clears or retries it with no one acting. The table below lists both+ for every reason.+- After a repair has tried the file, `fence_repair`: that attempt's `reason`,+ `tier` and `at`, `next_attempt_after` (when the maintenance run tries it+ again; null when it will not), and `gate` and `rows` when a proposed repair+ was rejected.+- `fix`, the next command (a single held file's preview,+ `gbrain repair fences --source <source> --only <path>`), and `docs`, the+ reason's anchor below.**What gbrain fixes by itself.** Before refusing or holding, every write pathruns the fence through a lossless normalizer: a missing end marker with only@@ -179,18 +198,19 @@ header-level defaults (`confidence 1.0`, `notability medium`,only on a world-visible page, else `private`), invented facts kinds (mapped tothe closest kind, the original word kept in `context`), a short list of takeskind synonyms, assistant holders (`System`, `assistant` → `brain`) and percent-confidences. It never changes a claim, an existing row number or a valid cell,-and never makes a row more visible. A fence it fixes completely is written in-its normalized form: managed sync commits the rewritten file (a read-only-mirror keeps it database-only; a company-brain source refuses-`source_writeback_required` naming the fence), and the result reports-`fences_normalized` (`count`, `by_class`, `writers`, sample paths for local-callers). A write also carries one `fence_normalized` coaching notice: the-stored page differs from what was sent, so re-read it with `get_page` before-editing; `remember` and `takes_add` write rows that never need it.-`gbrain sync --dry-run` lists `would_normalize` beside `would_hold`.-`gbrain config set fences.normalize false` turns normalization off: a fixable-fence is then held or refused like any other.+confidences ([every rule](fence-format.md#normalized)). It never changes a+claim, an existing row number or a valid cell, and never makes a row more+visible. A fence it fixes completely is written in its normalized form:+managed sync commits the rewritten file (a read-only mirror keeps it+database-only; a company-brain source refuses `source_writeback_required`+naming the fence), and the result reports `fences_normalized` (`count`,+`by_class`, `writers`, sample paths for local callers). A write also carries+one `fence_normalized` coaching notice: the stored page differs from what was+sent, so re-read it with `get_page` before editing; `remember` and+`takes_add` write rows that never need it. `gbrain sync --dry-run` lists+`would_normalize` beside `would_hold`. `gbrain config set fences.normalize false`+turns normalization off: a fixable fence is then held or refused like any+other.What the normalizer cannot fix exactly is refused or held as below; a refusallists every blocking problem in `fence_issues`@@ -204,15 +224,45 @@ documented exceptions keep blocking with the typed refusal instead ofholding: `sync.holds=fail`, and company-brain sources, which never hold andnever rewrite repository files (fix the fence in the repository and commit).-**Say to your agent:** *"Sync held a page because of its facts table. Show me-which rows are wrong and fix them."*+<a id="fence-repair"></a>**Repair.** Fence holds clear by themselves: the+maintenance run's `fence_repair` phase repairs held files and stored pages+whose fences do not parse, on the brain's owner host. A repaired file is+committed like any page write on a managed source; on a legacy source it is+backed up under `~/.gbrain/backups/` and left for you to commit. To see what+it would change, or to do it now:++```bash+gbrain repair fences --source <source> # preview: read-only, no model call+gbrain repair fences --source <source> --apply --expect <hash> # the apply command the preview prints+```-Fix: read the page (`gbrain get --source <source> -- <slug>`), edit only the-named fence in the file (never the frontmatter), commit, then+The preview lists each held file and stored page with its reasons, rows and+columns, the tier that fixes it and the estimated model cost against the+remaining 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 3+sends 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+`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) before+anything is written. `--no-llm` keeps a run to the free tiers and+`--max-usd <n>` lowers its cap; raising spend+(`gbrain config set fences.repair.max_usd_per_day <usd>`) or turning model+repair back on (`gbrain config set fences.repair.llm true`) is the user's+call. MCP and thin-client callers cannot run a repair: the hold's fix names+the owner-host command to hand to the user. Walkthrough with real output:+[fence repair](repair.md#fences).++A `manual` reason needs a person, because gbrain never guesses it: read the+page (`gbrain get --source <source> -- <slug>`), edit only the named fence in+the file (never the frontmatter), commit, then`gbrain sync --source <source> --no-pull`. `gbrain sources status <source>`lists every fence hold with its location. To add rows without hand-editing atable, use `remember` (facts) or `takes_add` (takes).+**Say to your agent:** *"Sync held a page because of its facts table. Show me+which rows are wrong and fix them."*+<a id="fence-integrity"></a>**How many are left.** `gbrain doctor --only fence_integrity`counts, per source, every malformed fence still waiting, once each: a heldfile, a stored page whose fence does not parse (for example one an older@@ -227,43 +277,67 @@ model-repair caps `fences.repair.max_usd_per_page` (default $0.05) 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`.-The fix is the edit above for held and unsynced files, and for a stored page:-read it with `gbrain get --source <source> -- <slug>` and write it again with-`put_page`.+The maintenance run repairs the `deterministic` and `resolver` ones by itself,+and the `llm` ones while model repair is on and within the caps;+`gbrain repair fences --source <source>` previews the plan.**Say to your agent:** *"How many broken facts or takes tables are left in my brain?"*-| `invalid_fence` reason | What it means | Recovery |-| --- | --- | --- |-| <a id="fence-repeated_marker"></a>`repeated_marker` | A body or timeline section has a second begin or end marker for the same fence outside code. | Keep one begin and one end marker per fence in that section, with every row in one table. |-| <a id="fence-missing_begin"></a>`missing_begin` | An end marker has no begin marker before it. | Add the begin marker above the table, or delete the stray end marker. |-| <a id="fence-marker_near_miss"></a>`marker_near_miss` | A takes marker uses the two-dash form (`<!-- gbrain:takes:begin -->`) instead of the three-dash marker, or a line mentions it outside a fence. | Use the exact three-dash markers around the takes table, or wrap a mere mention in backticks. |-| <a id="fence-unparseable"></a>`unparseable` | The fence does not parse cleanly: most often it has no end marker, or a row number is not a positive whole number (`column #`). | Add the end marker directly after the last table row, or fix the named row number. |-| <a id="fence-no_header"></a>`no_header` | The fence has table rows but no header row naming `claim` and `kind`. | Add the canonical header (below) as the first table line. |-| <a id="fence-row_before_header"></a>`row_before_header` | Rows sit above the header row. | Move them below the header. |-| <a id="fence-short_row"></a>`short_row` | A row has too few cells, so its columns are ambiguous. | Add the missing cells so every column lines up. |-| <a id="fence-extra_cells"></a>`extra_cells` | A row has more cells than the header, often an unescaped `\|` in a cell. | Escape the pipe as `\|` or remove the extra cell. |-| <a id="fence-enum_unmapped"></a>`enum_unmapped` | A facts `kind`, `visibility` or `notability` cell holds a value outside the allowed list (the message names the column and the allowed values). | Use one of the allowed values. |-| <a id="fence-takes_kind_unsupported"></a>`takes_kind_unsupported` | A takes `kind` is not fact, take, bet or hunch. gbrain never chooses a takes kind for you. | Use one of the four kinds. |-| <a id="fence-confidence_out_of_range"></a>`confidence_out_of_range` | A facts `confidence` is not a number from 0 to 1. | Write it as a decimal such as 0.8. |-| <a id="fence-claim_value_invalid"></a>`claim_value_invalid` | A facts `claim_value` is not a number. | Write a number (1,234 separators and a k/M/B suffix are allowed) or leave it empty. |-| <a id="fence-weight_missing"></a>`weight_missing` | A takes `weight` is missing or not a number. Takes have no default weight. | Add a weight from 0 to 1. |-| <a id="fence-holder_unresolved"></a>`holder_unresolved` | A takes `who` cell is not `world`, `brain`, `people/<slug>` or `companies/<slug>`. | Write one of those forms. |-| <a id="fence-row_collision"></a>`row_collision` | Two rows of the same fence kind share a row number, in one fence or across the body and timeline (`rows` lists the numbers). | Give one row a new number above every number used on the page. |-| <a id="fence-quoted_fence_rows"></a>`quoted_fence_rows` | A fence sits inside a code block or inline code span, so readers treat it as an example and importing would remove the stored rows it holds. | Move the fence out of the code, or delete the fence to remove its rows. |-| <a id="fence-stored_row_collision"></a>`stored_row_collision` | A new takes row's number already names a different stored take that is not in the page's fence (wire `take_row_collision`). | Renumber the new row, or add the stored take back to the fence. |-| <a id="fence-withdrawn_claim_in_malformed_fence"></a>`withdrawn_claim_in_malformed_fence` | A facts fence that does not parse holds a claim the user withdrew, so gbrain cannot tell whether the row should stay withdrawn. | Repair the fence so it parses; the withdrawn row then stays withdrawn. |-| <a id="fence-target_fence_malformed"></a>`target_fence_malformed` | A verb that appends to or edits a page (`remember`, `extract_facts`, `takes_*`, `facts relink`, `edit_page`) found that page's stored fence does not parse and cannot be normalized in the same write (`edit_page` and the other takes writes never normalize). Memory verbs keep their v1 code (`invalid_params`, `detail: invalid_fence`). | Read the page, fix the named fence (or write the whole page with `put_page`, which normalizes what it can and names every row it cannot), then retry with a new request_id. |-| <a id="fence-normalizer_failed"></a>`normalizer_failed` | The normalizer or its validator failed on this fence (a gbrain bug); the fence was not rewritten. A coordinated write refuses; a legacy import stores the page as written. | Run `gbrain doctor --json` and report it with the gbrain version; an upgrade re-screens the file. |-| <a id="fence-prepare_time"></a>`prepare_time` | Hold only: the file passed the content screen, but its fence was refused while it was prepared against the stored page (a stored-row collision, a withdrawn claim, rows quoted in code). `fence.reason` names which. Managed sync holds it in the same run instead of blocking. | Fix it as its `fence.reason` says. After a database-side fix (for example removing the conflicting take), `gbrain sources retry-held <source>` re-checks the file. |--Fence format. Markers are `<!--- gbrain:facts:begin -->` / `<!--- gbrain:facts:end -->`-and `<!--- gbrain:takes:begin -->` / `<!--- gbrain:takes:end -->` (three dashes).-The first table row is a header naming `claim` and `kind`.--- Facts rows: `| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |` (10 cells; 9 when the trailing context is empty; 14 with `claim_metric`, `claim_value`, `claim_unit`, `claim_period`). `kind` is event, preference, commitment, belief, fact or idea; `visibility` private or world; `notability` high, medium or low; `confidence` a number from 0 to 1.-- Takes rows: `| # | claim | kind | who | weight | since | source |` (7 cells; 6 without source; 13 with `resolved`, `quality`, `evidence`, `value`, `unit`, `by`). `kind` is fact, take, bet or hunch; `who` is world, brain, `people/<slug>` or `companies/<slug>`; `weight` a number.-- Row numbers are positive whole numbers, unique per fence kind across the whole page.+Each reason's **Tier** is the repair that clears it (`-` when that depends on+the page, which is screened again); **Auto** says whether the maintenance run+clears or retries it with no one acting.++| `invalid_fence` reason | What it means | Tier | Auto | Recovery |+| --- | --- | --- | --- | --- |+| <a id="fence-header_unmapped"></a>`header_unmapped` | The header has a column with no canonical name and no known spelling, so its cells cannot be placed. | `llm` | yes | Repaired by the next maintenance run (preview: `gbrain repair fences --source <source>`). By hand: rename each column to its canonical name. Format: [header spellings](fence-format.md#header-spellings). |+| <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-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). |+| <a id="fence-unclosed_trailing_content"></a>`unclosed_trailing_content` | A fence has no end marker and other text follows its table, so closing it automatically could expose text the privacy boundary hides. | `manual` | no | Add the end marker directly after the last table row, or wrap a mere mention of the marker in backticks. Format: [markers](fence-format.md#markers). |+| <a id="fence-marker_near_miss"></a>`marker_near_miss` | A line uses the two-dash takes marker (`<!-- gbrain:takes:begin -->`) or mentions it with no takes table after it. Two-dash markers directly above a takes table are rewritten by themselves. | `manual` | no | Use the exact three-dash markers around the takes table, or wrap a mere mention in backticks. Format: [markers](fence-format.md#markers). |+| <a id="fence-repeated_marker"></a>`repeated_marker` | A body or timeline section has a second begin or end marker for the same fence outside code. | `manual` | no | Keep one begin and one end marker per fence in that section, with every row in one table. Format: [markers](fence-format.md#markers). |+| <a id="fence-takes_in_facts"></a>`takes_in_facts` | A facts fence holds a takes table. | `manual` | no | Move the rows into a takes fence (or add them with `takes_add`), or rewrite them as facts rows. Format: [takes](fence-format.md#takes-columns). |+| <a id="fence-superseded_ambiguous"></a>`superseded_ambiguous` | Two rows share a number and a `superseded by #N` reference names that number, so renumbering could repoint the reference. | `manual` | no | Decide which row keeps the number, give the other a number above every number on the page, and fix the reference. Format: [row numbers](fence-format.md#row-numbers). |+| <a id="fence-enum_unmapped"></a>`enum_unmapped` | A facts `kind`, `visibility` or `notability` cell holds a value outside the allowed list and its synonyms (the message names the column and the allowed values). | `manual` | no | Use one of the allowed values. Format: [facts](fence-format.md#facts-columns). |+| <a id="fence-weight_missing"></a>`weight_missing` | A takes row has no `weight`, or the header has no weight column. Takes have no default weight. | `manual` | no | Add a weight from 0 to 1. Format: [takes](fence-format.md#takes-columns). |+| <a id="fence-holder_missing"></a>`holder_missing` | A takes row has no holder, or the header has no `who` column. | `manual` | no | Add the holder: `world`, `brain`, `people/<slug>` or `companies/<slug>`. Format: [holders](fence-format.md#holders). |+| <a id="fence-confidence_out_of_range"></a>`confidence_out_of_range` | A facts `confidence` or takes `weight` is not a number from 0 to 1 (a percent such as `85%` is rewritten by itself). | `manual` | no | Write the intended value as a decimal such as 0.8. Format: [facts](fence-format.md#facts-columns), [takes](fence-format.md#takes-columns). |+| <a id="fence-claim_value_invalid"></a>`claim_value_invalid` | A facts `claim_value` is not a number. | `manual` | no | Write a number (1,234 separators and a k/M/B suffix are allowed) or leave it empty. Format: [facts](fence-format.md#facts-columns). |+| <a id="fence-takes_kind_unsupported"></a>`takes_kind_unsupported` | A takes `kind` is not fact, take, bet or hunch and is not one of the few synonyms gbrain maps (a kind the schema pack declares but the parser does not accept included). gbrain never chooses a takes kind for you. | `manual` | no | Use one of the four kinds. Format: [takes](fence-format.md#takes-columns). |+| <a id="fence-unparseable"></a>`unparseable` | The fence does not parse cleanly: most often it has no end marker, or a row number is not a positive whole number (`column #`). | `-` | yes | Usually repaired by itself on the next write or maintenance run. By hand: add the end marker directly after the last table row, or fix the named row number. Format: [markers](fence-format.md#markers). |+| <a id="fence-row_collision"></a>`row_collision` | Two rows of the same fence kind share a row number, in one fence or across the body and timeline (`rows` lists the numbers). | `-` | yes | Usually renumbered by itself. By hand: give one row a new number above every number used on the page. Format: [row numbers](fence-format.md#row-numbers). |+| <a id="fence-quoted_fence_rows"></a>`quoted_fence_rows` | A fence sits inside a code block or inline code span, so readers treat it as an example and importing would remove the stored rows it holds. | `-` | no | Move the fence out of the code, or delete the fence to remove its rows. Format: [markers](fence-format.md#markers). |+| <a id="fence-stored_row_collision"></a>`stored_row_collision` | A new takes row's number already names a different stored take that is not in the page's fence (wire `take_row_collision`). | `-` | no | Renumber the new row, or add the stored take back to the fence. Format: [row numbers](fence-format.md#row-numbers). |+| <a id="fence-withdrawn_claim_in_malformed_fence"></a>`withdrawn_claim_in_malformed_fence` | A facts fence that does not parse holds a claim the user withdrew, so gbrain cannot tell whether the row should stay withdrawn. | `-` | yes | Repair the fence so it parses (`gbrain repair fences --source <source>` previews it); the withdrawn row then stays withdrawn. Format: [examples](fence-format.md#examples). |+| <a id="fence-target_fence_malformed"></a>`target_fence_malformed` | A verb that appends to or edits a page (`remember`, `extract_facts`, `takes_*`, `facts relink`, `edit_page`) found that page's stored fence does not parse and cannot be normalized in the same write (`edit_page` and the other takes writes never normalize). Memory verbs keep their v1 code (`invalid_params`, `detail: invalid_fence`). | `-` | yes | The maintenance run repairs the stored fence; to do it now, `gbrain repair fences --slug <slug>` on the brain host. Or read the page, fix the named fence (or write the whole page with `put_page`, which normalizes what it can and names every row it cannot), then retry with a new request_id. Format: [examples](fence-format.md#examples). |+| <a id="fence-prepare_time"></a>`prepare_time` | Hold only: the file passed the content screen, but its fence was refused while it was prepared against the stored page (a stored-row collision, a withdrawn claim, rows quoted in code). `fence.reason` names which. Managed sync holds it in the same run instead of blocking. | `-` | yes | Fix it as its `fence.reason` says. After a database-side fix (for example removing the conflicting take), `gbrain sources retry-held <source>` re-checks the file. Format: [what gbrain never guesses](fence-format.md#never-guessed). |+| <a id="fence-normalizer_failed"></a>`normalizer_failed` | The normalizer or its validator failed on this fence (a gbrain bug); the fence was not rewritten. A coordinated write refuses; a legacy import stores the page as written. | `manual` | no | Run `gbrain doctor --json` and report it with the gbrain version; an upgrade re-screens the file. Format: [what gbrain fixes](fence-format.md#normalized). |+| <a id="fence-llm_unavailable"></a>`llm_unavailable` | The repair model timed out, was rate-limited or returned a server error. | `llm` | yes | Nothing to do: the next maintenance run (or `gbrain repair fences --apply`) retries. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-llm_empty"></a>`llm_empty` | The repair model returned nothing for the fence. | `llm` | no | Fix the named rows by hand. The same file is not sent to the model again until it, the model (`models.fence_repair`) or gbrain's repair rules change. Format: [tiers](fence-format.md#never-guessed). |+| <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_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-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). |+| <a id="fence-owner_unavailable"></a>`owner_unavailable` | This host is not the brain's owner host, and fence repairs run only there. | `-` | yes | Run `gbrain repair fences` on the owner host (`gbrain sources writer status <source>` names it). A remote caller hands that command to the user. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-owner_cli_required"></a>`owner_cli_required` | The maintenance worker may not apply this managed-file repair; it must be applied from the owner host's CLI. | `-` | no | On the owner host: `gbrain repair fences --source <source>`, then the printed apply command. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-sync_in_progress"></a>`sync_in_progress` | A managed sync of the source has an unfinished cursor, or a queued sync request names the file, so the repair skipped it. | `-` | yes | Nothing to do: the next run retries. To finish the sync now: `gbrain sync --source <source> --no-pull`. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-time_budget"></a>`time_budget` | The repair run reached its time budget (the maintenance phase stops at the smaller of 300 s and a third of the job's remaining deadline). | `-` | yes | Nothing to do: the next run resumes where it stopped. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-changed_since_read"></a>`changed_since_read` | The file changed after the repair read it, so nothing was written. | `-` | yes | Nothing to do: the next run reads it again. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-changed_since_preview"></a>`changed_since_preview` | `gbrain repair fences --apply --expect <hash>` found the file's bytes or the page's revision changed since the preview, so that item was not applied. | `-` | no | Preview again with the same selection and apply the new `--expect` hash. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-still_invalid"></a>`still_invalid` | Gate (a): the proposed repair still does not parse cleanly. Nothing was written. | `-` | no | Fix the named rows by hand. Format: [gates](fence-format.md#gates). |+| <a id="fence-claim_changed"></a>`claim_changed` | Gate (b): the proposed repair changed claim text. Nothing was written. | `-` | no | Fix the named rows by hand. Format: [gates](fence-format.md#gates). |+| <a id="fence-row_number_changed"></a>`row_number_changed` | Gate (c): the proposed repair changed or dropped an existing valid row number. Nothing was written. | `-` | no | Fix the named rows by hand. Format: [gates](fence-format.md#gates). |+| <a id="fence-visibility_loosened"></a>`visibility_loosened` | Gate (d): the proposed repair made a row more visible. Nothing was written. | `-` | no | Fix the named rows by hand; ask the user which visibility is intended, never widen it yourself. Format: [gates](fence-format.md#gates). |+| <a id="fence-row_count_changed"></a>`row_count_changed` | Gate (e): the proposed repair added or dropped a row, or left one outside the fence. Nothing was written. | `-` | no | Fix the named rows by hand. Format: [gates](fence-format.md#gates). |+| <a id="fence-cell_changed"></a>`cell_changed` | Gate (f): the proposed repair changed a cell no named rule allows (a valid weight, holder, date, source, confidence or context). Nothing was written. | `-` | no | Fix the named columns of the named rows by hand. Format: [gates](fence-format.md#gates). |+| <a id="fence-protection_loosened"></a>`protection_loosened` | Gate (g): the proposed repair would show text the privacy boundary hid before it. Nothing was written. | `-` | no | Add the end marker where the fence really ends. Format: [gates](fence-format.md#gates). |A managed source a fence refusal blocked before this release recovers on itsnext sync with no command: the file is held and the rest importsdiff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.mdindex 761a98df5d..2e7d0ad897 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) caps | `fences.repair.max_usd_per_page` / `fences.repair.max_usd_per_day` | `0.05` / `1.00` | per page and per UTC day across every process, through the durable USD ledger (`llm_repair`/`fences`); validated at `config set` and shown with today's spend by `gbrain doctor --only fence_integrity`. No release ships the model repair that spends under them yet | `0` = 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.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 || 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 |@@ -169,6 +169,51 @@ the tracker cannot price — e.g. a local Ollama model selected viawarning (a USD cap cannot be enforced on an unpriced model; local models incurno API spend).+### Fence model repair (Tier 3)++**Say to your agent:** *"How much did fence repair spend today?"* or *"Stop+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.++- **Ledger.** Each call reserves its estimate in the durable daily USD ledger+ before it is sent and settles the measured cost after. Failed and retried+ calls settle against it too, and a call whose usage is unknown is charged+ its reserved maximum. The ledger is per UTC day and shared by every process+ on the brain (the maintenance cycle and the CLI), so concurrent runs never+ exceed 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+ `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+ `budget_exhausted`; `gbrain repair fences --apply` stops with exit 1,+ naming the spend, the cap, the reset time (next 00:00 UTC) and the pages+ waiting. Raising a cap is the user's call.+- **`--max-usd <n>`** on `gbrain repair fences` lowers the cap for that run+ below today's remainder and never raises it; `--no-llm` keeps a run to the+ free tiers. `gbrain doctor --remediate --max-usd <n>` passes what is left of+ its allowance to the fences step.+- **Off switches.** `gbrain config set fences.repair.llm false` stops model+ repair everywhere; those fences wait as `llm_disabled` while the free+ tiers keep running. `gbrain config set fences.repair.enabled false` pauses+ the maintenance phase (an explicit `gbrain repair fences --apply` still+ runs).+- **`spend.posture` is not consulted.** `tokenmax` neither lifts these caps+ nor skips the ledger.+- **Unpriced models.** Under the default caps, a repair model gbrain has no+ price for still runs: each call is metered at an estimated ceiling, the+ highest chat rate in the canonical price table, and the run carries a+ notice naming `gbrain pricing set` to make the metering exact. When the user+ set either cap, it is refused with `no_pricing` and the pricing guidance+ instead ([registering a model price](#registering-a-model-price)), and+ nothing is sent.++`gbrain doctor --only fence_integrity` shows both caps and today's spend.+### Sync inline-embed cost gateFires only when sync embeds **inline** (federated_v2 off, or `--serial` withoutdiff --git a/llms-full.txt b/llms-full.txtindex 99724ef4a3..a1ff0a967c 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1813,10 +1813,14 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contfiles through `put_page`/`capture` or a YAML serializer and check generatedcontent with `gbrain frontmatter validate --stdin --path <p>`. Walkthrough:[held files](docs/guides/repair.md#held-files). A hold with code- `invalid_fence` is a facts or takes table, not frontmatter: read the page- (`gbrain get --source <id> -- <slug>`), edit only the fence the hold names,- commit, then `gbrain sync --source <id> --no-pull`- ([fence holds](docs/guides/write-refusals.md#invalid_fence)).+ `invalid_fence` is a facts or takes table, not frontmatter, and clears+ automatically on the next maintenance run. `gbrain repair fences --source <id>`+ previews the repair and its printed apply command runs it now, with no+ extra consent; a `manual` reason needs the edit the hold names (read the+ page with `gbrain get --source <id> -- <slug>`, edit only that fence,+ commit, `gbrain sync --source <id> --no-pull`). Raising spend+ (`fences.repair.max_usd_per_day`, `fences.repair.llm true`) is the user's+ call ([fence holds](docs/guides/write-refusals.md#invalid_fence)).- **Migrate / upgrade:** `gbrain upgrade` (binary self-update + schema migrations + post-upgrade prompts),[`docs/UPGRADING_DOWNSTREAM_AGENTS.md`](./docs/UPGRADING_DOWNSTREAM_AGENTS.md),[`skills/migrations/`](./skills/migrations/), `gbrain apply-migrations --yes --no-autopilot-install` (manual migration orchestration without service installation).@@ -6491,11 +6495,12 @@ vars — incident-time escape hatches, not everyday knobs.repaired. A hold clears when the file changes, is deleted, or a newergbrain can read it; `gbrain sync --dry-run` lists would-be holds(`would_hold`) without writing anything. The backlog fix is one previewed,- hash-bound command:+ hash-bound command per kind of hold:```bashgbrain sources status <source-id> # what is held and why- gbrain repair frontmatter --source <source-id> # preview; writes nothing+ gbrain repair frontmatter --source <source-id> # frontmatter holds: preview; writes nothing+ gbrain repair fences --source <source-id> # fence holds: preview; writes nothing, no model call```A fence whose meaning is unambiguous (a missing end marker after the@@ -6504,13 +6509,19 @@ vars — incident-time escape hatches, not everyday knobs.reports `fences_normalized` (`gbrain sync --dry-run` lists`would_normalize`; `gbrain config set fences.normalize false` turns it off).A fence hold (`invalid_fence`) names the fence, section, reason and row- numbers, never a cell. Fix it by reading the page- (`gbrain get --source <source-id> -- <slug>`), editing that fence in the- file, committing, and running `gbrain sync --source <source-id> --no-pull`;- frontmatter repair does not touch fences. A fence refused only while being- prepared against the stored page (for example a takes row number a stored- take already uses) is held in the same run as `prepare_time`. See- [fence holds](write-refusals.md#invalid_fence).+ numbers, never a cell, and clears by itself: the maintenance run's+ `fence_repair` phase repairs it on the owner host (exact rules first, then+ the configured chat model for rows only a rewrite can realign, within+ the daily spend cap) and commits the file.+ `gbrain repair fences --source <source-id>` previews the same repair and+ prints its apply command, which needs no extra consent; frontmatter repair+ does not touch fences. A hold whose reason is `manual` needs a person: read+ the page (`gbrain get --source <source-id> -- <slug>`), edit that fence in+ the file, commit, and run `gbrain sync --source <source-id> --no-pull`. A+ fence refused only while being prepared against the stored page (for+ example a takes row number a stored take already uses) is held in the same+ run as `prepare_time`. See [fence holds](write-refusals.md#invalid_fence)+ and [fence repair](repair.md#fences).Walkthrough with real output: [held files](repair.md#held-files); codes:[content refusals](write-refusals.md#held-files-and-content-refusals).@@ -6518,7 +6529,11 @@ vars — incident-time escape hatches, not everyday knobs.holds; for fences, legacy sync stores the normalized fence in the database(it never rewrites the file), keeps importing a page whose fence cannot benormalized with its bad rows skipped (reported in `fence_issues`), and- never holds it. Holds never count toward the+ never holds it. The fence repair still repairs such a file: on a legacy+ source it re-reads the file, backs it up under `~/.gbrain/backups/`,+ writes and imports it, and leaves the change for you to commit+ (`gbrain sources status` names the `git add`/`git commit` command until+ you do). Holds never count toward thelegacy auto-skip streak below. A source blocked by such a file before thisrelease recovers on its next sync, or now with`gbrain sync --source <source-id> --no-pull`. Teams that want fail-closed@@ -10123,7 +10138,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| [Doctor residue (`timeline_history`, `derived_visibility`, `safe_index_pending`)](#doctor-residue) | preview `gbrain doctor --remediation-plan --json` or `gbrain repair`; then `gbrain repair <kind> --apply` | brain host, after the user agrees | `destructive` (rewrites derived rows) | `gbrain doctor --only timeline_history,derived_visibility,safe_index_pending --json` || Low health score | preview `gbrain doctor --remediation-plan --json`; then `gbrain doctor --remediate --yes --target-score 90 --max-usd 5` | agent, after the user agrees | `paid`; `destructive` with `--include-repairs` (approve with `--expect <plan_hash>` from the preview) | `gbrain doctor --json` || [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` |-| [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | `gbrain sources status <id>` names the fence, section, rows and reason; read the page with `gbrain get --source <id> -- <slug>`, edit that fence in the file, commit, then `gbrain sync --source <id> --no-pull` | agent (the user's file; editing the named fence is the requested fix) | none | `gbrain sources status <id> --json` (the hold is gone) |+| [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` || [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` || [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` || [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |@@ -10142,7 +10157,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro<a id="held-files"></a>**Sync held a file (`Held <path>: invalid_frontmatter …`, doctor `git_held_files`, `get_page` shows `file_held`)?** The sync succeeded; only that file waits, and its page (if any) keeps its last good revision and refuses `put_page` until the file is repaired. Run `gbrain sources status <id>`, preview `gbrain repair frontmatter --source <id>`, and after the user agrees run the printed apply. A source a broken file blocked before upgrading recovers on its next sync (`gbrain sync --source <id> --no-pull` does it now). See [held files](repair.md#held-files).-<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell. Read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. A fence with one obvious meaning is never held: sync rewrites it losslessly, commits the file and reports `fences_normalized`; a `fence_normalized` notice on a write means re-read the page before editing it. `gbrain doctor --only fence_integrity` counts every malformed fence still waiting (held, stored or unsynced) by tier. See [fence holds](write-refusals.md#invalid_fence).+<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell, and most holds clear by themselves: the maintenance run's `fence_repair` phase repairs the fence on the owner host and commits the file. To see the plan or do it now, run `gbrain repair fences --source <id>` (a read-only preview with no model call), then the apply command it prints; applying needs no extra consent. Model repair spends only within `fences.repair.max_usd_per_page` and `fences.repair.max_usd_per_day`; raising them, or pausing automatic repair with `gbrain config set fences.repair.enabled false`, is the user's call. A hold whose reason is `manual` needs a person: read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. A fence with one obvious meaning is never held: sync rewrites it losslessly, commits the file and reports `fences_normalized`; a `fence_normalized` notice on a write means re-read the page before editing it. `gbrain doctor --only fence_integrity` counts every malformed fence still waiting (held, stored or unsynced) by tier. See [fence holds](write-refusals.md#invalid_fence), [fence repair](repair.md#fences) and the [fence format](fence-format.md).<a id="held-connector-items"></a>**A Google or GitHub item is held after repeated failures (doctor `connector_held_items`, `gbrain waiting` says coverage is partial)?** Run `gbrain sources status <id>`, fix the cause, then after the user agrees run `gbrain sources retry-held <id>` and `gbrain sync --source <id>`. See [held items](google-connect.md#held-items).@@ -11804,6 +11819,23 @@ step. Per-file outcomes report `written`, `imported`, `hold_cleared` and`committed`. Repair stays explicit-only: `gbrain repair --all` and`gbrain doctor --remediate` never run it.+<a id="fences"></a>+### Fences++`gbrain repair fences` repairs malformed facts and takes fences: files sync+held with `invalid_fence`, stored pages whose fence does not parse, and+checkout files not yet synced. The maintenance run applies the same repair+automatically (phase `fence_repair`), so a fence hold usually clears with no+command. The preview is read-only and makes no model call; applying needs no+extra consent. What each reason means and who acts:+[fence holds](write-refusals.md#invalid_fence); the format and every rule:+[fence format](fence-format.md).++```bash+gbrain repair fences --source <id> # preview: tiers, rows, estimated model cost, apply command+gbrain repair fences --source <id> --apply --expect <hash> # apply exactly the previewed set+```+## ResumeRuns are resumable. After each page commits, the position is saved under thediff --git a/llms.txt b/llms.txtindex 6ce9f2e170..0c96420cda 100644--- a/llms.txt+++ b/llms.txt@@ -65,6 +65,7 @@ Repo: https://github.com/garrytan/gbrain- [docs/guides/minions-fix.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/minions-fix.md): Troubleshooting the Minions job queue.- [docs/guides/repair.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/repair.md): `gbrain repair <kind>`: dry run vs --apply, --source/--limit/--json, resume, capacity stop, thin-client refusal, what each kind fixes and costs; held files walkthrough (sync holds a broken file, `gbrain repair frontmatter` two-pass preview and apply).- [docs/guides/write-refusals.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/write-refusals.md): Refusal reasons (file_database_drift, ambiguous_source_path, physical_root_device_changed, cursor_processing_options_conflict, take_row_collision, invalid_source_uri, queue_capacity, parked effects) and held-file content refusals (invalid_frontmatter and its reasons, frontmatter_slug_conflict, file_too_large, content_rejected, rename_held, sync_parser_regression) with the exact recovery command. Every refusal's `docs` field links its row directly.+- [docs/guides/fence-format.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/fence-format.md): Facts and takes fence format, generated from the parser: markers, columns and layouts, allowed values, holders, row-number rules, one valid example per fence, what gbrain fixes by itself and what it never guesses, and the repair gates.- [docs/integrations/reliability-repair.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/integrations/reliability-repair.md): Data integrity recovery.## Migrationsdiff --git a/plugin-variants/gbrain-coding/skills/_brain-filing-rules.md b/plugin-variants/gbrain-coding/skills/_brain-filing-rules.mdindex 7a324945c6..89b40b0d2a 100644--- a/plugin-variants/gbrain-coding/skills/_brain-filing-rules.md+++ b/plugin-variants/gbrain-coding/skills/_brain-filing-rules.md@@ -198,6 +198,20 @@ examples lives in `docs/takes-vs-facts.md`.Slugs use the standard grammar (`[a-z0-9._-]+`). `Garry`, `people/Garry-Tan`,and `world/garry-tan` all fail validation.+**Write takes with `takes_add`, not by hand.** `takes_add` (and `takes_update`+for an existing row) writes the row for you: it allocates the row number,+accepts only the four kinds (`fact`, `take`, `bet`, `hunch`), and keeps the+fence's markers and header canonical, so the page never needs fence repair.+Give it a canonical holder: `world`, `brain`, `people/<slug>` or+`companies/<slug>`, with a lowercase slug (`people/alice-example`,+`companies/acme-example`). A display name (`Alice Example`), a bare first+name or an assistant label is not a holder: gbrain rewrites assistant labels+(`System`, `assistant`) to `brain`, resolves a name only when it matches+exactly one `people/` or `companies/` page, and otherwise refuses the write+or holds the file for a person to fix. Facts rows go through `remember` the same way. Write a fence+table by hand only when the user asks for one, and then follow the exact+format in `docs/guides/fence-format.md`.+**Founder-describing-own-company rule.** When a founder describes their owncompany, the holder is the FOUNDER, not the company. "We can hit $10M ARR"said by Bo Lu → `holder=people/bo-lu`, NOT `holder=companies/clipboard-health`.diff --git a/plugin-variants/gbrain-daily/skills/_brain-filing-rules.md b/plugin-variants/gbrain-daily/skills/_brain-filing-rules.mdindex 7a324945c6..89b40b0d2a 100644--- a/plugin-variants/gbrain-daily/skills/_brain-filing-rules.md+++ b/plugin-variants/gbrain-daily/skills/_brain-filing-rules.md@@ -198,6 +198,20 @@ examples lives in `docs/takes-vs-facts.md`.Slugs use the standard grammar (`[a-z0-9._-]+`). `Garry`, `people/Garry-Tan`,and `world/garry-tan` all fail validation.+**Write takes with `takes_add`, not by hand.** `takes_add` (and `takes_update`+for an existing row) writes the row for you: it allocates the row number,+accepts only the four kinds (`fact`, `take`, `bet`, `hunch`), and keeps the+fence's markers and header canonical, so the page never needs fence repair.+Give it a canonical holder: `world`, `brain`, `people/<slug>` or+`companies/<slug>`, with a lowercase slug (`people/alice-example`,+`companies/acme-example`). A display name (`Alice Example`), a bare first+name or an assistant label is not a holder: gbrain rewrites assistant labels+(`System`, `assistant`) to `brain`, resolves a name only when it matches+exactly one `people/` or `companies/` page, and otherwise refuses the write+or holds the file for a person to fix. Facts rows go through `remember` the same way. Write a fence+table by hand only when the user asks for one, and then follow the exact+format in `docs/guides/fence-format.md`.+**Founder-describing-own-company rule.** When a founder describes their owncompany, the holder is the FOUNDER, not the company. "We can hit $10M ARR"said by Bo Lu → `holder=people/bo-lu`, NOT `holder=companies/clipboard-health`.diff --git a/plugin/skills/_brain-filing-rules.md b/plugin/skills/_brain-filing-rules.mdindex 7a324945c6..89b40b0d2a 100644--- a/plugin/skills/_brain-filing-rules.md+++ b/plugin/skills/_brain-filing-rules.md@@ -198,6 +198,20 @@ examples lives in `docs/takes-vs-facts.md`.Slugs use the standard grammar (`[a-z0-9._-]+`). `Garry`, `people/Garry-Tan`,and `world/garry-tan` all fail validation.+**Write takes with `takes_add`, not by hand.** `takes_add` (and `takes_update`+for an existing row) writes the row for you: it allocates the row number,+accepts only the four kinds (`fact`, `take`, `bet`, `hunch`), and keeps the+fence's markers and header canonical, so the page never needs fence repair.+Give it a canonical holder: `world`, `brain`, `people/<slug>` or+`companies/<slug>`, with a lowercase slug (`people/alice-example`,+`companies/acme-example`). A display name (`Alice Example`), a bare first+name or an assistant label is not a holder: gbrain rewrites assistant labels+(`System`, `assistant`) to `brain`, resolves a name only when it matches+exactly one `people/` or `companies/` page, and otherwise refuses the write+or holds the file for a person to fix. Facts rows go through `remember` the same way. Write a fence+table by hand only when the user asks for one, and then follow the exact+format in `docs/guides/fence-format.md`.+**Founder-describing-own-company rule.** When a founder describes their owncompany, the holder is the FOUNDER, not the company. "We can hit $10M ARR"said by Bo Lu → `holder=people/bo-lu`, NOT `holder=companies/clipboard-health`.diff --git a/scripts/build-fence-format.ts b/scripts/build-fence-format.tsnew file mode 100644index 0000000000..b30f5225e9--- /dev/null+++ b/scripts/build-fence-format.ts@@ -0,0 +1,328 @@+#!/usr/bin/env bun+/**+ * Generated region of docs/guides/fence-format.md (#6188, D23): the facts and+ * takes fence format, rendered from the parser and repair constants so the+ * reference cannot drift from what gbrain accepts and rewrites.+ *+ * bun run scripts/build-fence-format.ts rewrite the region+ * bun run scripts/build-fence-format.ts --check exit 1 when the committed region is stale+ *+ * Sources: markers (facts-fence.ts, takes-fence.ts), columns, layouts, value+ * vocabularies, header aliases and Tier 1 synonym tables+ * (fence-repair/schema.ts), the holder grammar (`isValidHolder`), the reason+ * table (fence-repair/reasons.ts) and the gate letters. Both examples are+ * parsed with the strict parsers here; a render fails when either draws a+ * warning. Drift test: test/fence-format-reference.test.ts.+ */+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, isValidHolder, parseTakesFence } from '../src/core/takes-fence.ts';+import {+ ALLOWED, BASE_WIDTH, BRAIN_ALIASES, CANONICAL_HEADER, COLUMN_DEFAULTS, COLUMNS, FACT_KIND_SYNONYMS, FACTS_COLUMNS,+ HEADER_ALIASES, MIN_CELLS, NAMED_COLUMNS, NOTABILITY_SYNONYMS, PRIVATE_SYNONYMS, TAKE_KIND_SYNONYMS, TAKES_COLUMNS,+ TOLERATED_TRAILING, appendOriginalKind, confidenceFormat, holderAlias,+} from '../src/core/fence-repair/schema.ts';+import { FENCE_REASON_CODES, FENCE_REASONS, GATE_REASONS } from '../src/core/fence-repair/reasons.ts';+import type { FenceKind, FenceTier, FixClass, GateLetter } from '../src/core/fence-repair/types.ts';++export const FENCE_FORMAT_PATH = join(import.meta.dir, '..', 'docs', 'guides', 'fence-format.md');+const BEGIN = /<!-- BEGIN GENERATED fence-format[^>]*-->\n/;+const BEGIN_LINE = '<!-- BEGIN GENERATED fence-format (bun run scripts/build-fence-format.ts; drift test: test/fence-format-reference.test.ts) -->\n';+const END = '<!-- END GENERATED fence-format -->';+const REFUSALS = 'write-refusals.md';++const code = (text: string) => `\`${text}\``;+const codes = (values: Iterable<string>) => [...values].map(code).join(', ');++const FACTS_TEXT: Record<(typeof FACTS_COLUMNS)[number], string> = {+ '#': 'Row number.',+ claim: 'The statement, free text. `~~claim~~` marks a row that is no longer active.',+ kind: 'What the claim is.',+ confidence: 'How sure the brain is.',+ visibility: 'Who may read the row.',+ notability: 'How much it matters.',+ valid_from: 'When it became true (`YYYY-MM-DD`), or empty.',+ valid_until: 'When it stopped being true, or empty.',+ source: 'Where it came from, free text.',+ context: 'Free text. `superseded by #N` names the row that replaced a struck row; `forgotten: ...` marks a row withdrawn with `forget`.',+ claim_metric: 'Metric of a typed claim (`mrr`, `team_size`, ...), or empty.',+ claim_value: 'Value of a typed claim.',+ claim_unit: 'Unit (`USD`, `people`, ...), or empty.',+ claim_period: 'Period (`monthly`, `annual`, ...), or empty.',+};++const TAKES_TEXT: Record<(typeof TAKES_COLUMNS)[number], string> = {+ '#': 'Row number.',+ claim: 'The position, free text. `~~claim~~` marks a row that is no longer active.',+ kind: 'What the take is.',+ who: 'Who holds the position (see [holders](#holders)): who said or clearly implied it, not who it is about.',+ weight: 'How strongly it is held; stored on the 0.05 grid. There is no default.',+ since: 'When the holder took the position (`YYYY-MM-DD` or `YYYY-MM`; `start → end` for a range).',+ source: 'Where it came from. `superseded by #N` names the row that replaced a struck row.',+ resolved: 'When the take was resolved.',+ quality: 'How the take turned out.',+ evidence: 'What resolved it.',+ value: 'Resolved value.',+ unit: 'Unit of the resolved value.',+ by: 'Who resolved it.',+};++const COLUMN_TEXT: Record<FenceKind, Readonly<Record<string, string>>> = { facts: FACTS_TEXT, takes: TAKES_TEXT };++const GATE_TEXT = {+ a: 'The result parses with no warning: no repeated marker, unique row numbers.',+ b: 'Every claim cell is unchanged (struck claims included).',+ c: 'Every row number that was valid and unique still names the same claim.',+ d: 'No row becomes more visible: `private` never turns `world`.',+ e: 'No row is added or dropped, and every row of the fence stays inside it.',+ f: 'A cell valid in its column keeps its text; a misaligned cell may only move, and text changes only through a named rule.',+ g: 'Text the privacy boundary hid before the repair stays hidden after it.',+} satisfies Record<GateLetter, string>;++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',+ manual: 'a person edits the fence; gbrain never guesses',+};++/** Synthetic examples; both must parse with zero warnings. */+const FACTS_EXAMPLE = [+ FACTS_FENCE_BEGIN,+ CANONICAL_HEADER.facts.narrow,+ CANONICAL_HEADER.facts.narrowSep,+ '| 1 | Acme Example plans to open its widget API in 2026 | event | 0.9 | private | high | 2026-03-01 | | meetings/2026-04-03 | |',+ '| 2 | ~~Acme Example has 12 engineers~~ | fact | 1.0 | private | medium | 2025-06-01 | 2026-01-15 | companies/acme-example | superseded by #3 |',+ '| 3 | Acme Example has 18 engineers | fact | 1.0 | private | medium | 2026-01-15 | | companies/acme-example | |',+ FACTS_FENCE_END,+].join('\n');++const TAKES_EXAMPLE = [+ TAKES_FENCE_BEGIN,+ CANONICAL_HEADER.takes.narrow,+ CANONICAL_HEADER.takes.narrowSep,+ '| 1 | Acme Example reaches profitability in 2027 | bet | people/alice-example | 0.65 | 2026-04 | meetings/2026-04-03 |',+ '| 2 | Widget pricing drives most churn | take | brain | 0.55 | 2026-04 | |',+ '| 3 | Acme Example sells developer tools | fact | world | 1.0 | 2026-01 | companies/acme-example |',+ TAKES_FENCE_END,+].join('\n');++const HOLDER_PROBES = [+ 'world', 'brain', 'people/alice-example', 'companies/acme-example', 'alice-example',+ 'System', 'Alice Example', 'people/Alice-Example', 'world/alice-example', 'users/alice-example',+];++function checkExamples(): void {+ const facts = parseFactsFence(FACTS_EXAMPLE);+ const takes = parseTakesFence(TAKES_EXAMPLE);+ if (facts.warnings.length || facts.facts.length !== 3) throw new Error(`facts example no longer parses clean: ${facts.warnings.length} warning(s), ${facts.facts.length} row(s)`);+ if (takes.warnings.length || takes.takes.length !== 3) throw new Error(`takes example no longer parses clean: ${takes.warnings.length} warning(s), ${takes.takes.length} row(s)`);+}++function columnTable(kind: FenceKind): string {+ const rows = COLUMNS[kind].map((column, i) => {+ const allowed = ALLOWED[kind][column];+ const values = !allowed ? 'free text' : allowed.every(value => !/\s/.test(value)) ? codes(allowed) : allowed.join('; ');+ const notes = [COLUMN_TEXT[kind][column]];+ if (NAMED_COLUMNS[kind].has(column)) notes.push('Read by header name.');+ const fallback = COLUMN_DEFAULTS[kind][column];+ return `| ${i + 1} | ${code(column)} | ${values} | ${TOLERATED_TRAILING[kind].has(column) ? 'yes' : 'no'} | ${fallback ? code(fallback) : '-'} | ${notes.join(' ')} |`;+ });+ return ['| Position | Column | Values | May be left off the row end | Default when the header lacks it | Meaning |', '| --- | --- | --- | --- | --- | --- |', ...rows].join('\n');+}++function layouts(kind: FenceKind): string {+ const all = COLUMNS[kind];+ const dropped = all.slice(MIN_CELLS[kind], BASE_WIDTH[kind]);+ const wide = all.slice(BASE_WIDTH[kind]);+ return [+ `- **Narrow, ${BASE_WIDTH[kind]} cells** (what gbrain writes unless a row needs a wide column):`,+ '',+ ' ```text',+ ` ${CANONICAL_HEADER[kind].narrow}`,+ ` ${CANONICAL_HEADER[kind].narrowSep}`,+ ' ```',+ '',+ `- **Wide, ${all.length} cells** (adds ${codes(wide)}):`,+ '',+ ' ```text',+ ` ${CANONICAL_HEADER[kind].wide}`,+ ` ${CANONICAL_HEADER[kind].wideSep}`,+ ' ```',+ '',+ `- **Shortest row, ${MIN_CELLS[kind]} cells:** the narrow row without ${codes(dropped)}. A row that is short anywhere else is \`short_row\`.`,+ ].join('\n');+}++function headerSpellings(kind: FenceKind): string {+ const rows = Object.entries(HEADER_ALIASES[kind])+ .map(([column, aliases]) => [column, aliases.filter(alias => alias !== column)] as const)+ .filter(([, aliases]) => aliases.length)+ .map(([column, aliases]) => `| ${code(column)} | ${codes(aliases)} |`);+ return [`| ${kind} column | Also accepted in a header |`, '| --- | --- |', ...rows].join('\n');+}++function holderTable(): string {+ const rows = HOLDER_PROBES.map(holder => {+ const valid = isValidHolder(holder);+ const alias = holderAlias(holder);+ const legacy = valid && !/^(world|brain|people\/|companies\/)/.test(holder);+ const outcome = valid+ ? (legacy ? 'Accepted (an older bare-slug form); write `people/<slug>` or `companies/<slug>` instead.' : 'Accepted.')+ : alias ? `Rewritten to ${code(alias)} (\`holder_alias\`).` : 'Not a holder: `holder_unresolved`. Tier 2 resolves it only to one verified page; otherwise a person fixes it.';+ return `| ${code(holder)} | ${valid ? 'yes' : 'no'} | ${outcome} |`;+ });+ return ['| Written | Valid | What gbrain does |', '| --- | --- | --- |', ...rows].join('\n');+}++function synonymLines(table: Readonly<Record<string, string>>): string {+ const byTarget = new Map<string, string[]>();+ for (const [word, target] of Object.entries(table)) byTarget.set(target, [...(byTarget.get(target) ?? []), word]);+ return [...byTarget].map(([target, words]) => `${codes(words)} → ${code(target)}`).join('; ');+}++/** One row per fix class; the type binding fails typecheck when a class is added or removed. */+function normalizedTable(): string {+ const brainWords = [...BRAIN_ALIASES].filter(word => word !== 'brain');+ 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.',+ 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.`,+ 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`.',+ } satisfies Record<FixClass, string>;+ const rows = Object.entries(text).map(([cls, what]) => `| ${code(cls)} | ${what} |`);+ return ['| Class | What it rewrites |', '| --- | --- |', ...rows].join('\n');+}++function reasonsByTier(): string {+ const screen = FENCE_REASON_CODES.filter(reason => FENCE_REASONS[reason].stage === 'screen');+ return (['llm', 'resolver', 'manual'] as const).map(tier => {+ const reasons = screen.filter(reason => FENCE_REASONS[reason].tier === tier);+ return `- **${tier}** (${TIER_TEXT[tier]}): ${reasons.map(r => `[${code(r)}](${REFUSALS}#fence-${r})`).join(', ')}.`;+ }).join('\n');+}++function gateTable(): string {+ const rows = (Object.keys(GATE_REASONS) as GateLetter[]).map(letter => `| (${letter}) | [${code(GATE_REASONS[letter])}](${REFUSALS}#fence-${GATE_REASONS[letter]}) | ${GATE_TEXT[letter]} |`);+ return ['| Gate | Reason when it fails | What must hold |', '| --- | --- | --- |', ...rows].join('\n');+}++/** The generated region's body. */+export function renderFenceFormatRegion(): string {+ checkExamples();+ return [+ '<a id="markers"></a>',+ '## Markers',+ '',+ `A facts fence sits between ${code(FACTS_FENCE_BEGIN)} and ${code(FACTS_FENCE_END)}; a takes fence between ${code(TAKES_FENCE_BEGIN)} and ${code(TAKES_FENCE_END)} (three dashes after \`<!\`). The body and the timeline section of a page each hold at most one fence of each kind. A marker inside a code block or an inline code span is an example, not a fence. Inside the fence the first table line is the header, which names \`claim\` and \`kind\`, then a separator line, then one line per row. A \`|\` inside a cell is written \`\\|\`.`,+ '',+ '<a id="facts-columns"></a>',+ '## Facts columns',+ '',+ 'Facts cells are read by position.',+ '',+ columnTable('facts'),+ '',+ '<a id="facts-layouts"></a>',+ layouts('facts'),+ '',+ '<a id="takes-columns"></a>',+ '## Takes columns',+ '',+ `Takes cells are read by position, except ${codes(NAMED_COLUMNS.takes)}, which are read by header name.`,+ '',+ columnTable('takes'),+ '',+ '<a id="takes-layouts"></a>',+ layouts('takes'),+ '',+ '<a id="holders"></a>',+ '## Holders',+ '',+ `A takes \`who\` cell is one of ${codes(ALLOWED.takes.who!)}. Slugs are lowercase.`,+ '',+ holderTable(),+ '',+ '<a id="row-numbers"></a>',+ '## Row numbers',+ '',+ `- \`#\` is ${ALLOWED.facts['#']![0]}, unique per fence kind across the whole page: the body and the timeline count together.`,+ '- A struck row keeps its number, and `superseded by #N` must name a row on the page.',+ '- gbrain renumbers a row whose number is zero, negative, not a number or a duplicate. When two rows share a number, the row that matches the stored row keeps it. A new number is one above every number on the page (live and struck, both sections) and every stored row number of the page, so a freed number is not reused. A number whose only trace was deleted before this release is not known and could be reused.',+ '- gbrain does not renumber a duplicate that a `superseded by #N` reference names (`superseded_ambiguous`), or rows hidden from a remote caller.',+ '',+ '<a id="examples"></a>',+ '## Examples',+ '',+ 'A valid facts fence (narrow layout; row 2 was superseded by row 3):',+ '',+ '```markdown',+ FACTS_EXAMPLE,+ '```',+ '',+ 'A valid takes fence (narrow layout):',+ '',+ '```markdown',+ TAKES_EXAMPLE,+ '```',+ '',+ '<a id="normalized"></a>',+ '## What gbrain fixes by itself',+ '',+ 'These rules run on every write path for free. They edit or move cell text and never re-render a table. A fence they fix completely is written back in fixed form; each fix is reported by its class, row and column.',+ '',+ normalizedTable(),+ '',+ '<a id="header-spellings"></a>',+ '### Header spellings',+ '',+ 'Header cells are compared case-insensitively, with spaces, `_` and `-` treated alike. A column not listed accepts only its own name.',+ '',+ headerSpellings('facts'),+ '',+ headerSpellings('takes'),+ '',+ '<a id="never-guessed"></a>',+ '## What gbrain never guesses',+ '',+ 'A problem the rules above cannot fix exactly is held or refused with a reason. The reason says which tier clears it:',+ '',+ reasonsByTier(),+ '',+ '<a id="gates"></a>',+ '### Gates every repair passes',+ '',+ 'No tier writes a fence until all of these hold, and the result is one the rules above would leave unchanged. A Tier 3 proposal that fails one stays held with the gate and rows named.',+ '',+ gateTable(),+ ].join('\n');+}++/** The document with its generated region replaced by a fresh render. */+export function renderFenceFormatDoc(current: string): string {+ const begin = BEGIN.exec(current);+ const endAt = current.indexOf(END);+ if (!begin || endAt < begin.index) throw new Error(`${FENCE_FORMAT_PATH}: generated region markers are missing`);+ return `${current.slice(0, begin.index)}${BEGIN_LINE}${renderFenceFormatRegion()}\n${current.slice(endAt)}`;+}++if (import.meta.main) {+ const current = readFileSync(FENCE_FORMAT_PATH, 'utf8');+ const fresh = renderFenceFormatDoc(current);+ if (process.argv.includes('--check')) {+ if (fresh !== current) {+ console.error('docs/guides/fence-format.md is stale. Run: bun run scripts/build-fence-format.ts');+ process.exit(1);+ }+ console.log('fence-format.md: up to date');+ } else {+ writeFileSync(FENCE_FORMAT_PATH, fresh);+ console.log(`wrote ${FENCE_FORMAT_PATH}`);+ }+}diff --git a/scripts/llms-config.ts b/scripts/llms-config.tsindex 6bb7113156..a1d093d386 100644--- a/scripts/llms-config.ts+++ b/scripts/llms-config.ts@@ -312,6 +312,13 @@ export const SECTIONS: DocSection[] = [path: "docs/guides/write-refusals.md",includeInFull: false,},+ {+ title: "docs/guides/fence-format.md",+ description:+ "Facts and takes fence format, generated from the parser: markers, columns and layouts, allowed values, holders, row-number rules, one valid example per fence, what gbrain fixes by itself and what it never guesses, and the repair gates.",+ path: "docs/guides/fence-format.md",+ includeInFull: false,+ },{title: "docs/integrations/reliability-repair.md",description: "Data integrity recovery.",diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 10d5f5691b..0df32a9fb1 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -158,6 +158,8 @@ test/facts-backstop-remedy-verb.test.ts facts backstop thin-client-fallback remetest/facts-relink.test.ts relink reasons 1 readFileSynctest/features.test.ts CLI routing 2 source-surface-helpertest/fence-extraction.test.ts Layer 8 D2 — markdown fence extraction 18 readFileSync+test/fence-format-reference.test.ts docs/guides/fence-format.md 3 readFileSync+test/fence-format-reference.test.ts write-refusals fence reason rows 3 readFileSynctest/fence-refusal.test.ts no PR1 message or fix names a command that has not shipped 3 readFileSynctest/files.test.ts collectFiles (production import) 9 readFileSynctest/files.test.ts files upload-raw git-storage branch (#2297) 6 readFileSyncdiff --git a/skills/_brain-filing-rules.md b/skills/_brain-filing-rules.mdindex 7a324945c6..89b40b0d2a 100644--- a/skills/_brain-filing-rules.md+++ b/skills/_brain-filing-rules.md@@ -198,6 +198,20 @@ examples lives in `docs/takes-vs-facts.md`.Slugs use the standard grammar (`[a-z0-9._-]+`). `Garry`, `people/Garry-Tan`,and `world/garry-tan` all fail validation.+**Write takes with `takes_add`, not by hand.** `takes_add` (and `takes_update`+for an existing row) writes the row for you: it allocates the row number,+accepts only the four kinds (`fact`, `take`, `bet`, `hunch`), and keeps the+fence's markers and header canonical, so the page never needs fence repair.+Give it a canonical holder: `world`, `brain`, `people/<slug>` or+`companies/<slug>`, with a lowercase slug (`people/alice-example`,+`companies/acme-example`). A display name (`Alice Example`), a bare first+name or an assistant label is not a holder: gbrain rewrites assistant labels+(`System`, `assistant`) to `brain`, resolves a name only when it matches+exactly one `people/` or `companies/` page, and otherwise refuses the write+or holds the file for a person to fix. Facts rows go through `remember` the same way. Write a fence+table by hand only when the user asks for one, and then follow the exact+format in `docs/guides/fence-format.md`.+**Founder-describing-own-company rule.** When a founder describes their owncompany, the holder is the FOUNDER, not the company. "We can hit $10M ARR"said by Bo Lu → `holder=people/bo-lu`, NOT `holder=companies/clipboard-health`.diff --git a/skills/migrations/v0.60.84.0.md b/skills/migrations/v0.60.84.0.mdnew file mode 100644index 0000000000..32de0402e5--- /dev/null+++ b/skills/migrations/v0.60.84.0.md@@ -0,0 +1,122 @@+# Upgrade to v0.60.84.0: malformed facts and takes fences repair themselves++A facts or takes fence gbrain cannot import no longer blocks a sync. A fence+with one exact meaning is rewritten and committed in the same write; the rest+is **held** while the source keeps syncing, and the maintenance run now+repairs held files and stored pages by itself. A source such a fence blocked+before this release recovers by itself. No schema migration.++The repairs need no extra consent, but they rewrite the user's files: tell the+user what the first maintenance run will change (step 3) before it runs, and+leave spend decisions to them (step 4).++1. **Finish the upgrade.** `gbrain upgrade` runs it. To be sure, on the brain+ host:+ ```bash+ gbrain apply-migrations --yes --no-autopilot-install+ ```+ No schema migration and no rows are rewritten by the upgrade itself.+ Restart every `gbrain serve`, autopilot and worker so the maintenance run+ picks up the `fence_repair` phase.++2. **Unblock a source a fence blocked.** `gbrain post-upgrade` names each+ source a fence refusal blocked. The next scheduled or manual sync recovers+ it automatically; to do it now run:+ ```bash+ gbrain sync --source <id> --no-pull+ ```+ The blocked request is converted in place: the file is held and everything+ else imports. No `--retry-failed` and no ledger edits.++3. **Tell the user what the first maintenance run rewrites.** The first+ maintenance run after the upgrade repairs every malformed fence it finds+ across each source (held files, stored pages and checkout files not yet+ synced), rewriting those files and committing each one (a legacy source's+ files are backed up and left for the user to commit). Show the user the+ count and the plan first:+ ```bash+ gbrain doctor --only fence_integrity # malformed fences per source, by the tier that fixes them+ gbrain repair fences --source <id> # preview: read-only, no model call+ ```+ If the user wants to review before anything is rewritten, pause the+ automatic repair first:+ ```bash+ gbrain config set fences.repair.enabled false+ ```+ Then apply what they approve with the preview's printed+ `gbrain repair fences --source <id> --apply --expect <hash>` (select files+ with `--only` / `--skip`, stored pages with `--slug`), and resume with+ `gbrain config set fences.repair.enabled true`. Syncs and writes keep+ rewriting fixable fences inline either way; `gbrain config set fences.normalize false`+ makes them hold such a fence instead.++4. **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+ gbrain knows); under a cap the user set it waits until its price is+ registered with `gbrain pricing set`. Every proposed rewrite passes the+ validation gates before it is written. To keep fence rows away from the+ model:+ ```bash+ gbrain config set fences.repair.llm false+ ```+ The free tiers keep running. Raising a cap or turning model repair back on+ is the user's call.++5. **Tell the user what stays held.**+ ```bash+ 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+ the 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:+ `docs/guides/write-refusals.md#invalid_fence`; the format:+ `docs/guides/fence-format.md`.++6. **Inspect or undo a repair.**+ - Managed sources: each repaired file is committed with the subject+ `gbrain: repair fence in <path> (<classes>)`. `git log --grep 'repair fence in'`+ lists them, `git show <commit>` shows the change, and `git revert <commit>`+ undoes it (for one file of a commit that lists several,+ `git checkout <commit>^ -- <path>` and commit).+ - Database-only pages: `gbrain history <slug>` shows every version,+ including the one before the repair, and `gbrain revert <slug> <version_id>`+ restores it. A managed brain refuses a version whose fence it cannot+ import; then read the old rows from the history and write them again+ with `remember` or `takes_add`.+ - Legacy (unmanaged) sources: the original file is backed up under+ `~/.gbrain/backups/` (the repair output names the path); copy it back and+ sync.++ Turning the settings off stops future repairs and does not undo past ones.+ A restored malformed fence is held again on the next sync and repaired+ again by the next maintenance run, so pause first+ (`gbrain config set fences.repair.enabled false`) if the user wants to keep+ the original.++7. **Which steps need the user.**+ - Nothing to approve for the repairs themselves: the maintenance run and+ `gbrain repair fences --apply` need no extra consent.+ - Tell the user before the first maintenance run (step 3); pausing is+ 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+ every `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).++8. **Verify:**+ ```bash+ gbrain doctor --only fence_integrity,git_held_files --json+ gbrain sources status --json+ ```+ `fence_integrity` is `ok` when no malformed fence is left; it never reports+ `ok` while a scan is partial.diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 5a193cb30f..3588627814 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -2,7 +2,7 @@"RESOLVER.md": "e110522e362dfad7e5d025c148c99850ecffbb684a830da9df9c7b5a3f86b9c6","_AGENT_README.md": "ab51e36e9a0b53f4d0609294b0556444399147834932d9c1acfdc7aa367c70b8","_brain-filing-rules.json": "4e6ecee2d94867d146583d60bf98dccdd9205bb70793af56fe1397a2b258ae0d",- "_brain-filing-rules.md": "b8f6844fd7ab6fbe4a4e7a95e7089466b37d63127730040c766927f55b1ad138",+ "_brain-filing-rules.md": "5a5792a290e7f48e0123744e3460ea02514d7a514113827a9dde462935565d17","_friction-protocol.md": "51353207240142024ff1facc25f225712275ecdb4a034ffffdd83740c8d328e3","_output-rules.md": "0722ec2ecea7f9fa2f065cf12dfe1347956a9709d29898bf9fe95e875c64b800","academic-verify/SKILL.md": "d8a395ed8df706c6da888f81f518c2fd6607f78c2bc66134b9bc40530fdb08b5",@@ -175,6 +175,7 @@"migrations/v0.60.63.0.md": "cdc9f862a719bdb76140b5069fb659987978bc2d90498d808bc5d766dbf16891","migrations/v0.60.74.0.md": "cfd0e9fe6e7d506d60b3673cdb077b52ce292c12e74a81e8cb71c407cc926009","migrations/v0.60.77.0.md": "3a588974cea1db36a9f063ed056fae155adc5cb54fb606d49f69625e94e15c9d",+ "migrations/v0.60.84.0.md": "842169f5bbcfe9f3e6edc7a0adb72a7b33bf332547ec2a5d680e9690d11969ef","migrations/v0.60.98.0.md": "006598c5fc107e1a61510a54e029059183d4f4c0879c2c86640a2988f0b2d33c","migrations/v0.60.99.0.md": "f56aeec78556eed9cc789ba5cca12c0953c1888368fee0b462cb72581dd8c5a8","migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex d251bd5899..861460bd07 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -220,6 +220,9 @@ 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) => {@@ -258,6 +261,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; nothing spends under them yet.' },+ { since: '0.60.84.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.` },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/fence-repair/schema.ts b/src/core/fence-repair/schema.tsindex 2f755dc34d..a914077f69 100644--- a/src/core/fence-repair/schema.ts+++ b/src/core/fence-repair/schema.ts@@ -59,7 +59,8 @@ export const CANONICAL_HEADER: Record<FenceKind, { narrow: string; wide: string;};const ROW_NUM_ALIASES = ['#', 'row', 'row #', 'row num', 'row number', 'no', 'no.', 'num'];-const HEADER_ALIASES: Record<FenceKind, Readonly<Record<string, readonly string[]>>> = {+/** Header spellings each canonical column accepts (`header_alias`), before `lookupKey` folding. */+export const HEADER_ALIASES: Record<FenceKind, Readonly<Record<string, readonly string[]>>> = {facts: {'#': ROW_NUM_ALIASES,claim: ['claim', 'fact', 'statement'],@@ -171,22 +172,27 @@ function confidenceValid(text: string): boolean {return Number.isFinite(n) && n >= 0 && n <= 1;}-const FACT_KIND_SYNONYMS: Readonly<Record<string, string>> = {+/** `kind_map` for facts: written word to kind (any other word maps to `fact`). */+export const FACT_KIND_SYNONYMS: Readonly<Record<string, string>> = {proposal: 'idea', suggestion: 'idea', hypothesis: 'idea',opinion: 'belief', view: 'belief', insight: 'belief', assessment: 'belief', frame: 'belief',promise: 'commitment', pledge: 'commitment',meeting: 'event', launch: 'event', announcement: 'event', milestone: 'event',};-const TAKE_KIND_SYNONYMS: Readonly<Record<string, string>> = {+/** `kind_map` for takes: the only words mapped; any other word is `takes_kind_unsupported`. */+export const TAKE_KIND_SYNONYMS: Readonly<Record<string, string>> = {assessment: 'take', recommendation: 'take', 'strategic position': 'take', opinion: 'take', view: 'take',prediction: 'bet', forecast: 'bet',guess: 'hunch', intuition: 'hunch',};-const PRIVATE_SYNONYMS: ReadonlySet<string> = new Set(['internal', 'team', 'confidential', 'restricted', 'secret', 'shared']);-const NOTABILITY_SYNONYMS: Readonly<Record<string, string>> = {+/** `enum_synonym`: visibility words read as `private`. */+export const PRIVATE_SYNONYMS: ReadonlySet<string> = new Set(['internal', 'team', 'confidential', 'restricted', 'secret', 'shared']);+/** `enum_synonym`: notability words mapped to a canonical level. */+export const NOTABILITY_SYNONYMS: Readonly<Record<string, string>> = {critical: 'high', 'very high': 'high', highest: 'high', 'very low': 'low', minor: 'low',};-const BRAIN_ALIASES: ReadonlySet<string> = new Set(['system', 'assistant', 'ai', 'agent', 'gbrain', 'model', 'brain']);+/** `holder_alias`: holder words read as `brain`. */+export const BRAIN_ALIASES: ReadonlySet<string> = new Set(['system', 'assistant', 'ai', 'agent', 'gbrain', 'model', 'brain']);/** `kind_map` for facts: any word maps (unknown words to `fact`). */export function factsKindMap(word: string): string {diff --git a/test/behavior-change-notice.test.ts b/test/behavior-change-notice.test.tsindex 407166cb31..523a5f7369 100644--- a/test/behavior-change-notice.test.ts+++ b/test/behavior-change-notice.test.ts@@ -9,7 +9,10 @@* written still delivers (once per process); concurrent processes deliver it* once; the chain section appears only when a chain is set, and the HTTP view* never names entries or providers; failed tool responses carry it; doctor- * reads it without recording anything.+ * reads it without recording anything. The #6188 fence rows (inline+ * normalization, automatic repair) reach an upgraded brain with their opt-out+ * commands, the first-run sweep disclosure and undo guidance, and never a+ * fresh install.* Fails when: eligibility, marker identity, the HTTP per-client store, the* remote redaction or dispatch delivery regress.* Seams: per-test GBRAIN_HOME; `__resetBehaviorNoticeForTests` stands in for a@@ -429,3 +432,39 @@ describe('upgrades across releases (each step a new process pinned to a gbrain Vexpect(readFileSync(join(noticeDir(home), 'new.baseline'), 'utf8').trim()).toBe(NEWEST);}, 60_000);});++describe('fence rows (#6188 D25, D26)', () => {+ const NORMALIZE = 'Fixable facts and takes fences are now rewritten instead of held or refused';+ const REPAIR = 'Malformed facts and takes fences are now repaired automatically';+ const fenceRows = BEHAVIOR_CHANGES.filter(c => typeof c.text === 'string' && (c.text.startsWith(NORMALIZE) || c.text.startsWith(REPAIR)));+ const earliest = fenceRows.map(c => c.since).sort(compareReleases)[0]!;+ const before = BEHAVIOR_CHANGES.map(c => c.since).filter(v => compareReleases(v, earliest) < 0).sort(compareReleases).at(-1)!;+ const freshEngine = (createdAt: string) => ({ executeRaw: async () => [{ at: createdAt }], getConfig: async () => null }) as unknown as BrainEngine;++ test('an upgraded brain sees the never-block row and the automatic repair row, each with its opt-out, the sweep disclosure and undo guidance', async () => {+ expect(fenceRows.length).toBe(2);+ const home = freshHome();+ mkdirSync(noticeDir(home), { recursive: true });+ writeFileSync(join(noticeDir(home), 'upgraded.baseline'), `${before}\n`);+ __resetBehaviorNoticeForTests();+ await withEnv({ GBRAIN_HOME: home, ...NO_CHAIN }, async () => {+ const why = (await takeLocalBehaviorNotice(freshEngine(new Date().toISOString()), 'cli', { cfg: null, brainKey: 'upgraded' }))?.why ?? '';+ expect(why).toContain(NORMALIZE);+ expect(why).toContain(REPAIR);+ for (const command of ['gbrain config set fences.normalize false', 'gbrain config set fences.repair.llm false', 'gbrain config set fences.repair.enabled false']) {+ expect(why).toContain(command);+ }+ expect(why).toContain('its first run after upgrading repairs every malformed fence it finds in each source, rewriting and committing those files');+ expect(why).toContain('gbrain doctor --only fence_integrity');+ expect(why).toContain('`git revert` undoes it');+ expect(why).toContain('turning these settings off stops future repairs and does not undo past ones');+ });+ });++ test('a fresh install sees neither row', async () => {+ __resetBehaviorNoticeForTests();+ await withEnv({ GBRAIN_HOME: freshHome(), ...NO_CHAIN }, async () => {+ expect(await takeLocalBehaviorNotice(freshEngine(new Date().toISOString()), 'cli', { cfg: null, brainKey: 'fresh-fences' })).toBeNull();+ });+ });+});diff --git a/test/fence-docs-config-commands.test.ts b/test/fence-docs-config-commands.test.tsnew file mode 100644index 0000000000..e7e3ff9836--- /dev/null+++ b/test/fence-docs-config-commands.test.ts@@ -0,0 +1,62 @@+/**+ * Printed fence settings commands are real (#6188 D29).+ *+ * Protects: every `gbrain config set fences.* <value>` command that the fence+ * docs, the v0.60.84.0 migration note, the behavior-change rows and the fence+ * reason fixes print names a registered key with a value `config set`+ * accepts, and the three opt-outs (`fences.normalize`, `fences.repair.enabled`,+ * `fences.repair.llm` set false) are printed where an agent upgrading a brain+ * reads them.+ * Fails when: a doc or notice prints a misspelled or unregistered key, a value+ * `config set` refuses, or drops an opt-out the user is promised.+ * Why new: the config test checks the validator; nothing checked that the+ * commands the docs and notices print pass it.+ * Seams: none; reads the committed docs and the in-code texts.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';+import { BEHAVIOR_CHANGES } from '../src/core/behavior-change-notice.ts';+import { FENCE_CONFIG_KEYS, validateFenceConfigValue } from '../src/core/fence-repair/config.ts';+import { FENCE_REASON_CODES, FENCE_REASONS } from '../src/core/fence-repair/reasons.ts';++const ROOT = join(import.meta.dir, '..');+const MIGRATION_NOTE = 'skills/migrations/v0.60.84.0.md';+const DOCS = [+ 'AGENTS.md', MIGRATION_NOTE, 'docs/guides/fence-format.md', 'docs/guides/write-refusals.md', 'docs/guides/live-sync.md',+ 'docs/guides/troubleshooting.md', 'docs/guides/repair.md', 'docs/operations/spend-controls.md',+];+const OPT_OUTS = ['gbrain config set fences.normalize false', 'gbrain config set fences.repair.enabled false', 'gbrain config set fences.repair.llm false'];+const COMMAND = /gbrain config set (fences\.[A-Za-z_.]*[A-Za-z_])\s+([^\s`'")]+)/g;+/** A placeholder value (`<usd>`, `<n>`) stands for a number the user picks. */+const sample = (value: string) => (/^<[a-z_]+>$/.test(value) ? '2' : value);++const docTexts = Object.fromEntries(DOCS.map(path => [path, readFileSync(join(ROOT, path), 'utf8')]));+const notices = BEHAVIOR_CHANGES.flatMap(c => (typeof c.text === 'string' ? [c.text] : []));+const fixes = FENCE_REASON_CODES.map(reason => FENCE_REASONS[reason].fix);++function commands(text: string): Array<{ key: string; value: string }> {+ return [...text.matchAll(COMMAND)].map(m => ({ key: m[1]!, value: m[2]! }));+}++describe('printed fence config commands', () => {+ const printed = [...Object.values(docTexts), ...notices, ...fixes].flatMap(commands);++ test('every printed command names a registered fences key with a value config set accepts', () => {+ expect(printed.length).toBeGreaterThan(10);+ const refused = printed.flatMap(({ key, value }) => {+ const error = !KNOWN_CONFIG_KEYS.includes(key) ? 'not in KNOWN_CONFIG_KEYS' : validateFenceConfigValue(key, sample(value));+ return error ? [`gbrain config set ${key} ${value}: ${error}`] : [];+ });+ expect(refused).toEqual([]);+ expect([...new Set(printed.map(c => c.key))].filter(key => !FENCE_CONFIG_KEYS.includes(key))).toEqual([]);+ });++ test('the migration note and the behavior-change rows print every opt-out', () => {+ for (const optOut of OPT_OUTS) {+ expect(docTexts[MIGRATION_NOTE]).toContain(optOut);+ expect(notices.some(text => text.includes(optOut))).toBe(true);+ }+ });+});diff --git a/test/fence-format-reference.test.ts b/test/fence-format-reference.test.tsnew file mode 100644index 0000000000..509c2cf8a1--- /dev/null+++ b/test/fence-format-reference.test.ts@@ -0,0 +1,95 @@+/**+ * Fence format reference and fence reason docs (#6188, D23, D24).+ *+ * Protects: docs/guides/fence-format.md's generated region equals a fresh+ * render from the parser and repair constants (columns, layouts, vocabularies,+ * holder grammar, Tier 1 synonym tables, reason tiers, gates); both of its+ * examples parse with zero warnings; every FENCE_REASONS reason has its+ * `fence-<reason>` row in docs/guides/write-refusals.md, that row states the+ * reason's tier and whether the maintenance run clears it by itself, and it+ * links a section of the format reference that exists; every local link in+ * the reference resolves.+ * Fails when: a parser or schema constant changes without regenerating the+ * reference, an example stops parsing, a reason ships without its docs row+ * (its `docs` field would point at nothing), a row's tier or auto-retry+ * drifts from the reason table, or a link points at a missing section.+ * Why new: the reference is new, and the reason-table test checks only the+ * anchor string a reason carries, not that write-refusals.md defines it.+ * Seams: none; reads the committed docs.+ */+import { describe, expect, test } from 'bun:test';+import { existsSync, readFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { FENCE_FORMAT_PATH, renderFenceFormatDoc } from '../scripts/build-fence-format.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';+import { parseTakesFence } from '../src/core/takes-fence.ts';+import { FENCE_REASON_CODES, FENCE_REASONS } from '../src/core/fence-repair/reasons.ts';++const REGEN = 'Regenerate: bun run scripts/build-fence-format.ts';+const reference = readFileSync(join(import.meta.dir, '..', 'docs/guides/fence-format.md'), 'utf8');+const refusals = readFileSync(join(import.meta.dir, '..', 'docs/guides/write-refusals.md'), 'utf8');++function ids(markdown: string): Set<string> {+ return new Set([...markdown.matchAll(/<a id="([^"]+)"><\/a>/g)].map(m => m[1]!));+}++function markdownBlocks(markdown: string): string[] {+ return [...markdown.matchAll(/```markdown\n([\s\S]*?)```/g)].map(m => m[1]!);+}++describe('docs/guides/fence-format.md', () => {+ test('the generated region matches a fresh render from the constants', () => {+ expect(renderFenceFormatDoc(reference), REGEN).toBe(reference);+ });++ test('the facts and takes examples parse with no warnings', () => {+ const blocks = markdownBlocks(reference);+ const facts = blocks.filter(b => b.includes('gbrain:facts:begin')).map(parseFactsFence);+ const takes = blocks.filter(b => b.includes('gbrain:takes:begin')).map(parseTakesFence);+ expect(facts.map(r => ({ warnings: r.warnings, rows: r.facts.length > 0 }))).toEqual([{ warnings: [], rows: true }]);+ expect(takes.map(r => ({ warnings: r.warnings, rows: r.takes.length > 0 }))).toEqual([{ warnings: [], rows: true }]);+ });++ test('every local link in the reference resolves to an existing file and anchor', () => {+ const missing: string[] = [];+ for (const [, href] of reference.matchAll(/\]\(([^)\s]+)\)/g)) {+ if (/^[a-z]+:/i.test(href!)) continue;+ const [file, fragment] = href!.split('#');+ const target = file ? resolve(dirname(FENCE_FORMAT_PATH), file) : FENCE_FORMAT_PATH;+ if (!existsSync(target)) { missing.push(href!); continue; }+ if (fragment && !ids(readFileSync(target, 'utf8')).has(fragment)) missing.push(href!);+ }+ expect(missing).toEqual([]);+ });+});++describe('write-refusals fence reason rows', () => {+ const referenceIds = ids(reference);+ const rows = new Map(refusals.split('\n')+ .map(line => [/^\| <a id="fence-([a-z_]+)"><\/a>/.exec(line)?.[1], line] as const)+ .filter((entry): entry is readonly [string, string] => entry[0] !== undefined));++ test('every reason has exactly one row, and no row names an unknown reason', () => {+ expect([...rows.keys()].sort()).toEqual([...FENCE_REASON_CODES].sort());+ for (const reason of FENCE_REASON_CODES) expect(refusals.split(`<a id="fence-${reason}"></a>`).length).toBe(2);+ });++ test('each row states the reason table\'s tier and auto-retry', () => {+ const drift = FENCE_REASON_CODES.flatMap(reason => {+ const cells = rows.get(reason)!.split(' | ');+ const spec = FENCE_REASONS[reason];+ const expected = [spec.tier === null ? '`-`' : `\`${spec.tier}\``, spec.autoRetry ? 'yes' : 'no'];+ return cells[2] === expected[0] && cells[3] === expected[1] ? [] : [`${reason}: ${cells[2]} | ${cells[3]} (want ${expected.join(' | ')})`];+ });+ expect(drift).toEqual([]);+ });++ test('each row links an existing section of the format reference', () => {+ const broken = FENCE_REASON_CODES.flatMap(reason => {+ const anchors = [...rows.get(reason)!.matchAll(/\]\(fence-format\.md#([a-z-]+)\)/g)].map(m => m[1]!);+ if (!anchors.length) return [`${reason}: no fence-format.md link`];+ return anchors.filter(a => !referenceIds.has(a)).map(a => `${reason}: #${a}`);+ });+ expect(broken).toEqual([]);+ });+});