Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor): fence_integrity check and the fences.repair cap settings (#6188)

garrytand540ab7ad12b
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index c77071dbfe..4d26a1569a 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -21,6 +21,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/vector-coverage.ts` — `fact_take_vectors` (#5188, #5885), registered after `auto_chronicle`: per unarchived source (honoring `--source`), active facts (`eligibleFactEmbedding` + `staleFactEmbedding`) and takes (`countStaleTakes` with the DB-plane model and width) with no vector for their current text, split into missing versus other-model; warns with code `stale_vectors` and `details.fix` (`gbrain embed --stale`, or `gbrain takes embed` when `takes.auto_embed` is off; per-source `gbrain embed --facts --stale --source <id> --dry-run --json`). Keyless brains report `applicable: false`; a brain with no recorded model or width warns `vectors_not_verified`.
- `src/commands/doctor/checks/git-holds.ts` + `checks/frontmatter-repairable.ts` + `checks/frontmatter-hook.ts` — the #5988 hold and frontmatter checks. `git_held_files` (wave, host-only, `resolution: 'repair'`): Git-source holds per source from `readHeldCoverage` (missing vs stale counts) and the first five paths from `readGitHoldListing` with each one's code and `gitHoldFix` step, the put_page read-only note, `gbrain sources status <id>` and `gbrain repair frontmatter --source <id>`; `fail` once a source holds more than `sync.hold_escalate_count`; connector holds stay on `connector_held_items`. `frontmatter_repairable` (registered inline: emitted by the `frontmatter_integrity` entry from the same `scanBrainSources` walk, whose `PerSourceReport.repairable` counts files by repairable cause: recoverable `YAML_PARSE`, `needs_interpretation`, `FRONTMATTER_COMMENT_VALUE` on title/name/description/summary, `NESTED_QUOTES`, `NULL_BYTES`, `MISSING_CLOSE`, `SLUG_MISMATCH`); a deadline-partial scan sets `details.partial`. Both list `details.source_ids` and belong to the explicit-only `frontmatter` kind, so remediation classifies them `explicit_kind_required` with `--source <id>` when one source is named. `frontmatter_hook` (wave, operator): installed gbrain pre-commit hooks older than `FRONTMATTER_HOOK_VERSION`, fix `gbrain frontmatter install-hook --source <id> --force`. `frontmatterHoldsBannerNote` (a `POST_UPGRADE_NOTES` entry) names sources whose unfinished managed cursor stopped on a failed content refusal: the next sync recovers them, `gbrain sync --source <id> --no-pull` does it now, plus the repair preview and the hook refresh. Test: `test/doctor-frontmatter-holds.test.ts`.
+- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the PR1/PR2 step: `gbrain sources status <id>` for holds (then edit the fence and `gbrain sync --source <id> --no-pull`), `gbrain get --source <id> -- <slug>` and a fresh put_page for stored pages, `gbrain sync --source <id> --no-pull` for unsynced files. Location only. Test: `test/doctor-fence-integrity.test.ts`.
- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `registration` inline-in-doctor.ts or from this table). `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.
- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps), `combinedRemediateCommand` (with repair steps it ends `--expect <plan_hash>`, the same hash `--remediation-plan --json` reports as `plan_hash`), a `Repair kinds whose preview failed` block for `repair_preview_failures` (each `{kind, code, message, why, fix}`; such a kind is not planned, so a plan approved while it failed refuses `preview_changed` once it succeeds), `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / explicit_kind_required / unsupported, from wave checks run before and after; `details.partial` is pending; an explicit-only kind's preview gets `--source <id>` via `findingSource` when the finding names one source; `--remediation-plan` runs the wave checks too and reports the same classification as `findings`) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise, on budget exhaustion or when a repair preview failed; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`; 3 when consent is required), set through `setCliExitVerdict`. Consent (agent operator wave C1) lives in `doctor/remediate-consent.ts`: the CLI connects probe-only (no migrations) and computes the plan; when anything would run it calls `requireConsent` (effects `paid`, plus `destructive` with `--include-repairs`, bound to a `plan_hash` over the brain id, job step ids, repair kinds and pending counts, and the parameters, and persisted with the approval). Non-TTY without authorization changes nothing and exits 3 with the consent payload; `--json` never implies consent; `--yes` without `--max-usd` runs under the derived cap (estimate ×1.5, floor $0.25; the default cap when unpriced), and derived-cap exhaustion prints the `--max-usd` resume command. Startup (migrations) completes only after consent. A `--resume` is bound by its checkpoint manifest, not a new plan hash. Pinned by `test/doctor-remediate-consent.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 60fd5b8fde..74b1fcf454 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -8,7 +8,9 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `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/{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). `report.ts`: the one `fences_normalized` shape (count, by_class, writers, sample paths for local callers, coaching fix), the `fence_normalized` coaching notice and the per-file import tally (`fence_issues` for lenient imports). Tests: `test/fence-write-verbs.test.ts`, `test/persistence-sync-fence-holds.test.ts`, `test/fence-normalize-overhead.slow.test.ts`.
+- `src/core/fence-repair/{tier1,import-step,config,report}.ts` — #6188 Tier 1 on every write path. `fenceStep(page, ctx, { normalize })` is the step the coordinated screen, `importFromContent` and the append verbs share: no work beyond a marker substring check for a page with no fence, one shared scan when the fences compile, and `normalized` only when the validator passes and the output is a fixed point; otherwise `residual` with issues and the refusal location (`fenceIssuesWire` is the D18 `fence_issues` shape). `import-step.ts`: `applyImportFences` runs inside `importFromContent` before the remote hidden-row merge and withdrawal preservation (E7), reusing the screen's verdict unless hidden rows or a planned `renumber` need the database (stored rows load only then); `normalizeTargetFences` normalizes an append verb's target page or throws `target_fence_malformed` for a residual in its own fence kind; `normalizePageFences` serves synthesize verify. `config.ts`: `fences.normalize` (default on, read only when there is something to fix) and the model-repair caps `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00), validated at `config set` as non-negative USD (0 = no model spend) and read by `readFenceRepairCaps` (stored value = a user cap). `report.ts`: the one `fences_normalized` shape (count, by_class, writers, sample paths for local callers, coaching fix), the `fence_normalized` coaching notice and the per-file import tally (`fence_issues` for lenient imports). Tests: `test/fence-write-verbs.test.ts`, `test/persistence-sync-fence-holds.test.ts`, `test/fence-normalize-overhead.slow.test.ts`.
+- `src/core/fence-repair/{census,census-store}.ts` — #6188 the fence census: discovery only, nothing repairs. `runFenceCensus(engine, { sourceIds, deadline, now })` advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill over `pages.id`, then incremental passes over `updated_at >= watermark`, where each new watermark is the previous pass's start minus the oldest open writer transaction in `pg_stat_activity` and `LATE_COMMIT_GRACE_MS`, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk of `isFrontmatterScannablePath` files via `collectGitVisibleFiles`/`walkDir`, then only `git diff <walked commit>` files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the census `partial`. `judgeFences` runs the coordinated `fenceStep` (normalization on): `deterministic` when Tier 1 fixes it, else the highest `FENCE_REASONS` tier of its residual reasons (`reasonTier`; manual-only or page-dependent counts as manual). `listFenceCandidates` dedupes by page slug across `invalid_fence` holds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/`updated_at`/`content_hash`, file sha256/mtime, hold `upstream_version`); `summarizeFenceCensus` counts per source by bucket and tier with the oldest hold and scan state. `census-store.ts`: `op_checkpoints` rows `fence-candidate` (one per source incarnation and slug, `page`/`file` parts), `fence-scan` (cursors and last census) and `fence-trend` (one row per managed or legacy sync run, replaced as its total grows via `flushSyncFenceTrend`, and one per normalized page write via `recordPublicationFenceTrend`, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests: `test/fence-census.test.ts` (+ `test/e2e/fence-census-postgres.test.ts`), `test/doctor-fence-integrity.test.ts`.
+- `src/core/fence-repair/attempts.ts` — #6188 attempt claims and the attempt memo for paid (Tier 3) fence repairs, one `op_checkpoints` row per candidate (op `fence-repair-attempt`) changed only by compare-and-swap on a record version: `claimed` → `dispatched` → `settled` → `published` | `rejected` | `transient`, at most one paid call plus one corrective re-ask per claim. A rejected or published memo (content sha256, model, fence rules version, prompt version) is not claimed again until one changes; transient failures do not consume it; an expired lease is taken over (a stale dispatch counts a crash, two reject the memo). Records carry location and reason codes and their source incarnation, so the purge keeps them while it lives. Tests: `test/fence-repair-attempts.test.ts` (+ Postgres e2e).
- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.
- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.
- `src/core/persistence/{attribution,attribution-schema,context}.ts` — write attribution. `withCoordinatedWrite(engine, sourceIds, fn, attribution)` sets `gbrain.write_sources` and the transaction-local actor (`gbrain.write_request`, `gbrain.write_principal_kind`, `gbrain.write_principal_id`) in one round trip and restores them on exit; a nested scope keeps the outer actor. The argument is required: `requestAttribution(row)` for journaled publication (coordinator, forget), `maintenanceAttribution(engine)` (verified local writer, else the CLI registration, else `application`/`host:<id>`; no request) for derived facts, takes/timeline/link extraction, materialization, concept provenance, connector freshness and verify cleanup, `principalAttribution` for manual links (the caller) and source lifecycle (the topology principal). `withWriteAttribution` sets only the actor, for unmanaged legacy transactions; `maintenanceTransaction(engine, fn)` wraps it in one transaction, and every unmanaged direct writer except the three in the `system-of-record.md` "unattributed" list runs its write (or one bounded batch) in it. `attribution-schema.ts` (migration `f1_write_attribution`; migration-only like the facts DDL, so columns land last on fresh and upgraded brains) adds nullable columns and BEFORE ROW triggers: `facts`/`takes`/`timeline_entries` carry `write_*` (created_by, immutable once set) and `last_write_*` + `last_written_at` (moved only when a classified content column changes; a NULL actor records an unattributed writer); `pages.revision_*` is stamped when `knowledge_revision` changes; `page_versions.write_*` copies the snapshotted revision's actor and `archived_*` names the archiving write. `write_request_id` is `persistence_requests.id` with no foreign key; all-NULL reads as unrecorded. Every column of the three tables is classified content, projection (embeddings, `takes.updated_at`) or attribution, and a new column must be classified and the function re-created; the writer guard treats attribution-only facts/takes updates as projections. Tests: `test/write-attribution.test.ts`, `test/write-attribution-legacy.test.ts` (writer inventory) and `test/write-attribution-<family>.test.ts` (each routed unmanaged writer path; `write-attribution-timeline-10k.slow.test.ts` checks bounded batches at 10k pages) on PGLite; Postgres direct and PgBouncer through `test/e2e/write-attribution-postgres.test.ts`.
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index aff0935438..8e4b03c680 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -24,6 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/brainstorm/{domain-bank,orchestrator,judges}.ts` + `src/commands/{brainstorm,lsd,eval-brainstorm}.ts` + `src/core/last-retrieved.ts` — bisociation-grounded idea generation pair: `gbrain brainstorm <question>` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd <question>` (Lateral Synaptic Drift — inverted judge rejecting ideas with resistance >4.5 "too obvious", stale-page bias via `pages.last_retrieved_at`, 2 close × 12 far, axiomatic inversions required, ephemeral by default). The "domain bank" is prefix-stratified sampling from the user's own brain (`SELECT DISTINCT substring(slug from '^[^/]+/[^/]+')` cached 1h-TTL in `config` per source) tiebroken by `JOIN page_links` connection_count, with corpus-sampling fallback when fewer prefixes than M exist. Distance normalized to [0,1] via `1 - clamp(cosine_distance, 0, 2) / 2`. `judges.ts` exports `runJudge(config, ideas)` + two configs (`BRAINSTORM_JUDGE_CONFIG` weighted originality/resistance/thesis_density/concrete_grounding/cognitive_load 0.25/0.20/0.20/0.20/0.15 vs `LSD_JUDGE_CONFIG` cognitive_load 0.50 + inversion rule). Calibration cold-start fallback: when `calibration_profiles.active_bias_tags` is empty, judge runs without anti-bias context AND stderr-warns. Op-layer write-back in `src/core/operations.ts` `search`/`query`/`get_page` handlers fires `bumpLastRetrievedAt(engine, pageIds)` (fire-and-forget, 5-min throttled via SQL clause, default-on with `search.track_retrieval` config escape hatch); internal callers (sync, migrations, dream cycle) bypass the op layer so the LSD stale signal stays clean. The fire-and-forget IIFE is tracked in a module-scoped `Set<Promise<unknown>>`; `awaitPendingLastRetrievedWrites(timeoutMs?: number): Promise<{outcome, pending}>` resolves once all tracked promises settle, bounded by a 5s `Promise.race` timeout that stderr-warns the pending count. `src/cli.ts` awaits the drain unconditionally for every op in the op-dispatch finally block BEFORE `engine.disconnect()`, then a fallback `process.exit(0)` fires ONLY when `outcome === 'timeout'` AND `shouldForceExitAfterMain(argv)` (excludes `serve` so daemons stay alive) — so the IIFE cannot race disconnect and leave PGLite's WASM keeping Bun's event loop alive. `pages.last_retrieved_at TIMESTAMPTZ NULL` has a full (NOT partial) B-tree index covering both NULL and range branches; full forward-reference bootstrap probe on both engines. Frontmatter `mode: lsd` makes the dream-cycle synthesize phase skip LSD output via `isLsdOutput()` in `src/core/cycle/transcript-discovery.ts` short-circuiting `isDreamOutput()`. `gbrain eval brainstorm <fixture.jsonl>` is a three-axis conjunctive gate (distance + usefulness + grounding — distance alone is gameable). `gbrain doctor` has a `brainstorm_health` check (migration applied, `search.track_retrieval` setting, an unpriced cross or judge chat model, calibration cold-start status). Cost policy lives in `src/core/brainstorm/cost-gate.ts`: no cap flag is the $5 `default` tracker cap (an unpriced model warns and runs, priced calls stay metered; the estimate, mid-run guard and pre-judge check count it at Sonnet rates), `--max-usd N` (legacy `--max-cost`) is a `user` cap that refuses a run touching an unpriced chat, judge or embedding model before any work with the `no-pricing.ts` refusal, `--max-usd off` drops the USD ceiling; every price reads `pricing.overrides`; results carry `cost.cap_usd`/`cost.cap_source`. `judges.ts` computes the judge token budget via `computeJudgeMaxTokens(ideaCount, modelId)` (named constants `TOKEN_BUDGET_PER_IDEA`, `TOKEN_BUDGET_ENVELOPE`, `LEGACY_MIN_MAX_TOKENS`, `MAX_OUTPUT_TOKENS_CEIL`; `ANTHROPIC_OUTPUT_CAPS` map: Opus 4.7 32K, Sonnet 4.6 / Haiku 4.5 64K, legacy Claude 3.5 8K) so a large multi-call judge doesn't truncate mid-JSON; with no `modelOverride` the cap routes through the gateway's actual configured chat model via `getChatModel()`. `--save` for both commands persists through the canonical ingestion path: `persistSavedIdea(engine, {slug, content, provenanceVia})` calls `importFromContent({noEmbed:true, sourcePath})` (chunked + tagged + content_hash so search finds it, no embedding cost at save) THEN renders the saved row to disk via the shared `writePageThrough` helper (file rendered FROM the row so the two sinks can't diverge and `gbrain sync` doesn't churn it). `formatSaveOutcome(outcome, ctx)` returns an honest per-branch message (both-sinks, DB-only when no `sync.repo_path`/repo-not-a-dir, DB-saved-but-file-errored, total-failure → loud `save FAILED … NOT persisted` on stderr + nonzero exit) — `--save` never prints "Saved" when the DB write failed. `buildIdeaSlug(question, label, nonce?)` adds a random nonce suffix (injectable for tests) so two same-day runs sharing the first 60 slug chars don't clobber. `--json` callers stay DB-only. `buildBrainstormFrontmatterObject(result)` in orchestrator.ts returns the object form for `serializeMarkdown`. Pinned by `test/last-retrieved.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts` (IRON-RULE: real `bun src/cli.ts` subprocess against a hermetic PGLite tempdir asserts search/get/query exit 0 in <15s + daemon-survival), `test/fix-wave-structural.test.ts` (asserts the drain `await` is textually BEFORE `engine.disconnect`), `test/brainstorm/{distance,lsd-mode-skip,eval-brainstorm,judges-maxtokens,save}.test.ts`. Open Collider source: `github.com/CL-ML/open-collider`.
- `src/core/budget/budget-tracker.ts` — the keystone budget primitive. One typed error (`BudgetExhausted` with `reason: 'cost' | 'runtime' | 'no_pricing'`), one schema-stable audit JSONL at `~/.gbrain/audit/budget-YYYY-Www.jsonl`. Contracts: `record()` throws when cumulative spend exceeds cap (the cap is a real ceiling, not a suggestion); `reserve()` admission checks cumulative + OUTSTANDING spend and returns an opaque `BudgetReservation` id for each held projection; `record({ reservation })` settles that id and `release(id)` frees an attempt that never billed (no-op when already settled), so N concurrent callers can't all pass against the same cumulative and a small same-model call finishing first can't free a large in-flight call's hold (settlement is by id, never by model; an id-less record settles nothing; a priced reservation recorded under an unpriced served id charges its held ceiling). `gateway.chat` reserves, then runs the attempt in one try/finally that releases the id (provider-resolution failure, invocation-policy refusal); embed reserves after its preflights; rerank, decide, the TypeSafe rerank adapter and embed-facts pass their ids. Record audit rows carry `requested_model` and `reservation`; `reserve()` hard-fails with `reason: 'no_pricing'` when `maxCostUsd` is set AND the model is missing from pricing maps, its message and `BudgetExhausted.pricing` built by `no-pricing.ts` (warn-once preserved when cap is unset, naming the registration command); `lookupPricing` normalizes recipe aliases through `resolveRecipe` before consulting the pricing tables, so `claude-cli:haiku` prices exactly like `claude-cli:claude-haiku-4-5-20251001` at `reserve()`, `record()` and `isModelPriceable()` alike (the gateway reserves with the pre-resolution string the user configured); `extractUsageFromError(err, fallback)` returns `err.usage` when the SDK provides it, else the pessimistic fallback (caller passes `maxOutputTokens`, not the optimistic pre-call estimate). `onExhausted(cb)` fires once synchronously BEFORE the throw propagates so callers can persist checkpoints. Pricing math lives in the pure `src/core/budget/reservation-cost.ts`: `priceFor(model, kind, overrides) → { pricing, source: 'override' | 'provider_wildcard' | 'table' } | null` is the one resolver (exact override, then a `<provider>:*` wildcard admitted only for recipes with `billing: 'subscription'` by `isAllowedPricingOverrideKey`, then aliases, the claude-cli → Anthropic sibling, canonical rows and free local providers); `isModelPriceable`, `usageCostUsd`/`reservationCostUsd`, skillopt preflight and synthesize_concepts all use it. `parsePricingOverrides` drops disallowed keys and adds each alias key's canonical twin. Every `record()` also feeds an in-memory model ledger keyed by (requested model, served model, touchpoint, purpose) — updated BEFORE the cap throw and before the unpriced early return — exposed as `snapshot().models`; `BudgetActualUsage` carries `requestedModelId`, `purpose`, `failed`, `countsAsCall` (default true) and `estimated`, and rows track `calls` (gateway operations), `attempts` (every record), `failed_calls`, tokens, `cost_usd` (`null` when unpriced) and `cost_basis` (`estimated` if any contributing record was). `src/core/budget/models-used.ts` maps labels to touchpoints (`gateway.chat`→chat, `gateway.expand*`→expansion, `gateway.embed*`→embedding, `gateway.rerank*`→rerank, `gateway.ocr*`→ocr, else other), builds receipt rows (`buildModelsUsed`), merges resumed segments and renders the "Models called" table. No DB change. Shared by brainstorm, cycle/budget-meter, and eval-contradictions; `BudgetMeter` keeps its public shape over it (`schema_version: 1` stamped on every dream-budget audit line). Pinned by 18 unit cases. A4 cap sources: `capSource: 'derived' | 'default' | 'user'` (getter `capSource`; an explicit `maxCostUsd` with no declared source is `user`, the pre-A4 behaviour). Only a `user` cap hard-fails an unpriced model, and that `BudgetExhausted` carries `fix` (`noPricingFix`, actor `agent` on the CLI, `host_admin` when `transport` is remote); `derived`/`default` caps warn once and run the model unmetered. Cost exhaustion carries `capSource`, and a `derived` one appends `derived_cap_exhausted` to the agent-contract log (callers report it with `consent.ts`'s `derivedCapExhaustedError`). Pinned by `test/budget-tracker-cap-source.test.ts`.
+- `src/core/budget/daily-ledger.ts` — #6188 the durable per-UTC-day USD ledger over `budget_ledger`/`budget_reservations` (migration v012; no new schema), one ledger per (scope, resolver), e.g. `FENCE_REPAIR_LEDGER` (`llm_repair`/`fences`). `reserve(estimate, { capUsd })` is one conditional upsert (`reserved + committed + estimate <= cap`) plus a reservation row with `expires_at`; `dispatch` marks it sent; `settle(id, actual)` is idempotent, bound to the reservation's own day, and records an overrun; `release` returns an undispatched hold; expired holds are reclaimed before each reserve (a dispatched one is charged its estimate). Any ledger error means no call (`ledger_unavailable`); `meteredCall` runs the whole protocol. Amounts are NUMERIC(12,4), spend rounded up and caps down. `estimateChatCallUsd` prices a chat call through `pricing.overrides` and the canonical table; an unpriced model is metered at the highest canonical rate (`estimated: true`) under a default cap and refused with `noPricingGuidance` under a user cap. Never opens a BudgetTracker, so a caller's ambient tracker keeps metering. Read by doctor `fence_integrity` (today's spend). Tests: `test/daily-ledger.test.ts` (+ `test/e2e/daily-ledger-postgres.test.ts`, concurrent sessions).
- `src/core/consent.ts` + `src/core/consent-preapproval.ts` — the A4 consent primitive for trusted local CLI handlers. `requireConsent(req, env?)` evaluates the matrix (`paid`: `--yes`, finite `--max-usd`/`--max-cost`, `spend.posture=tokenmax` via `env.getConfig`, or the per-run preapproval; other effects: `--yes`, `--apply`/`--trust`, the per-command `NON_INTERACTIVE_AUTHORIZES` map (only `apply-migrations` → `persistent_install`), or the install preapproval, which never covers `credentials`; `destructive`: `--yes` plus `--expect <plan_hash>` when the request has one, never preapprovable, a mismatch is `preview_changed`), then a TTY prompt through `interaction.readLine` (EOF/timeout = decline), else throws `confirmation_required` carrying `confirmationPayload()` (`isConsentRefusal`; `renderConsentRefusal`/`printConsentRefusal`: `--json` payload document or an `[AGENT]` block with a fenced `[SHOW USER]` relay, exit 3). Caps on the returned `Authorization`: explicit or preapproved or configured → `user`; estimate → `derived` (x1.5, floor $0.25); no estimate → `default` ($5, printed). Refusals, declines and preapproved runs are logged to E11 (code, effects, outcome; never params). Destructive rail: `computePlanHash(selection)` (stable sha256 over brain, source, operation, records + revisions + incarnations, parameters, effects), `persistApproval`/`readApproval` under `<GBRAIN_HOME>/consent/approvals/`, `verifyApproval`/`assertApproval` re-ask on a changed, newly matching or dropped record. Preapprovals (`consent.preapprove.paid.max_usd_per_run`, `consent.preapprove.persistent_install`) live only in the host file plane; `setConsentPreapproval` refuses remote callers. Pinned by `test/consent.test.ts`; observational startup by `test/observational-startup.serial.test.ts`.
- `src/core/embed-consent.ts` — consent for explicit embedding backfills (`gbrain embed`, `jobs submit embed|embed-backfill|embed-catch-up`, `features --auto-fix`): `requireEmbedBackfillConsent` (`paid`, an SQL estimate from the text it would embed, a user cap below the estimate refuses with `cost_cap_exceeded`), null when nothing can spend (`embedWouldSpend`: embeddings off, no credentials, or a local recipe billing $0 per `embeddingProviderIsFree`). `embedBackfillFix` is the doctor-side backlog fix. Write-path embedding and the unattended library paths (autopilot, cycles, queued jobs) are deliberately outside it. Doctor's opt-in live probe asks through `src/commands/doctor/probe-consent.ts` (`paid` + `egress`). Pinned by `test/agent-operator-gate-fixes.{,serial.}test.ts`.
- `src/core/agent-markers.ts` — the one `[AGENT] … [/AGENT]` / `[SHOW USER]` builder (`agentBlock`): fixed field vocabulary, every value through `inertText()` so interpolated text cannot open or close a block.
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index fabee825ae..7551d08787 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser. A status-only host's 503 `serve_status_only` envelope from OAuth discovery or `/token` (`status_only` on the `remote-mcp-probe.ts` failure, with `retry_after_s`) becomes `RemoteMcpError` detail (`code`, `reason`, `why`, `fix`), which the CLI renders through the agent envelope and the thin-client doctor reports on its check (`test/remote-mcp-status-only.test.ts`).
-- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests and `sync-import-provenance` rows of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests never expire.
+- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests, `sync-import-provenance` rows, the blocked-cursor conversion log, the #6188 fence census (`fence-candidate`, `fence-scan`) and paid fence-repair attempt claims and memos (`fence-repair-attempt`) of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests never expire.
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms` and `repair extractor-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`).
- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `abortOnCleanupPass(name)` wraps that for child work: it returns `{ signal, release }`, the signal aborts when the cleanup pass runs (sync's `git pull` uses it), and `release` deregisters it. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/process-cleanup.test.ts` and `test/e2e/supervisor-stop-drain-5062.test.ts`.
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 337aae2d80..5c97176c17 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -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. 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. 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-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.md
index 6158f62dfb..33edb07396 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -213,6 +213,26 @@ named fence in the file (never the frontmatter), commit, then
lists every fence hold with its location. To add rows without hand-editing a
table, use `remember` (facts) or `takes_add` (takes).
+<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 held
+file, a stored page whose fence does not parse (for example one an older
+release imported as written), and a checkout file not yet synced. Each is
+split by the tier that would clear it: `deterministic` (the normalizer fixes
+it the next time the file syncs or the page is written), `resolver` (a
+holder name to resolve), `llm` (a table only a rewrite can realign) and
+`manual` (an edit only a person can decide). It also shows the oldest hold's
+age, the fences normalized in the last 7 days with their top writers (a
+source at 20 or more warns: something keeps writing malformed fences) and the
+model-repair caps `fences.repair.max_usd_per_page` (default $0.05) and
+`fences.repair.max_usd_per_day` (default $1.00) with today's spend. Each run
+scans for at most `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (10 s) and resumes where the
+last 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`.
+
+**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. |
diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.md
index 9755dda05f..761a98df5d 100644
--- a/docs/operations/spend-controls.md
+++ b/docs/operations/spend-controls.md
@@ -153,6 +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 |
| 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 |
diff --git a/llms-full.txt b/llms-full.txt
index 1fb31ca51a..99724ef4a3 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10142,7 +10142,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. 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. 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-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/src/commands/doctor/checks/fence-integrity.ts b/src/commands/doctor/checks/fence-integrity.ts
new file mode 100644
index 0000000000..09cb094acc
--- /dev/null
+++ b/src/commands/doctor/checks/fence-integrity.ts
@@ -0,0 +1,137 @@
+/**
+ * #6188 `fence_integrity`: per source, the malformed facts and takes fences
+ * still waiting, counted once each across three origins (an `invalid_fence`
+ * sync hold, a stored page whose fence fails the coordinated fence step, a
+ * working-tree file not yet synced) and split by the tier that would clear
+ * it (deterministic Tier 1, resolver, model, manual edit); the oldest
+ * unresolved hold's age; and the 7-day trend of fences Tier 1 normalized with
+ * its top writers, warning at `FENCE_NORMALIZATION_WARN_7D`.
+ *
+ * Each run first advances the stored census within a bounded scan
+ * (`GBRAIN_DOCTOR_FENCE_TIMEOUT_MS`, default 10 s), then reports the stored
+ * summary. A census the scan did not finish is `partial` and never reports
+ * ok; the next run resumes where it stopped. Output is location only: slugs,
+ * paths, fences, rows, reasons and tiers, never a cell value.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { agentFix } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { runFenceCensus, summarizeFenceCensus, type SourceCensus, type TierCounts } from '../../../core/fence-repair/census.ts';
+import { readTrend, type TrendEntry } from '../../../core/fence-repair/census-store.ts';
+import { readFenceRepairCaps } from '../../../core/fence-repair/config.ts';
+import { STRUCTURED_WRITE_ADVICE } from '../../../core/fence-repair/report.ts';
+import { dailyLedger, FENCE_REPAIR_LEDGER } from '../../../core/budget/daily-ledger.ts';
+
+/**
+ * A source whose writers made Tier 1 normalize this many pages or files in
+ * the last 7 days warns: something keeps emitting malformed fences, and each
+ * normalized write returns a page that differs from what was sent.
+ */
+export const FENCE_NORMALIZATION_WARN_7D = 20;
+const TREND_DAYS = 7;
+const DOCS = 'docs/guides/write-refusals.md#invalid_fence';
+
+/** `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s): the wall-clock bound of one census scan. */
+export function fenceScanTimeoutMs(): number {
+ const n = parseInt(process.env.GBRAIN_DOCTOR_FENCE_TIMEOUT_MS ?? '', 10);
+ return Number.isFinite(n) && n > 0 ? n : 10_000;
+}
+
+interface SourceTrend { source_id: string; normalized_7d: number; by_day: Array<{ day: string; count: number }>; top_writers: Array<{ writer: string; count: number }> }
+
+function sourceTrend(sourceId: string, days: readonly TrendEntry[]): SourceTrend {
+ const writers = new Map<string, number>();
+ for (const day of days) for (const [writer, n] of Object.entries(day.writers)) writers.set(writer, (writers.get(writer) ?? 0) + n);
+ return { source_id: sourceId, normalized_7d: days.reduce((sum, day) => sum + day.count, 0), by_day: days.map(day => ({ day: day.day, count: day.count })),
+ top_writers: [...writers].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 5).map(([writer, count]) => ({ writer, count })) };
+}
+
+const tiers = (counts: TierCounts) => (['deterministic', 'resolver', 'llm', 'manual'] as const).filter(t => counts[t]).map(t => `${t} ${counts[t]}`).join(', ');
+
+function sourceLine(census: SourceCensus, now: number): string {
+ const parts = [census.holds.total ? `${census.holds.total} held file(s)` : '', census.pages.total ? `${census.pages.total} stored page(s)` : '',
+ census.files.total ? `${census.files.total} unsynced file(s)` : ''].filter(Boolean);
+ const age = census.oldest_hold_at ? `; oldest hold ${Math.max(0, Math.round((now - Date.parse(census.oldest_hold_at)) / 3_600_000))} h old` : '';
+ return `${census.source_id}: ${parts.join(', ')} (by tier: ${tiers(census.by_tier)})${age}`;
+}
+
+/** The next step for one source, from the PR1/PR2 contract: holds and files are edited and synced, stored pages are read and written again. */
+function sourceFix(census: SourceCensus) {
+ if (census.holds.total) {
+ return agentFix(['gbrain', 'sources', 'status', census.source_id, '--json'], `Lists each held file of ${census.source_id} with the fence, section, rows and reason; `
+ + `read its page with gbrain get --source ${census.source_id} -- <slug>, edit that fence in the file, commit, then run gbrain sync --source ${census.source_id} --no-pull.`,
+ 'fence_integrity', { docs: DOCS });
+ }
+ const page = census.sample.find(c => c.bucket === 'page');
+ if (census.pages.total && page) {
+ return agentFix(['gbrain', 'get', '--source', census.source_id, '--', page.key], `Reads ${page.key}; write it again with put_page so gbrain normalizes a fixable fence `
+ + `(it reports fences_normalized), or correct the fence the refusal names first. ${STRUCTURED_WRITE_ADVICE}`, 'fence_integrity', { docs: DOCS });
+ }
+ return agentFix(['gbrain', 'sync', '--source', census.source_id, '--no-pull'], `Syncs ${census.source_id}: a fixable fence is rewritten and committed, and any other `
+ + 'is held with its fence, rows and reason (gbrain sources status names them) so you can edit that fence and sync again.', 'fence_integrity', { docs: DOCS });
+}
+
+/** The check's verdict after a bounded census scan. */
+export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutMs?: number; now?: () => Date } = {}): Promise<Omit<Check, 'name'>> {
+ const now = opts.now ?? (() => new Date());
+ const timeoutMs = opts.timeoutMs ?? fenceScanTimeoutMs();
+ await runFenceCensus(engine, { deadline: now().getTime() + timeoutMs, now });
+ const census = await summarizeFenceCensus(engine);
+ const from = new Date(now().getTime() - (TREND_DAYS - 1) * 86_400_000).toISOString().slice(0, 10);
+ const trendRows = await readTrend(engine, census.map(c => c.source_id), from);
+ const trend = census.map(c => sourceTrend(c.source_id, trendRows.get(c.source_id) ?? []));
+ const caps = await readFenceRepairCaps(engine);
+ const today = await dailyLedger(engine, FENCE_REPAIR_LEDGER, { now }).readDay().catch(() => null);
+ const waiting = census.filter(c => c.total);
+ const partial = census.filter(c => !c.scan.complete);
+ const noisy = trend.filter(t => t.normalized_7d >= FENCE_NORMALIZATION_WARN_7D);
+ const total = waiting.reduce((sum, c) => sum + c.total, 0);
+ const details = {
+ total, partial: partial.length > 0, partial_sources: partial.map(c => c.source_id), sources: census, trend, warn_at_normalized_7d: FENCE_NORMALIZATION_WARN_7D,
+ model_repair: { max_usd_per_page: caps.perPageUsd, max_usd_per_day: caps.perDayUsd, spent_today_usd: today?.committedUsd ?? null, reserved_today_usd: today?.reservedUsd ?? null },
+ timeout_ms: timeoutMs, docs: DOCS,
+ };
+ if (!total && !partial.length && !noisy.length) {
+ return { status: 'ok', details, message: census.length ? `No malformed facts or takes fence is held, stored or waiting in a checkout (${census.length} source(s) scanned).` : 'No sources to scan.' };
+ }
+ const at = now().getTime();
+ const sentences: string[] = [];
+ if (total) {
+ sentences.push(`${total} malformed facts or takes fence(s) wait: ${waiting.map(c => sourceLine(c, at)).join('; ')}. `
+ + 'Deterministic ones are rewritten losslessly the next time the file syncs or the page is written; the others need the named fence edited (none of them blocks a sync).');
+ if (waiting.some(c => c.by_tier.llm)) sentences.push(caps.perDayUsd === 0
+ ? 'Model repair spend is off (fences.repair.max_usd_per_day 0).'
+ : `Model repair caps: $${caps.perPageUsd.toFixed(2)} per page, $${caps.perDayUsd.toFixed(2)} per day${today ? ` ($${today.committedUsd.toFixed(2)} spent today)` : ''}.`);
+ }
+ if (noisy.length) {
+ sentences.push(`Writers keep sending malformed fences: ${noisy.map(t => `${t.source_id} had ${t.normalized_7d} normalized in ${TREND_DAYS} days`
+ + `${t.top_writers.length ? ` (top writers: ${t.top_writers.map(w => `${w.writer} ${w.count}`).join(', ')})` : ''}`).join('; ')} (warns at ${FENCE_NORMALIZATION_WARN_7D}). `
+ + `Fix the generator; a normalized page differs from what was sent. ${STRUCTURED_WRITE_ADVICE}`);
+ }
+ if (partial.length) {
+ sentences.push(`PARTIAL CENSUS: the scan of ${partial.map(c => c.source_id).join(', ')} did not finish within ${timeoutMs / 1000}s, so more fences may be malformed; `
+ + 'run gbrain doctor --only fence_integrity again to resume it (raise GBRAIN_DOCTOR_FENCE_TIMEOUT_MS for a larger share per run).');
+ }
+ const first = waiting[0];
+ const fix = first ? sourceFix(first)
+ : partial.length ? agentFix(['gbrain', 'doctor', '--only', 'fence_integrity', '--json'], 'Resumes the fence census where the last scan stopped and reports what it found.', 'fence_integrity', { docs: DOCS })
+ : agentFix(['gbrain', 'sources', 'status', noisy[0]!.source_id, '--json'], `Shows ${noisy[0]!.source_id}'s recent sync result, including fences_normalized with sample paths, so you can find what writes the malformed fences.`,
+ 'fence_integrity', { docs: DOCS });
+ return { status: 'warn', details, fix, message: sentences.join(' ') };
+}
+
+async function runFenceIntegrity(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ const checks: Check[] = [];
+ ctx.progress.heartbeat('fence_integrity');
+ try {
+ checks.push({ name: 'fence_integrity', ...await fenceIntegrityResult(engine) });
+ } catch (error) {
+ checks.push({ name: 'fence_integrity', status: 'warn', fix_unavailable_reason: 'check_errored', details: { health: 'unknown' },
+ message: `The fence census could not run: ${error instanceof Error ? error.message : String(error)}. Fence health is unknown; run gbrain doctor --only fence_integrity again.` });
+ }
+ return checks;
+}
+
+export const fenceIntegrityEntry: DoctorEntry = { name: 'fence_integrity', emits: ['fence_integrity'], run: runFenceIntegrity };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 466e154057..4646f125f9 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -98,6 +98,7 @@ import { harnessWiringDoctorEntry } from './checks/harness-wiring.ts';
import { agentContractEntry } from './checks/agent-contract.ts';
import { chatFallbackChainEntry } from './checks/chat-fallback.ts';
import { behaviorChangesEntry } from './checks/behavior-changes.ts';
+import { fenceIntegrityEntry } from './checks/fence-integrity.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
import type { Check } from '../doctor.ts';
import { infoCheck } from './check-fix.ts';
@@ -172,6 +173,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
retrievalFeedbackEntry,
revisionBackfillEntry,
coreMemoryEntry,
+ fenceIntegrityEntry,
searchModeEntry,
];
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 449dee9b44..d251bd5899 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -257,6 +257,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },
{ 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.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/config.ts b/src/core/config.ts
index df76fc1870..2af92f6751 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1671,6 +1671,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'sync.hold_escalate_pct',
'sync.parser_regression',
'fences.normalize', // #6188: inline Tier 1 fence normalization (fence-repair/config.ts); default on
+ 'fences.repair.max_usd_per_page', // #6188: Tier 3 fence repair caps (fence-repair/config.ts); 0 = no model spend
+ 'fences.repair.max_usd_per_day',
// #2179: clamp window for DCR-requested per-client token TTLs. Read by
// `gbrain serve --http` at startup; unset min defaults to 300s, unset max
// defaults fail-closed to max(--token-ttl, min).
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index ab833507bb..c59a5afc58 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -61,6 +61,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'connector_checkpoints',
'connector_held_items',
'git_held_files',
+ 'fence_integrity',
'credential_projection_pending',
'derived_visibility',
'extractor_facts_expired',
diff --git a/src/core/fence-repair/config.ts b/src/core/fence-repair/config.ts
index 396ececa3d..3f13f235af 100644
--- a/src/core/fence-repair/config.ts
+++ b/src/core/fence-repair/config.ts
@@ -1,15 +1,28 @@
/**
- * #6188: the inline fence normalization switch. `fences.normalize` (default
- * true, opt-out) lets Tier 1 rewrite a fixable facts or takes fence on write
- * paths; false restores refusing (coordinated writers) or storing as written
- * (legacy importers). It is read only when a write actually has something to
+ * #6188: fence settings. `fences.normalize` (default true, opt-out) lets
+ * Tier 1 rewrite a fixable facts or takes fence on write paths; false
+ * restores refusing (coordinated writers) or storing as written (legacy
+ * importers). It is read only when a write actually has something to
* normalize, so a clean write never pays the config read.
+ *
+ * `fences.repair.max_usd_per_page` (default $0.05) and
+ * `fences.repair.max_usd_per_day` (default $1.00) cap model (Tier 3) fence
+ * repair: per page, and per UTC day across every process through the daily
+ * USD ledger. 0 means no Tier 3 spend. They are validated at `config set`
+ * and shown by `gbrain doctor` (`fence_integrity`); the fence repair reads
+ * them.
*/
import type { BrainEngine } from '../engine.ts';
export const FENCES_NORMALIZE_KEY = 'fences.normalize';
+export const FENCE_REPAIR_MAX_USD_PER_PAGE_KEY = 'fences.repair.max_usd_per_page';
+export const FENCE_REPAIR_MAX_USD_PER_DAY_KEY = 'fences.repair.max_usd_per_day';
+/** Defaults of the Tier 3 caps (USD). */
+export const FENCE_REPAIR_DEFAULT_MAX_USD_PER_PAGE = 0.05;
+export const FENCE_REPAIR_DEFAULT_MAX_USD_PER_DAY = 1;
+const USD_KEYS: readonly string[] = [FENCE_REPAIR_MAX_USD_PER_PAGE_KEY, FENCE_REPAIR_MAX_USD_PER_DAY_KEY];
/** Every `fences.*` key `gbrain config set` accepts. */
-export const FENCE_CONFIG_KEYS: readonly string[] = [FENCES_NORMALIZE_KEY];
+export const FENCE_CONFIG_KEYS: readonly string[] = [FENCES_NORMALIZE_KEY, ...USD_KEYS];
const TRUE = /^(true|1|on|yes)$/i;
const FALSE = /^(false|0|off|no)$/i;
@@ -17,10 +30,43 @@ const FALSE = /^(false|0|off|no)$/i;
/** Null when the value is valid for the key; otherwise the refusal text (nothing is written). */
export function validateFenceConfigValue(key: string, value: string): string | null {
if (!FENCE_CONFIG_KEYS.includes(key)) return `Unknown config key "${key}". fences keys: ${FENCE_CONFIG_KEYS.join(', ')}. Nothing was written.`;
+ if (USD_KEYS.includes(key)) {
+ return parseUsd(value) === null ? `${key} must be a non-negative USD amount such as 0.05 (0 means no model spend on fence repair; got "${value}"). Nothing was written.` : null;
+ }
if (TRUE.test(value.trim()) || FALSE.test(value.trim())) return null;
return `${key} must be true or false (got "${value}"). Nothing was written.`;
}
+function parseUsd(value: string): number | null {
+ const text = value.trim();
+ if (!/^\d+(\.\d+)?$/.test(text)) return null;
+ const usd = Number(text);
+ return Number.isFinite(usd) ? usd : null;
+}
+
+export interface FenceRepairCaps {
+ perPageUsd: number;
+ perDayUsd: number;
+ /** `user` when the setting is stored, `default` otherwise (an unpriced model is refused only under a user cap). */
+ perPageSource: 'user' | 'default';
+ perDaySource: 'user' | 'default';
+}
+
+/** The Tier 3 caps; an unset or unreadable value keeps its default. */
+export async function readFenceRepairCaps(engine: Pick<BrainEngine, 'getConfig'>): Promise<FenceRepairCaps> {
+ const read = async (key: string): Promise<number | null> => {
+ try {
+ const value = await engine.getConfig(key);
+ return typeof value === 'string' ? parseUsd(value) : null;
+ } catch {
+ return null;
+ }
+ };
+ const [page, day] = await Promise.all([read(FENCE_REPAIR_MAX_USD_PER_PAGE_KEY), read(FENCE_REPAIR_MAX_USD_PER_DAY_KEY)]);
+ return { perPageUsd: page ?? FENCE_REPAIR_DEFAULT_MAX_USD_PER_PAGE, perDayUsd: day ?? FENCE_REPAIR_DEFAULT_MAX_USD_PER_DAY,
+ perPageSource: page === null ? 'default' : 'user', perDaySource: day === null ? 'default' : 'user' };
+}
+
/** The effective switch: on unless explicitly set false. A config read error keeps the default (on). */
export async function fencesNormalizeEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {
try {
diff --git a/test/doctor-fence-integrity.test.ts b/test/doctor-fence-integrity.test.ts
new file mode 100644
index 0000000000..98fffc26e7
--- /dev/null
+++ b/test/doctor-fence-integrity.test.ts
@@ -0,0 +1,167 @@
+/**
+ * #6188 PR3 doctor `fence_integrity` (src/commands/doctor/checks/fence-integrity.ts).
+ *
+ * Protects: doctor reports every malformed facts or takes fence that waits
+ * (held file, stored page, unsynced file) per source, split by planned tier,
+ * with the oldest hold and the PR1/PR2 next step (never `repair fences`,
+ * which has not shipped); a census the bounded scan did not finish is
+ * partial and never ok; the 7-day normalization trend warns at
+ * FENCE_NORMALIZATION_WARN_7D and not below, naming the top writers; the
+ * model-repair caps and today's ledger spend are shown; output is location
+ * only.
+ * Fails when: a partial or stale census reads ok, counts double a page found
+ * twice, the trend threshold is off by one, or a cell value reaches the check.
+ * PGLite in-memory ($0); synthetic content only.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { categorizeCheck } from '../src/core/doctor-categories.ts';
+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';
+import { FENCE_NORMALIZATION_WARN_7D, fenceIntegrityResult } from '../src/commands/doctor/checks/fence-integrity.ts';
+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';
+import { recordWriteTrend } from '../src/core/fence-repair/census-store.ts';
+import { dailyLedger, FENCE_REPAIR_LEDGER } from '../src/core/budget/daily-ledger.ts';
+
+const T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';
+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';
+const FB = '<!--- gbrain:facts:begin -->', FE = '<!--- gbrain:facts:end -->';
+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';
+const CLAIM = 'Sentinelclaimzq6 renews yearly', HOLDER = 'Sentinelholderzq6 Example', KIND = 'sentinelkindzq6';
+const SECRETS = [CLAIM, HOLDER, KIND, 'Sentinelclaimzq6', 'Sentinelholderzq6'];
+const row = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | private | medium | 2026-01-01 | | call | |`;
+const RESOLVER = `${T}\n${TH}\n| 1 | ${CLAIM} | take | ${HOLDER} | 0.7 | 2026-01 | chat |\n${TE}\n`;
+const MANUAL = `${T}\n${TH}\n| 1 | Synthetic take | ${KIND} | brain | 0.7 | 2026-01 | chat |\n${TE}\n`;
+const LLM = `${FB}\n${row(1, 'Synthetic fact')}\n${row(2, 'Another synthetic fact')}\n${FE}\n`;
+const DETERMINISTIC = `${FB}\n${FH}\n${row(1, 'Synthetic fact')}\n${row(2, 'Second synthetic fact')}\n\n`;
+const CLEAN = `${FB}\n${FH}\n${row(1, 'Clean synthetic fact')}\n${FE}\n`;
+
+let engine: PGLiteEngine;
+const roots: string[] = [];
+const NOW = new Date('2026-10-06T12:00:00Z');
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => { await engine.disconnect(); for (const root of roots) rmSync(root, { recursive: true, force: true }); }, 60_000);
+
+// Every test reads the whole brain, so each one starts with only its own sources live.
+afterEach(async () => {
+ await engine.executeRaw("UPDATE sources SET archived=true WHERE id<>'default'");
+ for (const key of ['fences.repair.max_usd_per_day', 'fences.repair.max_usd_per_page']) await engine.unsetConfig(key);
+});
+
+async function source(files: Record<string, string> = {}) {
+ const id = `fi-${randomUUID().replace(/-/g, '').slice(0, 10)}`;
+ const root = mkdtempSync(join(tmpdir(), 'fence-integrity-'));
+ roots.push(root);
+ for (const [path, content] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); }
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, root]);
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ return { id, root, incarnation };
+}
+const md = (title: string, body: string) => `---\ntitle: ${title}\n---\n${body}`;
+const stored = (sourceId: string, slug: string, body: string) => engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: '' }, { sourceId });
+const result = (opts: { timeoutMs?: number } = {}) => fenceIntegrityResult(engine, { timeoutMs: opts.timeoutMs ?? 60_000, now: () => NOW });
+
+describe('fence_integrity doctor check', () => {
+ test('is registered before search_mode and categorized as a brain check', () => {
+ const names = DOCTOR_CHECK_REGISTRY.map(entry => entry.name);
+ expect(names.indexOf('fence_integrity')).toBe(names.indexOf('search_mode') - 1);
+ expect(categorizeCheck('fence_integrity')).toBe('brain');
+ });
+
+ test('a brain whose fences all parse is ok once the census is complete', async () => {
+ const s = await source({ 'notes/clean.md': md('Clean', CLEAN) });
+ await stored(s.id, 'notes/clean', CLEAN);
+ const check = await result();
+ expect(check.status).toBe('ok');
+ expect(check.details).toMatchObject({ total: 0, partial: false, warn_at_normalized_7d: FENCE_NORMALIZATION_WARN_7D });
+ });
+
+ test('counts each waiting fence once per source by bucket and tier, names the oldest hold and the edit-and-sync step', async () => {
+ const s = await source({ 'notes/held.md': md('Held', MANUAL), 'notes/both.md': md('Both', RESOLVER), 'notes/unsynced.md': md('Unsynced', LLM) });
+ await stored(s.id, 'notes/both', RESOLVER);
+ await stored(s.id, 'notes/db-only', DETERMINISTIC);
+ await engine.transaction(tx => writeGitHold(tx, { source_id: s.id, incarnation: s.incarnation, path: 'notes/held.md', source_path: 'notes/held.md', slug: 'notes/held',
+ page_id: null, code: 'invalid_fence', message: 'Fence takes_kind_unsupported: in the takes fence (body), row 1, column kind.', upstream_version: 'v1',
+ observed_at: new Date().toISOString(), run_id: 'run-1', mode: 'managed',
+ meta: { reason: 'takes_kind_unsupported', recovery_version: 1, fence_version: 1, fence: { reason: 'takes_kind_unsupported', fence: 'takes', section: 'body', rows: [1], columns: ['kind'], line: 4 } } }));
+ const check = await result();
+ expect(check.status).toBe('warn');
+ const details = check.details as any;
+ expect(details.total).toBe(4);
+ expect(details.sources.find((c: any) => c.source_id === s.id)).toMatchObject({ total: 4, holds: { manual: 1, total: 1 }, pages: { resolver: 1, deterministic: 1, total: 2 },
+ files: { llm: 1, total: 1 }, by_tier: { deterministic: 1, resolver: 1, llm: 1, manual: 1, total: 4 } });
+ expect(check.message).toContain(`${s.id}: 1 held file(s), 2 stored page(s), 1 unsynced file(s) (by tier: deterministic 1, resolver 1, llm 1, manual 1); oldest hold`);
+ expect(check.message).toContain('Model repair caps: $0.05 per page, $1.00 per day ($0.00 spent today).');
+ expect(check.fix).toMatchObject({ argv: ['gbrain', 'sources', 'status', s.id, '--json'], actor: 'agent' });
+ expect(check.fix!.why).toContain(`gbrain sync --source ${s.id} --no-pull`);
+ const text = JSON.stringify(check);
+ expect(text).not.toMatch(/repair fences/);
+ for (const secret of SECRETS) expect(text).not.toContain(secret);
+ });
+
+ test('a stored-page-only source points at reading the page and writing it again', async () => {
+ const s = await source();
+ await stored(s.id, 'notes/db-only', DETERMINISTIC);
+ const check = await result();
+ expect(check.status).toBe('warn');
+ expect(check.fix!.argv).toEqual(['gbrain', 'get', '--source', s.id, '--', 'notes/db-only']);
+ });
+
+ test('a census the scan did not finish is partial and never ok, even with nothing found so far', async () => {
+ const s = await source({ 'notes/clean.md': md('Clean', CLEAN) });
+ await stored(s.id, 'notes/clean', CLEAN);
+ const partial = await result({ timeoutMs: 0 });
+ expect(partial.status).toBe('warn');
+ expect(partial.details).toMatchObject({ total: 0, partial: true });
+ expect((partial.details as any).partial_sources).toContain(s.id);
+ expect(partial.message).toContain('PARTIAL CENSUS');
+ expect(partial.fix!.argv).toEqual(['gbrain', 'doctor', '--only', 'fence_integrity', '--json']);
+ expect((await result()).status).toBe('ok');
+ // A finished census goes stale when a later scan cannot catch up: still never ok.
+ await stored(s.id, 'notes/later', CLEAN);
+ expect((await result({ timeoutMs: 0 })).details).toMatchObject({ partial: true });
+ });
+
+ test('the 7-day normalization trend warns at the threshold and not below, naming the top writers', async () => {
+ const s = await source();
+ for (let i = 0; i < FENCE_NORMALIZATION_WARN_7D - 1; i++) {
+ await recordWriteTrend(engine, { sourceId: s.id, requestKey: `r-${i}`, day: i % 2 ? '2026-10-06' : '2026-10-01', byClass: { renumber: 1 }, writer: i % 3 ? 'oauth_client' : 'local_cli' });
+ }
+ // Older than the 7-day window: never counted.
+ await recordWriteTrend(engine, { sourceId: s.id, requestKey: 'old', day: '2026-09-29', byClass: { renumber: 1 }, writer: 'local_cli' });
+ const below = await result();
+ expect(below.status).toBe('ok');
+ expect((below.details as any).trend.find((t: any) => t.source_id === s.id).normalized_7d).toBe(FENCE_NORMALIZATION_WARN_7D - 1);
+ await recordWriteTrend(engine, { sourceId: s.id, requestKey: 'last', day: '2026-10-06', byClass: { close_fence: 1 }, writer: 'oauth_client' });
+ const at = await result();
+ expect(at.status).toBe('warn');
+ expect(at.message).toContain(`${s.id} had ${FENCE_NORMALIZATION_WARN_7D} normalized in 7 days (top writers: oauth_client 13, local_cli 7)`);
+ expect((at.details as any).trend.find((t: any) => t.source_id === s.id)).toMatchObject({ normalized_7d: FENCE_NORMALIZATION_WARN_7D,
+ top_writers: [{ writer: 'oauth_client', count: 13 }, { writer: 'local_cli', count: 7 }] });
+ });
+
+ test('shows the model-repair caps and today\'s ledger spend, and says when model spend is off', async () => {
+ const s = await source();
+ await stored(s.id, 'notes/model', LLM);
+ const ledger = dailyLedger(engine, FENCE_REPAIR_LEDGER, { now: () => NOW });
+ const held = await ledger.reserve(0.2, { capUsd: 1 });
+ if (!held.ok) throw new Error('expected a reservation');
+ await ledger.dispatch(held.reservation.id);
+ await ledger.settle(held.reservation.id, 0.12);
+ await engine.setConfig('fences.repair.max_usd_per_page', '0.1');
+ const capped = await result();
+ expect(capped.details).toMatchObject({ model_repair: { max_usd_per_page: 0.1, max_usd_per_day: 1, spent_today_usd: 0.12, reserved_today_usd: 0 } });
+ expect(capped.message).toContain('Model repair caps: $0.10 per page, $1.00 per day ($0.12 spent today).');
+ await engine.setConfig('fences.repair.max_usd_per_day', '0');
+ expect((await result()).message).toContain('Model repair spend is off (fences.repair.max_usd_per_day 0).');
+ });
+});
diff --git a/test/fence-repair-config.test.ts b/test/fence-repair-config.test.ts
new file mode 100644
index 0000000000..b69be6194a
--- /dev/null
+++ b/test/fence-repair-config.test.ts
@@ -0,0 +1,56 @@
+/**
+ * #6188 PR3 fence repair caps (src/core/fence-repair/config.ts).
+ *
+ * Protects: `fences.repair.max_usd_per_page` (default 0.05) and
+ * `fences.repair.max_usd_per_day` (default 1.00) are registered keys that
+ * `gbrain config set` accepts as non-negative USD amounts (0 = no model
+ * spend) and refuses otherwise with nothing written; the reader keeps the
+ * default for an unset or unreadable value and says whether the cap is the
+ * user's (an unpriced model is refused only under a user cap).
+ * Fails when: a negative, empty or non-numeric cap is accepted, 0 is refused,
+ * a key is missing from KNOWN_CONFIG_KEYS, or an unset cap reads as 0.
+ * PGLite in-memory ($0).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
+import {
+ FENCE_CONFIG_KEYS, FENCE_REPAIR_MAX_USD_PER_DAY_KEY, FENCE_REPAIR_MAX_USD_PER_PAGE_KEY, readFenceRepairCaps, validateFenceConfigValue,
+} from '../src/core/fence-repair/config.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => { await engine.disconnect(); }, 60_000);
+
+describe('fence repair caps', () => {
+ test('both keys are registered and accept non-negative USD amounts, 0 included', () => {
+ for (const key of [FENCE_REPAIR_MAX_USD_PER_PAGE_KEY, FENCE_REPAIR_MAX_USD_PER_DAY_KEY]) {
+ expect(KNOWN_CONFIG_KEYS).toContain(key);
+ expect(FENCE_CONFIG_KEYS).toContain(key);
+ for (const ok of ['0', '0.05', '1.00', '12', ' 2.5 ']) expect(validateFenceConfigValue(key, ok)).toBeNull();
+ for (const bad of ['-1', '-0.01', '', 'abc', '1e3', '0x10', 'Infinity', 'true', '1.']) {
+ expect(validateFenceConfigValue(key, bad)).toBe(`${key} must be a non-negative USD amount such as 0.05 (0 means no model spend on fence repair; got "${bad}"). Nothing was written.`);
+ }
+ }
+ expect(validateFenceConfigValue('fences.normalize', 'false')).toBeNull();
+ expect(validateFenceConfigValue('fences.normalize', '0.05')).toContain('must be true or false');
+ expect(validateFenceConfigValue('fences.repair.max_usd', '1')).toContain('Unknown config key');
+ });
+
+ test('the reader keeps the defaults until the user sets a cap, and reports whose cap it is', async () => {
+ expect(await readFenceRepairCaps(engine)).toEqual({ perPageUsd: 0.05, perDayUsd: 1, perPageSource: 'default', perDaySource: 'default' });
+ await engine.setConfig(FENCE_REPAIR_MAX_USD_PER_DAY_KEY, '0');
+ await engine.setConfig(FENCE_REPAIR_MAX_USD_PER_PAGE_KEY, '0.2');
+ expect(await readFenceRepairCaps(engine)).toEqual({ perPageUsd: 0.2, perDayUsd: 0, perPageSource: 'user', perDaySource: 'user' });
+ await engine.setConfig(FENCE_REPAIR_MAX_USD_PER_PAGE_KEY, 'garbage');
+ expect((await readFenceRepairCaps(engine)).perPageUsd).toBe(0.05);
+ const failing = { getConfig: async () => { throw new Error('config table unavailable'); } };
+ expect(await readFenceRepairCaps(failing)).toEqual({ perPageUsd: 0.05, perDayUsd: 1, perPageSource: 'default', perDaySource: 'default' });
+ });
+});