Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(fence-repair): route every fence hold to gbrain repair fences with a fix by state; fence_integrity wave check and banner (#6188)
garrytanb2ab4f7aea4a
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex bd19d11244..f76b69fe5b 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -20,15 +20,15 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/checks/auto-chronicle.ts` — `auto_chronicle`, `chronicle_config_invalid` and `auto_chronicle_default_on` (#5876), registered after `unlinked_facts`, config-plane only (no provider calls). `auto_chronicle`: off by choice is ok with `severity: info`, `readiness: disabled_by_choice`; an invalid word warns `auto_chronicle_invalid`; when on it reads `core/chronicle/ledger-stats.ts` and warns `judge_llm_unavailable` (pending pages, no chat provider) or the top failure reason with that reason's fix, else reports ok with 24 h use of the daily limit, the largest writer's share, 7-day outcomes and spend, and `gbrain dream --phase chronicle`. Every warn carries `details.fix` (an Action: argv/consent/actor) and `fix_hint`. `chronicle_config_invalid` warns on an out-of-range stored `chronicle.*` value. `auto_chronicle_default_on` is ok/info with `ask_user` and keep/opt-out decisions until `gbrain config set auto_chronicle` acknowledges. Test: `test/auto-chronicle-surfaces-5876.test.ts`.- `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/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 each source's repair command from the hold router (`holdRepairSteps`: `gbrain repair frontmatter --source <id>`, `gbrain repair fences --source <id>` for `invalid_fence` holds, both for a mixed source; with fence holds the details add `fences` and `auto_repair`, and the banner line names the fence repair through the wave entry's `bannerHow`); `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. `fenceHoldsBannerNote` (a separate `POST_UPGRADE_NOTES` entry, #6188 D7) names sources whose cursor stopped on a fence receipt (typed or the message an older gbrain stored): the next sync recovers them with no command, `gbrain sync --source <id> --no-pull` does it now, the malformed fences the stored census knows and whether the next maintenance run repairs them, the read-only `gbrain repair fences` preview and the pause command `gbrain config set fences.repair.enabled false`; never an applying command. Tests: `test/doctor-frontmatter-holds.test.ts`, `test/persistence-sync-fence-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 read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). 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, `bannerHow` when a finding's details change the banner's parenthetical, `registration` inline-in-doctor.ts or from this table). `fence_integrity` (#6188, `repair`, registered inline) counts `details.total`; its banner line says "repaired automatically by the next maintenance run" while one is active (from `details.auto_repair`), else why not, with `gbrain repair fences` as the preview; a fence-only `git_held_files` finding gets the same wording, a mixed one adds it to the frontmatter preview. `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; a repair step with `llm_usd` names its paid chat model spend, and any embedding part, in its fix and plan line), `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`.- `src/commands/doctor/checks/global-maintenance-timeouts.ts` — `global_maintenance_timeouts` (#4578): warns when the last three finished `autopilot-global-maintenance` jobs died at their deadline, or one phase was running in three consecutive job deaths (read from config `autopilot.global_maintenance.progress`). Details carry `code`, `cause`, `fix` (`gbrain dream --phase <name>`, else the deadline config key) and the `docs/guides/troubleshooting.md#global-maintenance-timeouts` anchor. Pinned by `test/autopilot-global-maintenance-resume-4578.test.ts`.- `src/commands/doctor/checks/legacy-job-authority.ts` — `legacy_job_authority` (#5157): the claim gate's population (`UNREVIEWED_LIVE_JOBS_WHERE`), split into authorizable SQL NULL and unsupported rows; terminal keyed SQL NULL rows are reported as `ok`. Live rows `fail` with the filled recovery. `legacyJobAuthorityBannerNote` feeds the banner. The same check counts queued paid jobs by spend basis (`details.queued_spend`) and warns, with the read-only fix `gbrain jobs list --status waiting --json`, when spend-authorized rows wait over 10 minutes while registered workers run (an un-upgraded worker is fenced off them); `legacyDefaultSpendBannerNote` names queued `legacy_default` rows after an upgrade. Tests: `test/doctor-legacy-job-authority.test.ts`, `test/doctor-queued-spend.test.ts`.-- `src/commands/doctor/upgrade-banner.ts` — `postUpgradeRecoveryBanner`: runs the wave checks once and returns one `[AGENT] Relay this to your operator` block (brain, per-finding count and resolution, the read-only `gbrain doctor --remediation-plan`, ask before applying), never an applying command; empty for a clean brain. `POST_UPGRADE_NOTES` lets other subsystems add lines. Test: `test/post-upgrade-banner.test.ts`.+- `src/commands/doctor/upgrade-banner.ts` — `postUpgradeRecoveryBanner`: runs the wave checks once and returns one `[AGENT] Relay this to your operator` block (brain, per-finding count and resolution, refined by the check's `bannerHow`, the read-only `gbrain doctor --remediation-plan`, ask before applying), never an applying command; empty for a clean brain. `POST_UPGRADE_NOTES` lets other subsystems add lines (`fenceHoldsBannerNote` among them). Test: `test/post-upgrade-banner.test.ts`.- `src/commands/doctor/checks/{safe-index,self-capture,stale-embedding-effects}.ts` — `safe_index_pending` (BRAIN: re-sealable pages below the safe-chunk fence, names `gbrain repair safe-chunks`; kept code/image pages are informational), `self_capture` (BRAIN, #5413: corpus `.txt` files whose session id matches a gbrain claude-cli scratch transcript are classified, ones with no harness transcript left are unclassifiable; classification is `isClaudeCliSelfSessionId`; details carry `newest_capture_at`, a capped sample and copy-paste quarantine commands into `<corpus>.quarantine`, and the message says new captures stopped (#5820) so only the existing files need one quarantine; never moves or deletes), `stale_embedding_effects` (OPS, #5629: committed writes with a queued embedding effect untouched for an hour; names each effect with its inspect command; reported as unsupported). Unreadable state is warn with `details.health: 'unknown'`. `writer_version` (`checks/writer-version.ts`, owned by the persistence entry) is registered in the same table as operator-required. Tests: `test/doctor-self-capture.test.ts`, `test/recovery-layer.test.ts`.diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 1ec63b309e..a7032a1a4b 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -5,11 +5,12 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELManaged connector ingestion, connector item holds, sync checkpoint validation and the no-op kernel. Also the persistence verb types and errors, database-write and manual links, write attribution, purge-deleted and loop-fact retirement.- `src/core/fence-repair/refusal.ts` — #6188 the one fence check coordinated writers share. `scanCanonicalFences` decides from the strict parsers what the canonical projection refuses (a repeated marker outside code, any parser warning, a row number used twice on the page) and locates each defect from the raw-row view (`raw-rows.ts`, `schema.ts`), never from parser warning strings, which embed row text; reasons and messages come from `reasons.ts` (`FENCE_REASONS`, `fenceMessage`, `issueLocation`). `fenceOperationError` is the typed refusal (`invalid_fence`, wire `invalid_params`, or `take_row_collision` for a stored-row collision). `fenceFailureDetail` is the bounded, versioned `error_detail.fence` a failed receipt keeps through compaction; `fenceReceiptLocation` reads a receipt back from that detail, the message grammar or an older release's exact message, and never from an arbitrary `invalid_params`. `completeFenceLocation` names the section of a legacy receipt from the refused bytes. Tests: `test/fence-refusal.test.ts`, `test/fence-hold-surfaces.test.ts`, `test/persistence-sync-fence-holds.test.ts` (PGLite and Postgres).-- `src/core/fence-repair/{types,schema,raw-rows,reasons}.ts` — #6188 the shared fence vocabulary, all location-only. `types.ts`: `FenceIssue`, `FenceFix`, `FenceCtx`, `FenceReason`, `FixClass`. `schema.ts`: canonical columns, accepted widths (facts 9/10/14, takes 6/7/13), header aliases, enum and kind synonym tables (exported for the format reference), cell validity. `raw-rows.ts`: `extractRawRows` reads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row is `accepted` exactly when the strict parser returns it. `reasons.ts`: `FENCE_REASONS` (tier, auto-retry, actor, fix template, docs anchor per reason; the registry's `invalid_fence.reasons`) and `fenceMessage`. Tests: `test/fence-repair-raw-rows.test.ts`, `test/fence-repair-reasons.test.ts`.+- `src/core/fence-repair/{types,schema,raw-rows,reasons}.ts` — #6188 the shared fence vocabulary, all location-only. `types.ts`: `FenceIssue`, `FenceFix`, `FenceCtx`, `FenceReason`, `FixClass`. `schema.ts`: canonical columns, accepted widths (facts 9/10/14, takes 6/7/13), header aliases, enum and kind synonym tables (exported for the format reference), cell validity. `raw-rows.ts`: `extractRawRows` reads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row is `accepted` exactly when the strict parser returns it. `reasons.ts`: `FENCE_REASONS` (tier, auto-retry, actor, fix template, docs anchor per reason; the registry's `invalid_fence.reasons`; templates a repair can clear name the read-only `gbrain repair fences` preview) and `fenceMessage`. Tests: `test/fence-repair-raw-rows.test.ts`, `test/fence-repair-reasons.test.ts`.- `scripts/build-fence-format.ts` — #6188 renders the generated region of `docs/guides/fence-format.md` (between `BEGIN/END GENERATED fence-format`) from the fence constants: markers, the column tables and layouts from `schema.ts` (`COLUMNS`, `BASE_WIDTH`, `MIN_CELLS`, `CANONICAL_HEADER`, `ALLOWED`, `COLUMN_DEFAULTS`, `NAMED_COLUMNS`, `TOLERATED_TRAILING`, `HEADER_ALIASES`), holder outcomes computed with `isValidHolder`/`holderAlias`, the Tier 1 rule table from the synonym tables (bound to `FixClass` by `satisfies`), screen reasons grouped by tier and the gate table from `reasons.ts`. It parses both synthetic examples with the strict parsers and throws on any warning. `--check` exits 1 when the committed region is stale. Drift test: `test/fence-format-reference.test.ts` (the region, the examples, the reference's links, and one `fence-<reason>` row per reason in `write-refusals.md` with the reason table's tier and auto-retry and a link into the reference).- `src/core/fence-repair/{normalize,structure,content,rules}.ts` — #6188 Tier 1. `normalizeFences(page, ctx)` returns a page that compiles plus location-only fixes and residual issues; a page whose fences compile comes back as the same object, and only edited cells, markers and headers change (no table is re-rendered). `structure.ts` closes a fence only when nothing but blank lines follows its last row and fixes two-dash takes markers; `content.ts` rewrites headers into canonical order with header-level defaults and renumbers prior-aware across both sections (`nextFreeRowNum`: above every fence and stored number; hidden rows never move); `rules.ts` holds the cell rules (kind map with the original word kept in `context`, enum and holder synonyms, percent confidence). `safeNormalizeFences` turns a throw into residual `normalizer_failed`. Tests: `test/fence-repair-normalize.test.ts`, `test/fence-repair-fixtures.test.ts`.- `src/core/fence-repair/{validate,validate-cells,page-checks}.ts` — #6188 the one gate every tier's output passes before a write: (a) compiles, (e) row count and containment, (b) claims, (c) existing row numbers, (d) visibility only tightens, (f) per-row cell preservation with rule-produced changes only, (g) nothing the privacy boundary hid is shown; gates (b), (c), (e) and (f) read the raw-row view. `isFenceFixedPoint` is E14. `page-checks.ts` holds `strictFailures` (gate a, the projection's three checks) and `exposedLines` (gate g). Tests: `test/fence-repair-validate.test.ts`.- `src/core/fence-repair/{tier1,import-step,config,report}.ts` — #6188 Tier 1 on every write path. `fenceStep(page, ctx, { normalize })` is the step the coordinated screen, `importFromContent` and the append verbs share: no work beyond a marker substring check for a page with no fence, one shared scan when the fences compile, and `normalized` only when the validator passes and the output is a fixed point; otherwise `residual` with issues and the refusal location (`fenceIssuesWire` is the D18 `fence_issues` shape). `import-step.ts`: `applyImportFences` runs inside `importFromContent` before the remote hidden-row merge and withdrawal preservation (E7), reusing the screen's verdict unless hidden rows or a planned `renumber` need the database (stored rows load only then); `normalizeTargetFences` normalizes an append verb's target page or throws `target_fence_malformed` for a residual in its own fence kind; `normalizePageFences` serves synthesize verify. `config.ts`: `fences.normalize` (default on, read only when there is something to fix) and the model-repair caps `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00), validated at `config set` as non-negative USD (0 = no model spend) and read by `readFenceRepairCaps` (stored value = a user cap). `report.ts`: the one `fences_normalized` shape (count, by_class, writers, sample paths for local callers, coaching fix), the `fence_normalized` coaching notice and the per-file import tally (`fence_issues` for lenient imports). Tests: `test/fence-write-verbs.test.ts`, `test/persistence-sync-fence-holds.test.ts`, `test/fence-normalize-overhead.slow.test.ts`.+- `src/core/fence-repair/hold-fix.ts` — #6188 (D16, D17, E35, Codex CEO #7) what an `invalid_fence` sync hold tells an agent. `readFenceAutoRepair` (two reads: `fences.repair.enabled`, `fences.repair.llm` and `autopilot.last_global_at` from `config`, plus the last completed `autopilot-global-maintenance` job) says whether the maintenance run repairs fences by itself (active within `FENCE_MAINTENANCE_ACTIVE_MS`, 24 h). `fenceHoldStatus` derives the state from the reason table and `meta.fence_repair`: `auto` (no action needed, the read-only preview), `apply` (preview, then apply), `manual` (manual-only reason, gate rejection or a model failure the run does not retry: the preview names the edit, then the sync), `paid` (`budget_exhausted`, `llm_disabled`, `no_pricing`: the exact config or `pricing set` command with consent `paid`), `owner` (the owner-host command, actor `host_admin`). `fenceHoldFix` is the local fix (`gbrain repair fences --source <id> --only <path>`), `fenceHoldRelay` the remote one (`tell_user_to_run`, no path), `fenceHoldLocation` the D16 object, `fenceFileLine` the file line of a section line. Location only. Tests: `test/fence-hold-surfaces.test.ts`, `test/sync-hold-surfaces.test.ts`.- `src/core/fence-repair/{census,census-store}.ts` — #6188 the fence census: discovery only, nothing repairs. `runFenceCensus(engine, { sourceIds, deadline, now })` advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill over `pages.id`, then incremental passes over `updated_at >= watermark`, where each new watermark is the previous pass's start minus the oldest open writer transaction in `pg_stat_activity` and `LATE_COMMIT_GRACE_MS`, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk of `isFrontmatterScannablePath` files via `collectGitVisibleFiles`/`walkDir`, then only `git diff <walked commit>` files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the census `partial`. `judgeFences` runs the coordinated `fenceStep` (normalization on): `deterministic` when Tier 1 fixes it, else the highest `FENCE_REASONS` tier of its residual reasons (`reasonTier`; manual-only or page-dependent counts as manual). `listFenceCandidates` dedupes by page slug across `invalid_fence` holds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/`updated_at`/`content_hash`, file sha256/mtime, hold `upstream_version`); `summarizeFenceCensus` counts per source by bucket and tier with the oldest hold and scan state. `census-store.ts`: `op_checkpoints` rows `fence-candidate` (one per source incarnation and slug, `page`/`file` parts), `fence-scan` (cursors and last census) and `fence-trend` (one row per sync run, keyed by run id: a managed run's total is rewritten in the same transaction as each cursor step that changes it, so the trend never differs from the cursor, and a legacy run writes its total when it ends; plus one row per normalized page write via `recordPublicationFenceTrend`, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests: `test/fence-census.test.ts` (+ `test/e2e/fence-census-postgres.test.ts`), `test/doctor-fence-integrity.test.ts`.- `src/core/fence-repair/{llm,repair-tiers}.ts` — #6188 Tier 2 and Tier 3 for one candidate. `analyzeFences`: Tier 1 (`safeNormalizeFences`, stored rows loaded only for `renumber`), Tier 2 (`resolveStrictEntityReference` without the same-name arm per `holder_unresolved` cell, only `people/`/`companies/` slugs, private pages excluded on a world page; hits feed `verifiedHolders`), then `proposal` (validated by gates (a)-(g) and a fixed point), `llm` (only `TIER3_REASONS` residuals left; a fence with stray text lines or no end marker is not eligible) or `manual`. `llm.ts`: `tier3Requests` (per fence: the header line and the residual rows, every row for a fence-level issue), `buildTier3Prompt` (schema, vocabulary, reason codes, page visibility; pinned by a prompt-bytes digest and `FENCE_REPAIR_PROMPT_VERSION`), `callTier3` (gateway `chat`, no tools, no fallback, thinking off; `llm_unavailable` when the provider throws, `llm_refused`, `llm_truncated` for any stop but a normal end, `llm_malformed`/`llm_empty` from `extractSingleTable`, a wrong row count is a gate (e) failure), `spliceTier3` (rebuilds only that fence: canonical header, then every row in order with the sent rows replaced). `runTier3` claims the attempt (a rejected memo returns its verdict), checks the per-page cap and the run allowance, reserves on the daily ledger before each call (a refusal stops the run), settles actual tokens (an answerless call at its estimate), normalizes and validates the spliced page against the bytes as read, and re-asks once with the failed gate letter and rows. Tests: `test/fence-repair-llm.test.ts`, `test/repair-fences.test.ts`.- `src/core/fence-repair/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource`: managed owner root (or `ownerElsewhere`), legacy checkout, mirror flag, unfinished managed sync cursor and the paths/slugs pending writes name. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `git add`/`git commit` step, dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex 0a46b8a1f7..8b182fa072 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -21,7 +21,7 @@- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading.- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must be committed; a failed one cancels the group, a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts cancels, releases or falls back to the single path, and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.-- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, line) and `fence_version`; the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence holds read the page, edit the named fence and sync with `--no-pull`, other holds preview `gbrain repair frontmatter`, a mixed source names both. `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator. Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.+- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence holds preview `gbrain repair fences --source <id>`, other holds preview `gbrain repair frontmatter`, a mixed source names both. One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. A fence repair (`gbrain repair fences`) passes its `FenceRepairReceipt` as `fenceRepair`: submission and the preparer refuse (`invalid_params`, nothing written) a receipt `parseFenceRepairReceipt` rejects or whose `before_sha256`/`after_sha256` are not the previewed and written bytes; the outcome carries it as `fence_repair`, the file target carries the commit note from `fenceRepairCommit` (`effect-model.ts`), and every refusal and fix names `gbrain repair fences --source <id>` instead of `gbrain repair frontmatter` (`FileRepairKind`, also taken by `confinedRepairTarget` and `managedRepairRoot`). Tests: `test/repair-frontmatter.test.ts`, `test/fence-repair-receipts.test.ts`.- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` (then the mention pass unless `mentions: false`, which sync passes) derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.diff --git a/src/commands/doctor/checks/fence-integrity.ts b/src/commands/doctor/checks/fence-integrity.tsindex a4c7aa1236..81bd7334e0 100644--- a/src/commands/doctor/checks/fence-integrity.ts+++ b/src/commands/doctor/checks/fence-integrity.ts@@ -10,8 +10,13 @@* 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.+ * ok; the next run resumes where it stopped. The fix is the read-only+ * `gbrain repair fences --source <id>` preview for holds, stored pages and+ * files alike; what the next maintenance run repairs automatically is said+ * so (only while one is active and `fences.repair.enabled` is on), and why+ * model-tier fences wait when `fences.repair.llm` is off or today's budget is+ * spent. 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';@@ -21,6 +26,7 @@ import { runFenceCensus, summarizeFenceCensus, type SourceCensus, type TierCountimport { 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 { fencePreviewArgv, readFenceAutoRepair, type FenceAutoRepair } from '../../../core/fence-repair/hold-fix.ts';import { dailyLedger, FENCE_REPAIR_LEDGER } from '../../../core/budget/daily-ledger.ts';/**@@ -56,28 +62,43 @@ function sourceLine(census: SourceCensus, now: number): string {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 });+/** Whether the maintenance run repairs fences by itself: "repaired automatically by the next maintenance run", or why not. */+function automaticRepair(auto: FenceAutoRepair): string {+ if (auto.active) return 'repaired automatically by the next maintenance run';+ return `not repaired automatically (${auto.enabled ? 'no maintenance run has completed in the last 24 h' : 'fences.repair.enabled is false'})`;+}++/**+ * The next step for one source: the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike.+ * With no active maintenance run, `then` applies the plan (the preview prints the `--expect <hash>` form).+ */+function sourceFix(census: SourceCensus, auto: FenceAutoRepair) {+ const preview = fencePreviewArgv(census.source_id);+ const manual = census.by_tier.manual;+ const why = `Previews the repair of each malformed fence of ${census.source_id} (read-only, no model call): its planned tier and diff, the estimated model cost, or the exact edit for a fence gbrain will not guess; it prints the apply command with --expect <hash>. `+ + (auto.active ? `Everything but the manual ones is ${automaticRepair(auto)}, so no action is needed for those.` : `They are ${automaticRepair(auto)}, so apply the plan with the command the preview prints.`)+ + (manual ? ` ${manual} need a manual edit: make the edit the preview names in the file (or the page), commit, then sync.` : '');+ return agentFix(preview, why, 'fence_integrity', { docs: 'docs/guides/repair.md#fences',+ ...(auto.active ? {} : { then: agentFix([...preview, '--apply'], `Applies the current repair plan of ${census.source_id}; the command the preview prints adds --expect <hash>, which applies exactly what it showed.`, 'fence_integrity') }) });+}++/** Why model-tier fences wait, or the caps when nothing stops them. */+function modelRepairSentence(caps: { perPageUsd: number; perDayUsd: number }, today: { committedUsd: number; reservedUsd: number } | null, auto: FenceAutoRepair, llm: number): string {+ if (!auto.llm) return `Model repair (Tier 3) is off (fences.repair.llm false), so ${llm} model-tier fence(s) wait for a manual edit; turning it on is the user's call (gbrain config set fences.repair.llm true).`;+ if (caps.perDayUsd === 0) return 'Model repair spend is off (fences.repair.max_usd_per_day 0).';+ if (today && today.committedUsd + today.reservedUsd >= caps.perDayUsd) {+ return `Today's model repair budget is spent ($${today.committedUsd.toFixed(2)} of $${caps.perDayUsd.toFixed(2)}), so ${llm} model-tier fence(s) wait until after 00:00 UTC; `+ + 'raising it is the user\'s call (gbrain config set fences.repair.max_usd_per_day <usd>).';}- 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 });+ return `Model repair caps: $${caps.perPageUsd.toFixed(2)} per page, $${caps.perDayUsd.toFixed(2)} per day${today ? ` ($${today.committedUsd.toFixed(2)} spent today)` : ''}.`;}-/** The check's verdict after a bounded census scan. */-export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutMs?: number; now?: () => Date } = {}): Promise<Omit<Check, 'name'>> {+/** The check's verdict after a bounded census scan (`sourceIds`: only those sources, for a scoped remote caller). */+export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutMs?: number; now?: () => Date; sourceIds?: string[] } = {}): Promise<Omit<Check, 'name'>> {const now = opts.now ?? (() => new Date());const timeoutMs = opts.timeoutMs ?? fenceScanTimeoutMs();- const runs = await runFenceCensus(engine, { deadline: now().getTime() + timeoutMs, now });- const census = await summarizeFenceCensus(engine, undefined, runs);+ const runs = await runFenceCensus(engine, { deadline: now().getTime() + timeoutMs, now, ...(opts.sourceIds ? { sourceIds: opts.sourceIds } : {}) });+ const census = await summarizeFenceCensus(engine, opts.sourceIds, runs);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) ?? []));@@ -95,14 +116,16 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutMif (!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 auto = await readFenceAutoRepair(engine, now());const at = now().getTime();const sentences: string[] = [];if (total) {+ const manual = waiting.reduce((sum, c) => sum + c.by_tier.manual, 0);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)` : ''}.`);+ + `${manual < total ? `The ${auto.llm ? 'deterministic, resolver and model-tier' : 'deterministic and resolver'} ones are ${automaticRepair(auto)}` : 'All of them need a manual edit'}`+ + `${manual && manual < total ? `; ${manual} need the manual edit the preview names` : ''}. None of them blocks a sync. Preview: ${waiting.map(c => fencePreviewArgv(c.source_id).join(' ')).join('; ')}.`);+ const llm = waiting.reduce((sum, c) => sum + c.by_tier.llm, 0);+ if (llm) sentences.push(modelRepairSentence(caps, today, auto, llm));}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`@@ -114,11 +137,16 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM+ '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)+ const fix = first ? sourceFix(first, auto): 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(' ') };+ return { status: 'warn', details: { ...details, auto_repair: auto }, fix, message: sentences.join(' ') };+}++/** The wave check (`WAVE_CHECKS`): the same verdict, scoped to `sourceIds` when a remote caller is. */+export async function fenceIntegrityCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ return { name: 'fence_integrity', ...await fenceIntegrityResult(engine, sourceIds ? { sourceIds } : {}) };}async function runFenceIntegrity(ctx: DoctorContext): Promise<Check[]> {diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.tsindex 4cdc1af583..cd6e064adb 100644--- a/src/commands/doctor/checks/git-holds.ts+++ b/src/commands/doctor/checks/git-holds.ts@@ -3,6 +3,8 @@ import type { Check } from '../../doctor.ts';import { gitHoldFix, holdRepairSteps, readGitHoldListing, readGitImageHoldCounts, readSyncHoldPolicy } from '../../../core/persistence/sync-holds.ts';import { coverageRoute, readHeldCoverage } from '../../../core/persistence/held-reads.ts';import { fenceReceiptLocation } from '../../../core/fence-repair/refusal.ts';+import { readFenceAutoRepair, type FenceAutoRepair } from '../../../core/fence-repair/hold-fix.ts';+import { summarizeFenceCensus } from '../../../core/fence-repair/census.ts';import { agentFix } from '../check-fix.ts';import { isContentRefusal } from '../../../core/import-screen.ts';@@ -15,28 +17,32 @@ const SAMPLE_PATHS = 5;* holds stay on `connector_held_items`. Warns per source with the missing and* stale counts, the first paths with their code and next step (the check is* host-only, so paths never reach a remote caller), and each source's next- * step from the hold router (D6: frontmatter repair preview, the fence edit- * and sync, or both); fails once a source carries more holds than+ * step from the hold router (D6: the frontmatter repair preview, the fence+ * repair preview, or both); fails once a source carries more holds than* `sync.hold_escalate_count`, the same count rule that escalates a sync result.- * Unsupported-image holds (#5493) are listed but never escalate.+ * Unsupported-image holds (#5493) are listed but never escalate. With fence+ * holds, details carry `fences` and `auto_repair` (whether the maintenance run+ * repairs them by itself), which the post-upgrade banner reads.*/export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {try {const [coverage, policy] = await Promise.all([readHeldCoverage(engine, sourceIds ? { sourceIds } : {}), readSyncHoldPolicy(engine)]);const listing = new Map((await readGitHoldListing(engine, coverage.map(source => source.source_id), SAMPLE_PATHS)).map(entry => [entry.sourceId, entry.holds]));const images = await readGitImageHoldCounts(engine, coverage.map(source => source.source_id));+ const fences = coverage.reduce((sum, source) => sum + coverageRoute(source).fences, 0);+ const auto = fences ? await readFenceAutoRepair(engine) : undefined;const sources = coverage.map(source => {const route = coverageRoute(source);- const steps = holdRepairSteps(source.source_id, route);+ const steps = holdRepairSteps(source.source_id, route, auto);return { source_id: source.source_id, held: source.missing + source.stale, stale: source.stale, missing: source.missing, ...(route.fences ? { fences: route.fences } : {}),- first: (listing.get(source.source_id) ?? []).map(hold => ({ path: hold.path, code: hold.code, ...(hold.meta.reason ? { reason: hold.meta.reason } : {}), why: gitHoldFix(hold).why })),+ first: (listing.get(source.source_id) ?? []).map(hold => ({ path: hold.path, code: hold.code, ...(hold.meta.reason ? { reason: hold.meta.reason } : {}), why: gitHoldFix(hold, auto).why })),escalated: source.missing + source.stale - (images.get(source.source_id) ?? 0) > policy.escalateCount,- status: `gbrain sources status ${source.source_id}`, repair: route.others ? `gbrain repair frontmatter --source ${source.source_id}` : `gbrain sync --source ${source.source_id} --no-pull`,+ status: `gbrain sources status ${source.source_id}`, repair: steps.commands.join('; '),argv: steps.argv, next: steps.text };});const held = sources.reduce((sum, source) => sum + source.held, 0);const details = { held, source_ids: sources.map(source => source.source_id), sources: sources.map(({ argv: _argv, ...source }) => source), escalate_count: policy.escalateCount,- docs: 'docs/guides/repair.md#held-files' };+ ...(fences ? { fences, auto_repair: auto } : {}), docs: 'docs/guides/repair.md#held-files' };if (!held) return { name: 'git_held_files', status: 'ok', message: 'No Git source files are held.', details };const escalated = sources.filter(source => source.escalated);const single = sources.length === 1 ? sources[0]! : undefined;@@ -51,12 +57,14 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[+ `Inspect with ${sources.map(source => source.status).join('; ')}; `+ (sources.some(source => source.fences) ? `then ${sources.map(source => `${source.source_id}: ${source.next}`).join('; ')}.` : `preview the fix with ${sources.map(source => source.repair).join('; ')}.`),fix: single- ? agentFix(single.argv, fenceOnly ? `Lists each held file of ${single.source_id} with the fence and reason that hold it; edit that fence in the file, commit, then run gbrain sync --source ${single.source_id} --no-pull.`- : 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing.', 'git_held_files', { docs: 'docs/guides/repair.md#held-files' })- : agentFix(fenceOnly ? ['gbrain', 'sources', 'status', '--json'] : ['gbrain', 'repair', 'frontmatter'],- fenceOnly ? 'Lists each held file with the fence and reason that hold it; edit that fence in the file, commit, then sync its source with --no-pull.'- : 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing. Fence holds are listed by gbrain sources status and fixed by editing the named fence.',- 'git_held_files', { docs: 'docs/guides/repair.md#held-files' }),+ ? agentFix(single.argv, fenceOnly ? `Previews the fence repair of each held file of ${single.source_id} (read-only, no model call): ${single.next}.`+ : 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing.',+ 'git_held_files', { docs: fenceOnly ? 'docs/guides/repair.md#fences' : 'docs/guides/repair.md#held-files' })+ : agentFix(fenceOnly ? ['gbrain', 'repair', 'fences'] : ['gbrain', 'repair', 'frontmatter'],+ fenceOnly ? `Previews the fence repair of every held file (read-only, no model call) with each one's planned repair or exact edit, and prints the apply command with --expect <hash>. ${fenceAutoSentence(auto)}`+ : 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing. '+ + `Fence holds are previewed by gbrain repair fences instead. ${fenceAutoSentence(auto)}`,+ 'git_held_files', { docs: fenceOnly ? 'docs/guides/repair.md#fences' : 'docs/guides/repair.md#held-files' }),};} catch (error) {return { name: 'git_held_files', status: 'warn', fix_unavailable_reason: 'check_errored',@@ -65,9 +73,16 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[}}+/** Whether the maintenance run repairs fence holds by itself, as one sentence ('' when nothing says). */+function fenceAutoSentence(auto: FenceAutoRepair | undefined): string {+ if (!auto) return '';+ return auto.active ? 'The next maintenance run repairs the fence holds it can by itself.'+ : `Nothing repairs fence holds by itself (${auto.enabled ? 'no maintenance run is active' : 'fences.repair.enabled is false'}), so apply the plan the preview prints.`;+}+/*** Sources whose unfinished managed sync cursor is stopped on a failed content refusal (fixed by the next sync, which converts it in place).- * `fence` marks a source whose refusal is a facts or takes fence (#6188); it is held and fixed by editing the fence, not by frontmatter repair.+ * `fence` marks a source whose refusal is a facts or takes fence (#6188); it is held and repaired by `gbrain repair fences`, not by frontmatter repair.*/export async function contentBlockedSources(engine: BrainEngine): Promise<Array<{ source_id: string; fence: boolean }>> {const rows = await engine.executeRaw<{ source_id: string; error_code: string | null; error_message: string | null; error_detail: unknown }>(`SELECT c.completed_keys->0->>'sourceId' AS source_id,@@ -105,16 +120,23 @@ export async function frontmatterHoldsBannerNote(engine: BrainEngine): Promise<s}/**- * #6188 `gbrain post-upgrade` line, separate from the frontmatter one: a+ * #6188 (D7) `gbrain post-upgrade` line, separate from the frontmatter one: a* source blocked by a malformed facts or takes fence (a typed receipt or the- * message an older gbrain stored) recovers on its next sync with no command:- * the file is held and the rest of the source imports. Null when none is.+ * message an older gbrain stored) recovers on its next sync with no command+ * (the file is held and the rest of the source imports), the malformed fences+ * the stored census knows and whether the next maintenance run repairs them,+ * the read-only preview and the pause setting. Never an applying command.+ * Null when no source is blocked.*/export async function fenceHoldsBannerNote(engine: BrainEngine): Promise<string | null> {const ids = (await contentBlockedSources(engine)).filter(source => source.fence).map(source => source.source_id);if (!ids.length) return null;+ const [auto, census] = await Promise.all([readFenceAutoRepair(engine), summarizeFenceCensus(engine).catch(() => [])]);+ const malformed = census.reduce((sum, source) => sum + source.total, 0);+ const repair = auto.active ? 'the next maintenance run repairs them automatically (the manual ones are listed with the exact edit)'+ : `nothing repairs them by itself until a maintenance run is active${auto.enabled ? '' : ' and fences.repair.enabled is true again'}, so preview them and apply the plan the preview prints once the user agrees`;return `fence_holds: ${ids.length} source(s) are blocked by a file whose facts or takes fence gbrain could not import (${ids.join(', ')}). The next scheduled or manual sync `- + `recovers each automatically; to do it now run ${ids.map(id => `gbrain sync --source ${id} --no-pull`).join('; ')}. The file is then held and the rest of the source imports; `- + `${ids.map(id => `gbrain sources status ${id}`).join('; ')} names the file, fence and reason. Read the page with gbrain get --source <id> -- <slug>, edit that fence in the file, `- + 'commit, and sync again; frontmatter repair does not change fences. Recipe: docs/guides/live-sync.md#held-files';+ + `recovers each with no command; to do it now run ${ids.map(id => `gbrain sync --source ${id} --no-pull`).join('; ')}. The file is then held and the rest of the source imports. `+ + `${malformed} malformed fence(s) are known so far (gbrain doctor --only fence_integrity counts them by tier); ${repair}. `+ + 'Preview (read-only, no model call): gbrain repair fences. Pause automatic fence repair first with: gbrain config set fences.repair.enabled false. Recipe: docs/guides/repair.md#fences';}diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.tsindex 7940f08f92..3a33401acb 100644--- a/src/commands/doctor/remediate.ts+++ b/src/commands/doctor/remediate.ts@@ -332,7 +332,7 @@ export function classifyWaveFindings(before: WaveFinding[], after: WaveFinding[]if (now.state === 'unknown') { findings.push({ ...base, class: 'pending', instruction: 'The check could not run; rerun gbrain doctor on the brain host.' }); continue; }if (now.check.details?.partial === true) {findings.push({ ...base, class: 'pending', ...(kind ? { repair_kind: kind } : {}),- instruction: `The scan stopped at its deadline, so the finding is incomplete; raise GBRAIN_DOCTOR_FM_TIMEOUT_MS and rerun gbrain doctor --only ${now.spec.id} on the brain host.` });+ instruction: `The scan stopped at its deadline, so the finding is incomplete; raise ${now.spec.id === 'fence_integrity' ? 'GBRAIN_DOCTOR_FENCE_TIMEOUT_MS' : 'GBRAIN_DOCTOR_FM_TIMEOUT_MS'} and rerun gbrain doctor --only ${now.spec.id} on the brain host.` });continue;}if (now.spec.resolution === 'operator') { findings.push({ ...base, class: 'operator_required', instruction: now.spec.instruction }); continue; }diff --git a/src/commands/doctor/upgrade-banner.ts b/src/commands/doctor/upgrade-banner.tsindex b74b39cd6e..b7bf5d9c7f 100644--- a/src/commands/doctor/upgrade-banner.ts+++ b/src/commands/doctor/upgrade-banner.ts@@ -33,13 +33,14 @@ async function connectorRewalkNote(engine: BrainEngine): Promise<string | null>*/export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote, legacyJobAuthorityBannerNote, legacyDefaultSpendBannerNote, frontmatterHoldsBannerNote, fenceHoldsBannerNote];-/** One banner line for a non-ok wave finding. */+/** One banner line for a non-ok wave finding (a check's `bannerHow` refines the parenthetical, e.g. fences the maintenance run repairs). */export function bannerFindingLine({ spec, check, state }: WaveFinding): string {if (state === 'unknown') return `[AGENT] ${spec.id}: could not be checked (health unknown)`;const kind = waveRepairKind(spec);- const how = kind && repairSpec(kind).explicit_only ? `explicit_kind_required; preview with: ${repairPreviewCommand(kind, { source: findingSource({ check }) })}`+ const source = findingSource({ check });+ const how = kind && repairSpec(kind).explicit_only ? `explicit_kind_required; preview with: ${repairPreviewCommand(kind, { source })}`: spec.resolution === 'repair' ? 'repairable after the user agrees' : spec.resolution === 'operator' ? 'needs an operator action' : 'reported only; no command clears it yet';- return `[AGENT] ${spec.id}: ${spec.count(check.details ?? {})} (${how})`;+ return `[AGENT] ${spec.id}: ${spec.count(check.details ?? {})} (${spec.bannerHow ? spec.bannerHow(check.details ?? {}, how, source) : how})`;}export async function postUpgradeRecoveryBanner(engine: BrainEngine, brainLabel: string): Promise<string[]> {diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 15e0c6d401..b6e96cd85e 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -37,9 +37,26 @@ export interface WaveCheckSpec {hostOnly?: string;/** Items behind a finding, read from the check's details (host-side banners only). */count(details: Record<string, any>): number;+ /**+ * The banner's parenthetical when the finding's details change it: `how` is the+ * default from the resolution, `source` the one source the finding names.+ */+ bannerHow?(details: Record<string, any>, how: string, source?: string): string;run(engine: BrainEngine, scope: WaveScope): Promise<Check>;}+/**+ * #6188 (D7): what clears malformed fences, from a check's `auto_repair` detail: the next maintenance run while+ * one is active and `fences.repair.enabled` is on, otherwise `gbrain repair fences` (whose preview prints the apply command).+ */+function fenceRepairHow(details: Record<string, any>, source?: string): string {+ const preview = `preview with: gbrain repair fences${source ? ` --source ${source}` : ''}`;+ const auto = details.auto_repair as { active?: boolean; enabled?: boolean } | undefined;+ if (auto && auto.active === false) return `not repaired automatically (${auto.enabled === false ? 'fences.repair.enabled is false' : 'no maintenance run is active'}); ${preview}`;+ const manual = Array.isArray(details.sources) ? details.sources.reduce((sum: number, c: { by_tier?: { manual?: number } }) => sum + Number(c.by_tier?.manual ?? 0), 0) : 0;+ return `repaired automatically by the next maintenance run${manual ? `, except ${manual} that need a manual edit` : ''}; ${preview}`;+}+/** Checks that take one optional source id: run once brain-wide, or once per scoped source and merged. */async function perSource(scope: WaveScope, run: (sourceId?: string) => Promise<Check>): Promise<Check> {if (!scope.sourceIds) return run();@@ -105,8 +122,16 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [hostOnly: 'Held file paths are host-local; remote callers see held counts on sync results, get_page and search.',count: d => Number(d.held ?? 0),impact: 'Some Git source files are held instead of imported, so their pages are missing or keep an older revision',+ bannerHow: (d, how, source) => !d.fences ? how : d.fences >= Number(d.held ?? 0) ? `fence holds: ${fenceRepairHow(d, source)}` : `${how}; fence holds: ${fenceRepairHow(d, source)}`,run: async (engine, scope) => (await import('./checks/git-holds.ts')).gitHeldFilesCheck(engine, scope.sourceIds),},+ {+ id: 'fence_integrity', resolution: 'repair', registration: 'doctor.ts',+ count: d => Number(d.total ?? 0),+ impact: 'Some facts or takes fences are malformed and wait for repair; none of them blocks a sync',+ bannerHow: (d, _how, source) => fenceRepairHow(d, source),+ run: async (engine, scope) => (await import('./checks/fence-integrity.ts')).fenceIntegrityCheck(engine, scope.sourceIds),+ },{id: 'frontmatter_repairable', resolution: 'repair', registration: 'doctor.ts',hostOnly: 'The scan reads source checkouts on the brain host, and the frontmatter repair rewrites files there (explicit-only).',diff --git a/src/commands/sources-retry-held.ts b/src/commands/sources-retry-held.tsindex 8d5649c4b1..d394face57 100644--- a/src/commands/sources-retry-held.ts+++ b/src/commands/sources-retry-held.ts@@ -20,7 +20,8 @@ import type { Action } from '../core/agent-output.ts';import { OperationError } from '../core/ops/contract.ts';import { managedBrain, readAllSourceHolds, readHoldRetryKeys, requestHoldRetry, writeHeldRetryPointer } from '../core/connectors/item-holds-store.ts';import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';-import { holdRepairSteps, readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry } from '../core/persistence/sync-holds.ts';+import { fenceAutoRepairFor, holdRepairSteps, readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry } from '../core/persistence/sync-holds.ts';+import type { FenceAutoRepair } from '../core/fence-repair/hold-fix.ts';export interface RetryHeldReceipt {source_id: string;@@ -34,7 +35,7 @@ export interface RetryHeldReceipt {fix?: Action;}-interface Scheduled { items: Array<{ key: string; code: string; reason?: string; already: boolean }>; sync: string[] }+interface Scheduled { items: Array<{ key: string; code: string; reason?: string; already: boolean }>; sync: string[]; fenceAuto?: FenceAutoRepair }async function scheduleConnectorItems(engine: BrainEngine, sourceId: string, incarnation: string, dryRun: boolean): Promise<Scheduled> {const held = (await readAllSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.held ?? [];@@ -56,8 +57,9 @@ async function scheduleGitFiles(engine: BrainEngine, sourceId: string, incarnatiif (!held.length) return { items: [], sync };if (!dryRun) await requestGitHoldRetry(engine, sourceId, incarnation, held.map(record => record.path));const already = new Set(dryRun ? await readGitHoldRetryPaths(engine, sourceId, incarnation) : []);+ const fenceAuto = await fenceAutoRepairFor(engine, held);return { items: held.map(record => ({ key: record.path, code: record.code, ...(record.meta.reason ? { reason: record.meta.reason } : {}),- already: already.has(record.path) })), sync };+ already: already.has(record.path) })), sync, ...(fenceAuto ? { fenceAuto } : {}) };}function gitNextStep(sourceId: string, dryRun: boolean, scheduled: Scheduled): { text: string; fix: Action } {@@ -71,7 +73,7 @@ function gitNextStep(sourceId: string, dryRun: boolean, scheduled: Scheduled): {why: `Schedules a re-screen of ${count} held file(s) on the next sync of ${sourceId}; nothing runs now.` } };const fences = scheduled.items.filter(item => item.code === 'invalid_fence').length;return { text: `${count} held file(s) scheduled for a re-screen; none has run yet. ${automatic} Run it now with: ${sync}, then verify with: gbrain sources status ${sourceId}. `- + `A file that still refuses stays held; ${fences ? holdRepairSteps(sourceId, { fences, others: count - fences }).text : `preview its fix with: gbrain repair frontmatter --source ${sourceId}`}`,+ + `A file that still refuses stays held; ${holdRepairSteps(sourceId, { fences, others: count - fences }, scheduled.fenceAuto).text}.`,fix: { argv: scheduled.sync, consent: [], actor: 'agent', requires_exclusive: false, verify,why: `The sync re-screens the ${count} scheduled file(s): each one that now passes imports and its hold clears; the rest stay held without blocking the sync.` } };}@@ -101,7 +103,8 @@ export async function runRetryHeld(engine: BrainEngine, args: string[]): Promiseconsole.log('Usage: gbrain sources retry-held <id> [--dry-run] [--json]\n\n'+ 'Re-attempt every held connector item of a Google or GitHub source on its next sync, or re-screen every\n'+ 'held file of a Git source on its next sync (most held files re-screen by themselves when they change).\n'- + 'Nothing runs now.\n'+ + 'Nothing runs now. A file that still refuses stays held: preview frontmatter holds with\n'+ + "'gbrain repair frontmatter --source <id>' and fence holds (invalid_fence) with 'gbrain repair fences --source <id>'.\n"+ ' --dry-run show what would be scheduled; change nothing\n --json print the receipt as JSON');return;}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 50ad21ba08..add8e650fc 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -2000,7 +2000,7 @@ Subcommands:retry-held <id> [--dry-run] [--json]Re-attempt a connector source's held items, or re-screen a Git source's held files, on its next sync.Runs nothing now. Most Git holds re-screen by themselves (file changed or deleted, newer gbrain); fix- frontmatter holds with gbrain repair frontmatter --source <id>, fence holds (invalid_fence) by editing the named fence.+ frontmatter holds with gbrain repair frontmatter --source <id>; preview fence holds (invalid_fence) with gbrain repair fences --source <id>.shared-skills <id> on|off|status [--json]Opt a source out of (or back into) shared-skills adoption; status explains its effective policy.set-path <id> --clear Clear a connector source's (google, github)diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.tsindex 93758fa89f..280fd9afea 100644--- a/src/commands/sync-diagnostics.ts+++ b/src/commands/sync-diagnostics.ts@@ -5,12 +5,15 @@ import { fenceWhere } from '../core/fence-repair/refusal.ts';const HOLD_LINES = 20;export function holdLine(item: GitHoldItem, verb: string): string {- const where = [item.line !== undefined ? `line ${item.line}` : '', item.key ? `key "${item.key}"` : ''].filter(Boolean).join(', ');+ const where = item.fence ? '' : [item.line !== undefined ? `line ${item.line}` : '', item.key ? `key "${item.key}"` : ''].filter(Boolean).join(', ');const page = item.stale ? 'its page keeps its last good revision and is read-only for put_page until the file is repaired' : 'its page is missing until the file imports';- // #6188: a fence hold names fence, section, rows, columns and line (never a cell), then the edit-and-sync step.- const fence = item.fence ? ` in ${fenceWhere(item.fence)}${item.reason === 'prepare_time' ? ` (${item.fence.reason})` : ''}` : '';+ // #6188 (D16): a fence hold names fence, section, rows, columns and its file line (never a cell), then the step its state calls for.+ const fence = item.fence ? ` in ${fenceWhere({ ...item.fence, line: item.line ?? item.fence.line })}${item.reason === 'prepare_time' ? ` (${item.fence.reason})` : ''}` : '';const then = item.fix.then?.argv ? `, then ${item.fix.then.argv.join(' ')}` : '';- return ` ${verb} ${item.path}: ${item.code}${item.reason ? ` (${item.reason})` : ''}${fence}${where ? ` at ${where}` : ''}; ${page}. Next: ${item.fix.argv?.join(' ') ?? item.fix.why}${then} (${item.docs})`;+ const next = item.fix.argv?.join(' ') ?? item.fix.why;+ const step = item.fence?.auto_retry ? `No action needed: the next maintenance run repairs it. Preview: ${next}`+ : item.fix.consent.includes('paid') ? `Ask the user first, then: ${next}` : item.fix.actor === 'host_admin' ? `On the owner host: ${next}` : `Next: ${next}`;+ return ` ${verb} ${item.path}: ${item.code}${item.reason ? ` (${item.reason})` : ''}${fence}${where ? ` at ${where}` : ''}; ${page}. ${step}${then} (${item.docs})`;}/**diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex 08dccc40a1..79df55615b 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -24,10 +24,12 @@ content_sanity reject, or on a managed brain a facts or takes fence thatcannot be imported) is held: the rest of the source imports, thecheckpoint advances, and each hold prints its code, location and nextcommand. Inspect holds with 'gbrain sources status <id>'. Preview a-frontmatter fix with 'gbrain repair frontmatter --source <id>'; fix a-fence hold (invalid_fence) by editing the named fence in the file,-committing, and syncing again. A source a file blocked before this release-recovers on its next sync ('--no-pull' on a managed brain).+frontmatter fix with 'gbrain repair frontmatter --source <id>'. A fence hold+(invalid_fence) is repaired by the next maintenance run when one is active;+preview it with 'gbrain repair fences --source <id>' (read-only, no model+call), which prints the apply command, or the exact edit for a fence gbrain+will not guess. A source a file blocked before this release recovers on its+next sync ('--no-pull' on a managed brain).'gbrain config set sync.holds fail' restores fail-closed blocking.Options:@@ -156,7 +158,7 @@ See also:gbrain doctor Diagnose dim mismatches and other sync issues.gbrain sources status <id> Held files with their next command.gbrain repair frontmatter --source <id> Preview the fix for frontmatter holds.- gbrain get --source <id> -- <slug> Read a page whose fence is held.+ gbrain repair fences --source <id> Preview the repair of fence holds.docs/guides/repair.md#held-files Walkthrough.`);}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 036144c853..2574de50c7 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -60,7 +60,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],- 'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--source'],+ 'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--slug', '--source'],'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],'feedback': ['--brain', '--help', '--json', '--page', '--source'],'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--wait', '--yes'],@@ -76,7 +76,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],- 'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],+ 'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],diff --git a/src/core/fence-repair/hold-fix.ts b/src/core/fence-repair/hold-fix.tsnew file mode 100644index 0000000000..1a123c552c--- /dev/null+++ b/src/core/fence-repair/hold-fix.ts@@ -0,0 +1,229 @@+/**+ * #6188 (D16, D17, E35, Codex CEO #7): what an `invalid_fence` sync hold tells+ * an agent, by state. A hold's state comes from the reason table (planned+ * tier, auto-retry), the last repair attempt the fences repair kind recorded+ * on it (`meta.fence_repair`) and whether the maintenance cycle repairs fences+ * on its own right now (`readFenceAutoRepair`: `fences.repair.enabled` and a+ * brain-wide maintenance pass within `FENCE_MAINTENANCE_ACTIVE_MS`). Without+ * that evidence no surface says "no action is needed".+ *+ * States: `auto` (the next maintenance run repairs it; the fix is the+ * read-only preview), `apply` (repairable, but nothing runs it now: the+ * preview, then the apply), `manual` (a manual-only reason, a gate rejection+ * or a model failure the run does not retry: the preview names the exact+ * edit), `paid` (waits on spend the user controls: the exact config or+ * pricing command with consent `paid`, so it renders `ask_user`), `owner`+ * (repairs run on the canonical owner host). Remote callers get the+ * owner-host command as a relay (`tell_user_to_run`) and a `user_message`+ * saying whether the hold clears by itself; never a path.+ *+ * Location only: fence, section, rows, columns, classes and lines.+ */+import type { BrainEngine } from '../engine.ts';+import type { Action, ActionInput } from '../agent-output.ts';+import type { GitHoldRecord } from '../persistence/sync-holds.ts';+import { FENCE_REPAIR_ENABLED_KEY, FENCE_REPAIR_LLM_KEY } from './config.ts';+import { FENCE_REASONS, renderFenceFix, type FenceMessageLocation } from './reasons.ts';+import { fenceWhere } from './refusal.ts';+import type { FenceReason, FenceTier } from './types.ts';++type Exec = Pick<BrainEngine, 'executeRaw'>;++/** A brain-wide maintenance pass at most this old counts as an active maintenance job (autopilot runs one about hourly). */+export const FENCE_MAINTENANCE_ACTIVE_MS = 24 * 3_600_000;+/** The config key a completed brain-wide maintenance pass stamps (`LAST_GLOBAL_AT_KEY` in cycle.ts). */+export const LAST_GLOBAL_MAINTENANCE_KEY = 'autopilot.last_global_at';++/** Whether the maintenance cycle repairs fences without anyone acting. */+export interface FenceAutoRepair {+ /** `fences.repair.enabled`: the cycle's `fence_repair` phase runs. */+ enabled: boolean;+ /** `fences.repair.llm`: the repair may call the model tier. */+ llm: boolean;+ /** The last completed brain-wide maintenance pass or job (ISO), or null when none ran. */+ last_maintenance_at: string | null;+ /** Enabled, and a maintenance pass completed within `FENCE_MAINTENANCE_ACTIVE_MS`. */+ active: boolean;+}++const FALSE = /^(false|0|off|no)$/i;++/** Two reads: the fence switches with the maintenance stamp, and the last completed maintenance job. A read error counts as no evidence. */+export async function readFenceAutoRepair(engine: Exec, now: Date = new Date()): Promise<FenceAutoRepair> {+ const config = await engine.executeRaw<{ key: string; value: string | null }>('SELECT key, value FROM config WHERE key = ANY($1::text[])',+ [[FENCE_REPAIR_ENABLED_KEY, FENCE_REPAIR_LLM_KEY, LAST_GLOBAL_MAINTENANCE_KEY]]).catch(() => []);+ const value = (key: string) => config.find(row => row.key === key)?.value?.trim() ?? '';+ const job = await engine.executeRaw<{ at: string | null }>(`SELECT to_char(max(finished_at) AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS at+ FROM minion_jobs WHERE name='autopilot-global-maintenance' AND status='completed'`).then(rows => rows[0]?.at ?? '', () => '');+ const times = [value(LAST_GLOBAL_MAINTENANCE_KEY), job].map(at => Date.parse(at)).filter(Number.isFinite);+ const last = times.length ? Math.max(...times) : null;+ const enabled = !FALSE.test(value(FENCE_REPAIR_ENABLED_KEY));+ return { enabled, llm: !FALSE.test(value(FENCE_REPAIR_LLM_KEY)), last_maintenance_at: last === null ? null : new Date(last).toISOString(),+ active: enabled && last !== null && now.getTime() - last <= FENCE_MAINTENANCE_ACTIVE_MS };+}++export type FenceHoldState = 'auto' | 'apply' | 'manual' | 'paid' | 'owner';++export interface FenceHoldStatus {+ state: FenceHoldState;+ /** The reason that decides the state: the last repair attempt's, else the screened one; `llm_disabled` while a model-tier hold waits on `fences.repair.llm`. */+ reason: FenceReason;+ /** The tier that clears it; null when it depends on the bytes the repair reads. */+ tier: FenceTier | null;+ /** The maintenance run retries it with no one acting. */+ auto_retry: boolean;+ /** When the last repair attempt said the maintenance run tries again (null: unknown or never). */+ next_attempt_after: string | null;+}++const PAID: readonly FenceReason[] = ['budget_exhausted', 'llm_disabled', 'no_pricing'];+const OWNER: readonly FenceReason[] = ['owner_unavailable', 'owner_cli_required'];++type HoldMeta = Pick<GitHoldRecord['meta'], 'reason' | 'line' | 'fence' | 'fence_repair'>;++const known = (reason: string | undefined): reason is FenceReason => !!reason && reason in FENCE_REASONS;++/** The screened problem: the receipt's reason for a prepare-time hold, else the hold's own. */+function screenedReason(meta: HoldMeta): FenceReason {+ return meta.fence?.reason ?? (known(meta.reason) ? meta.reason : 'unparseable');+}++/** The state of one fence hold; `auto` is what the caller read (undefined: unknown, so never `auto`). */+export function fenceHoldStatus(meta: HoldMeta, auto?: FenceAutoRepair): FenceHoldStatus {+ const screened = screenedReason(meta);+ const last = meta.fence_repair && known(meta.fence_repair.reason) ? meta.fence_repair : undefined;+ const planned = FENCE_REASONS[screened];+ const tier = last?.tier ?? (planned.manualOnly ? 'manual' : planned.tier);+ const llmOff = tier === 'llm' && auto?.llm === false && (!last || FENCE_REASONS[last.reason].autoRetry);+ const reason: FenceReason = llmOff ? 'llm_disabled' : last?.reason ?? screened;+ const spec = FENCE_REASONS[reason];+ const retries = !llmOff && (last ? last.next_attempt_after !== null : spec.autoRetry && !spec.manualOnly);+ const needsEdit = spec.manualOnly || spec.tier === 'manual' || !!spec.gate || reason.startsWith('llm_');+ const state: FenceHoldState = PAID.includes(reason) ? 'paid' : OWNER.includes(reason) ? 'owner' : !retries && needsEdit ? 'manual' : retries && auto?.active ? 'auto' : 'apply';+ return { state, reason, tier, auto_retry: retries && auto?.active === true, next_attempt_after: last?.next_attempt_after ?? null };+}++/** D16: a hold's structured location (remote callers get no row numbers). */+export interface FenceHoldLocation extends FenceMessageLocation {+ /** Problem classes (location-only reason codes). */+ classes: string[];+ tier: FenceTier | null;+ auto_retry: boolean;+ next_attempt_after: string | null;+}++export function fenceHoldLocation(meta: HoldMeta, auto?: FenceAutoRepair, remote = false): FenceHoldLocation | undefined {+ if (!meta.fence) return undefined;+ const status = fenceHoldStatus(meta, auto);+ return { ...meta.fence, rows: remote ? [] : [...meta.fence.rows], columns: [...meta.fence.columns], classes: [meta.fence.reason], tier: status.tier,+ auto_retry: status.auto_retry, next_attempt_after: status.next_attempt_after };+}++/**+ * The file line of the location's first bad row: the section's first line in+ * the file plus its line within the section. Null when the section text is not+ * found verbatim (for example after line-ending normalization) or has no line.+ */+export function fenceFileLine(content: string, page: { compiled_truth: string; timeline?: string | null }, at: Pick<FenceMessageLocation, 'section' | 'line'>): number | null {+ if (at.line === null) return null;+ const body = page.compiled_truth ?? '', timeline = page.timeline ?? '';+ const bodyAt = body ? content.indexOf(body) : -1;+ const start = at.section === 'body' ? bodyAt : timeline ? content.indexOf(timeline, bodyAt < 0 ? 0 : bodyAt + body.length) : -1;+ return start < 0 ? null : content.slice(0, start).split('\n').length + at.line - 1;+}++/** The hold's location as prose, at the file line when the hold recorded one. */+export function fenceHoldWhere(meta: HoldMeta): string {+ return fenceWhere(meta.fence ? { ...meta.fence, line: meta.line ?? meta.fence.line } : undefined);+}++/** `gbrain repair fences --source <id> [--only <path>]`: the read-only preview (no model call). */+export function fencePreviewArgv(sourceId: string, path?: string): string[] {+ return ['gbrain', 'repair', 'fences', '--source', sourceId, ...(path ? ['--only', path] : [])];+}++/** The exact command a paid state waits on; `<...>` placeholders are described by `inputs`. */+function paidStep(reason: FenceReason): { argv: string[]; inputs?: ActionInput[] } {+ if (reason === 'budget_exhausted') return { argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<usd>'],+ inputs: [{ name: 'usd', how: 'The daily cap in USD the user agreed to; read the current one with gbrain config get fences.repair.max_usd_per_day.' }] };+ if (reason === 'llm_disabled') return { argv: ['gbrain', 'config', 'set', 'fences.repair.llm', 'true'] };+ return { argv: ['gbrain', 'pricing', 'set', '<model>', '--input', '<usd>', '--output', '<usd>'],+ inputs: [{ name: 'model', how: 'The fence repair model: models.fence_repair in gbrain models --json.' },+ { name: 'usd', how: "The provider's price in USD per 1M input tokens after --input and per 1M output tokens after --output, from its pricing page." }] };+}++/** Why a paid state waits, in words a user can decide on. */+function paidWait(reason: FenceReason): string {+ if (reason === 'budget_exhausted') return "today's fence repair budget (fences.repair.max_usd_per_day) is spent";+ if (reason === 'llm_disabled') return 'model repair is off (fences.repair.llm false)';+ return 'a fence repair spend cap is set but gbrain has no price for the repair model, so it will not call it';+}++/** Why an `apply` hold is not repaired by itself. */+function applyWait(auto: FenceAutoRepair | undefined): string {+ if (!auto) return 'Unless a maintenance run repairs it first';+ return auto.enabled ? 'No maintenance run is active on this brain, so nothing repairs it by itself' : 'Automatic fence repair is paused (fences.repair.enabled false), so nothing repairs it by itself';+}++/** The local next step for one `invalid_fence` hold (actor `agent`; the owner state is the host operator's). */+export function fenceHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'meta'>, auto?: FenceAutoRepair): Action {+ const status = fenceHoldStatus(record.meta, auto);+ const source = record.source_id, path = record.path;+ const preview = fencePreviewArgv(source, path);+ const command = preview.join(' ');+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };+ const held = `${path} is held because ${fenceHoldWhere(record.meta)} ${record.meta.reason === 'prepare_time' ? 'was refused against the stored page' : 'cannot be imported'} (${screenedReason(record.meta)}).`;+ const rest = 'The rest of the source keeps syncing.';+ const step = { consent: [], actor: 'agent' as const, requires_exclusive: false, verify };+ const base = { ...step, docs: 'docs/guides/repair.md#fences' };+ switch (status.state) {+ case 'auto':+ return { ...base, argv: preview, why: `${held} No action is needed: the next maintenance run repairs it automatically${status.next_attempt_after ? ` (next attempt after ${status.next_attempt_after})` : ''}. `+ + `The preview shows the planned repair, read-only. ${rest}` };+ case 'apply':+ return { ...base, argv: preview, why: `${held} ${applyWait(auto)}: the preview (read-only, no model call) shows the planned repair and prints the apply command with --expect <hash>; `+ + `run that printed command to apply exactly what it showed. ${rest}`,+ then: { ...step, argv: [...preview, '--apply'], why: `Applies the current repair plan for ${path} and clears the hold. The command the preview prints adds --expect <hash>, which applies exactly the previewed repair; prefer it.` } };+ case 'manual': {+ const at = record.meta.fence ? { ...record.meta.fence, reason: status.reason, rows: record.meta.fence_repair?.rows ?? record.meta.fence.rows } : null;+ const gate = record.meta.fence_repair?.gate;+ return { ...base, argv: preview, why: `${held} ${gate ? `The proposed repair failed gate ${gate}, so it was not written.` : 'gbrain will not guess this repair.'} ${at ? `${renderFenceFix(at)} ` : ''}`+ + `The preview names the exact edit, read-only: make it in ${path} (never the frontmatter), commit, then sync. ${rest}`,+ then: { ...step, argv: ['gbrain', 'sync', '--source', source, '--no-pull'],+ why: `Imports the corrected ${path} and clears the hold; a fence that still does not parse stays held without blocking the sync.` } };+ }+ case 'paid': {+ const paid = paidStep(status.reason);+ return { ...base, ...paid, consent: ['paid'], preview_argv: preview,+ why: `${held} Its model repair waits because ${paidWait(status.reason)}${status.reason === 'budget_exhausted' && status.auto_retry ? '; the maintenance run retries it after 00:00 UTC with no action' : ''}. `+ + `Spending more on fence repair is the user's call, so ask before running this; without it, fix the rows by hand (${command} names them, read-only, with the estimated cost). ${rest}`,+ user_message: `gbrain can repair a malformed facts or takes table in ${path} with the paid repair model, but ${paidWait(status.reason)}. May I run '${paid.argv.join(' ')}'? Otherwise I can fix the rows by hand.` };+ }+ case 'owner':+ return { ...base, actor: 'host_admin', argv: preview, why: `${held} Fence repairs write files only on the source's canonical owner host, and this host is not it (${status.reason}). `+ + `On the owner host run ${command} to preview the repair, then the apply command it prints. ${rest}`,+ user_message: `Please run '${command}' on the brain's owner host to preview the repair of a malformed facts or takes table, then run the apply command it prints.` };+ }+}++/** Why a remote caller's held fence does or does not clear by itself, for its `user_message`. */+function relayText(status: FenceHoldStatus, auto: FenceAutoRepair | undefined, run: string, paid: string): string {+ switch (status.state) {+ case 'auto': return `It clears by itself: the brain host's maintenance run repairs it automatically${status.next_attempt_after ? ` (next attempt after ${status.next_attempt_after})` : ''}, so nothing is needed now. To see the planned repair, the brain host operator can run ${run}.`;+ case 'apply': return `It does not clear by itself because ${auto?.enabled === false ? 'automatic fence repair is paused on the brain host' : 'no maintenance run is active on the brain host'}. Please run ${run} on the brain host to preview the repair, then run the apply command it prints.`;+ case 'manual': return `It does not clear by itself: it needs an edit gbrain will not guess. Please run ${run} on the brain host; it names the exact edit to make in the file, then commit and sync.`;+ case 'paid': return `It does not clear by itself: its repair needs the paid repair model, and ${paidWait(status.reason)}. Raising spend or enabling the model is your call: if you agree, run '${paid}' on the brain host; otherwise ${run} there names the rows to fix by hand.`;+ case 'owner': return `Fence repairs run on the brain's owner host: please run ${run} there, then the apply command it prints.`;+ }+}++/** The relay a remote caller gets for one held fence (`tell_user_to_run`): the owner-host command and whether it clears by itself. No path. */+export function fenceHoldRelay(record: Pick<GitHoldRecord, 'source_id' | 'meta'>, auto: FenceAutoRepair | undefined, why: string): Action {+ const status = fenceHoldStatus(record.meta, auto);+ const preview = fencePreviewArgv(record.source_id);+ const paid = status.state === 'paid' ? paidStep(status.reason) : null;+ return { argv: paid?.argv ?? preview, ...(paid?.inputs ? { inputs: paid.inputs } : {}), consent: paid ? ['paid'] : [], actor: 'host_admin', requires_exclusive: false, why,+ ...(paid ? { preview_argv: preview } : {}),+ user_message: `A facts or takes table in one of your brain's files could not be imported, so answers can show an older version of that page. `+ + relayText(status, auto, `'${preview.join(' ')}'`, paid?.argv.join(' ') ?? '') };+}diff --git a/src/core/fence-repair/reasons.ts b/src/core/fence-repair/reasons.tsindex 99af6efcf7..5ffa1ffb7f 100644--- a/src/core/fence-repair/reasons.ts+++ b/src/core/fence-repair/reasons.ts@@ -32,8 +32,8 @@ export interface FenceReasonSpec {// The anchor is built per reason, so no partial `write-refusals.md#...` literal reads as a broken link (write-refusals-coverage).const DOCS = 'docs/guides/write-refusals.md';-// PR4 switches this next step to `gbrain repair fences`, routed through the hold-repair router.-const REPAIR = 'Edit the fence by hand, then sync or write the page again.';+const REPAIR = 'Preview its repair with `gbrain repair fences` (read-only; it names the exact edit when gbrain will not repair it), or fix the fence and write the page again.';+const BY_HAND = '`gbrain repair fences` (read-only) lists the exact edit.';type Base = Pick<FenceReasonSpec, 'stage' | 'tier' | 'manualOnly' | 'autoRetry'>;const tier3: Base = { stage: 'screen', tier: 'llm', manualOnly: false, autoRetry: true };@@ -79,11 +79,11 @@ const SPECS: Record<FenceReason, Omit<FenceReasonSpec, 'docs'>> = {prepare_time: entry(prepared, 'The {fence} fence passed the screen but its rows were refused while the write was prepared. ' + REPAIR),normalizer_failed: entry({ ...prepared, autoRetry: false, tier: 'manual' }, 'The fence normalizer failed on the {fence} fence in the {section}; the page is held as it was. Run `gbrain doctor --json` and report it; a gbrain upgrade re-screens it.'),llm_unavailable: entry(run(true), 'The repair model was unavailable (timeout, rate limit or server error). The next repair run retries.'),- llm_empty: entry(run(false), 'The repair model returned nothing for the {fence} fence. Fix row(s) {rows} by hand. ' + REPAIR),- llm_refused: entry(run(false), 'The repair model declined to repair the {fence} fence. Fix row(s) {rows} by hand. ' + REPAIR),- llm_malformed: entry(run(false), 'The repair model did not return a single table for the {fence} fence. Fix row(s) {rows} by hand. ' + REPAIR),- llm_truncated: entry(run(false), 'The repair model stopped before finishing the {fence} fence. Fix row(s) {rows} by hand. ' + REPAIR),- llm_disabled: entry(run(false), 'Model repair is off (`fences.repair.llm`). Fix row(s) {rows} by hand, or ask the user before running `gbrain config set fences.repair.llm true`.', { paid: true }),+ llm_empty: entry(run(false), 'The repair model returned nothing for the {fence} fence. Fix row(s) {rows} by hand; ' + BY_HAND),+ llm_refused: entry(run(false), 'The repair model declined to repair the {fence} fence. Fix row(s) {rows} by hand; ' + BY_HAND),+ llm_malformed: entry(run(false), 'The repair model did not return a single table for the {fence} fence. Fix row(s) {rows} by hand; ' + BY_HAND),+ llm_truncated: entry(run(false), 'The repair model stopped before finishing the {fence} fence. Fix row(s) {rows} by hand; ' + BY_HAND),+ llm_disabled: entry(run(false), 'Model repair is off (`fences.repair.llm`). Fix row(s) {rows} by hand (' + BY_HAND + '), or ask the user before running `gbrain config set fences.repair.llm true`.', { paid: true }),budget_exhausted: entry(run(true), 'The daily fence-repair budget is spent; repairs resume after 00:00 UTC. Raising it is the user\'s call: `gbrain config set fences.repair.max_usd_per_day <usd>`.', { paid: true }),no_pricing: entry(run(false), 'A spend cap is set but gbrain has no price for the repair model. Look up its price and run `gbrain pricing set <model> --input <usd> --output <usd>` on the brain host.', { paid: true }),ledger_unavailable: entry(run(true), 'The spend ledger could not be read, so no model call was made. The next repair run retries.'),diff --git a/src/core/persistence/connector-status.ts b/src/core/persistence/connector-status.tsindex ac4d8e83c6..9bcaa23d00 100644--- a/src/core/persistence/connector-status.ts+++ b/src/core/persistence/connector-status.ts@@ -15,7 +15,7 @@ import { readFix } from '../ops/op-fix.ts';import { readManagedConnectorState, type ConnectorRunCounts, type UpgradeRecovery } from './connector-state.ts';import { managedBrain, readAllSourceHolds } from '../connectors/item-holds-store.ts';import type { ItemHoldRecord } from '../connectors/item-holds.ts';-import { gitHoldItem, readGitHoldListing, readSyncConversions, readSyncHoldPolicy, type GitHoldItem, type SyncConversion } from './sync-holds.ts';+import { fenceAutoRepairFor, gitHoldItem, readGitHoldListing, readSyncConversions, readSyncHoldPolicy, type GitHoldItem, type SyncConversion } from './sync-holds.ts';import { holdLine } from '../../commands/sync-diagnostics.ts';/** Fix wave 4: `sources status` lists this many held items per source, then "+N more". */@@ -117,11 +117,12 @@ export async function readGitHoldStatuses(engine: Pick<BrainEngine, 'executeRaw'const [sources, conversions] = await Promise.all([readGitHoldListing(engine, sourceIds, cap), readSyncConversions(engine, sourceIds, CONVERSION_STATUS_LIMIT)]);if (!sources.length && !conversions.size) return out;const managed = await managedBrain(engine);+ const auto = await fenceAutoRepairFor(engine, sources.flatMap(source => source.holds));const counts = new Map(sources.map(source => [source.sourceId, source]));for (const sourceId of sourceIds) {const source = counts.get(sourceId), converted = conversions.get(sourceId);if (!source && !converted) continue;- const items = (source?.holds ?? []).map(gitHoldItem);+ const items = (source?.holds ?? []).map(hold => gitHoldItem(hold, auto));out.set(sourceId, { count: source?.count ?? 0, items, ...((source?.count ?? 0) > items.length ? { truncated: true as const } : {}),...(converted ? { recent_conversions: converted } : {}),sync_argv: ['gbrain', 'sync', '--source', sourceId, ...(managed ? ['--no-pull'] : [])] });diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsindex c656785208..d3613119e6 100644--- a/src/core/persistence/held-reads.ts+++ b/src/core/persistence/held-reads.ts@@ -11,22 +11,27 @@** Cost: one indexed lookup (`op_checkpoints_sync_hold_page_idx`) for the pages* a call returns and one read of the per-source summary rows in scope, each- * cached per request. Remote callers get codes, counts and flags, never paths,- * and a fix addressed to the brain host operator.+ * cached per request (plus, only for a page whose held file is an+ * `invalid_fence` hold, the two reads that say whether the maintenance run+ * repairs it). Remote callers get codes, counts and flags, never paths, and a+ * fix addressed to the brain host operator; the repair commands come from the+ * hold router (D6): `gbrain repair fences` for fence holds, `gbrain repair+ * frontmatter` for the rest.*/import type { BrainEngine } from '../engine.ts';import type { Action, Notice } from '../agent-output.ts';import { ALL_SOURCES } from '../source-id.ts';-import { GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, gitHoldDocs, gitHoldFix, holdRepairSteps, type GitHoldCode, type GitHoldReason, type GitHoldRecord, type HoldRepairRoute } from './sync-holds.ts';-import type { FenceMessageLocation } from '../fence-repair/reasons.ts';+import { GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, fenceAutoRepairFor, gitHoldDocs, gitHoldFix, holdRepairSteps, type GitHoldCode, type GitHoldReason, type GitHoldRecord, type HoldRepairRoute } from './sync-holds.ts';+import { fenceHoldLocation, fenceHoldRelay, fencePreviewArgv, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';type Exec = Pick<BrainEngine, 'executeRaw'>;-export interface HeldPage { record: GitHoldRecord; revision: string | null }+/** `fenceAuto`: whether the maintenance run repairs fence holds, read only when some returned hold is one. */+export interface HeldPage { record: GitHoldRecord; revision: string | null; fenceAuto?: FenceAutoRepair }/*** Held files of the sources in a read scope: new files with no page (`missing`) and pages whose newer file is held (`stale`);- * `fences` (present only when some are) counts the #6188 `invalid_fence` holds among them, which route to a fence edit instead of frontmatter repair.+ * `fences` (present only when some are) counts the #6188 `invalid_fence` holds among them, which route to `gbrain repair fences` instead of frontmatter repair.*/export interface HeldCoverage { source_id: string; missing: number; stale: number; fences?: number }@@ -36,8 +41,8 @@ export interface FileHeld {reason?: GitHoldReason;key?: string;line?: number;- /** #6188 `invalid_fence`: fence, section, reason and problem classes (row numbers for trusted local callers only). */- fence?: FenceMessageLocation;+ /** #6188 `invalid_fence` (D16): fence, section, reason, classes, planned tier, auto_retry and next_attempt_after (row numbers for trusted local callers only). */+ fence?: FenceHoldLocation;since: string;/** Source-relative file path; trusted local callers only. */path?: string;@@ -71,9 +76,10 @@ export function readHeldPages(engine: Exec, pageIds: number[], request?: object)WHERE h.op=$1 AND (h.completed_keys->0->>'page_id')=ANY($2::text[])ORDER BY h.fingerprint`, [GIT_HOLD_OP, ids.map(String)]);const out = new Map<number, HeldPage>();+ const fenceAuto = await fenceAutoRepairFor(engine, rows.map(row => row.record));for (const row of rows) {const id = Number(row.record.page_id);- if (!out.has(id)) out.set(id, { record: row.record, revision: row.revision });+ if (!out.has(id)) out.set(id, { record: row.record, revision: row.revision, ...(fenceAuto ? { fenceAuto } : {}) });}return out;});@@ -104,25 +110,24 @@ export function coverageRoute(source: HeldCoverage): HoldRepairRoute {return { fences, others: Math.max(0, source.missing + source.stale - fences) };}-function repairArgv(sourceId: string): string[] {- return ['gbrain', 'repair', 'frontmatter', '--source', sourceId];-}-/*** The fix a remote caller relays (`tell_user_to_run`): only the brain host- * operator can inspect and repair held files. A source without a route, or- * with frontmatter-style holds, names the frontmatter repair preview; a source- * with fence holds names the status read, the fence edit and the sync (D6).+ * operator can inspect and repair held files. Commands come from the hold+ * router (D6): a source without a route, or with frontmatter-style holds,+ * names the frontmatter repair preview; a source with fence holds names the+ * fence repair preview and says the maintenance run repairs most of them by+ * itself when it runs. No path.*/export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; route?: HoldRepairRoute }>, why: string): Action {- const frontmatter = sources.filter(source => !source.route || source.route.others > 0).map(source => `'${repairArgv(source.source_id).join(' ')}'`);- const fences = sources.filter(source => source.route && source.route.fences > 0).map(source => source.source_id);+ const frontmatter = sources.filter(source => !source.route || source.route.others > 0).map(source => `'gbrain repair frontmatter --source ${source.source_id}'`);+ const fences = sources.filter(source => source.route && source.route.fences > 0).map(source => `'${fencePreviewArgv(source.source_id).join(' ')}'`);const first = sources[0]!;const parts = [...(frontmatter.length ? [`Please run ${frontmatter.join(', ')} on the brain host to preview the fixes, then apply them.`] : []),- ...(fences.length ? [`Some held files have a facts or takes table gbrain cannot import: on the brain host run ${fences.map(id => `'gbrain sources status ${id}'`).join(', ')} to see which file and table, edit that table and commit, then run ${fences.map(id => `'gbrain sync --source ${id} --no-pull'`).join(', ')}.`] : []),+ ...(fences.length ? [`Some held files have a facts or takes table gbrain could not import. The brain host's maintenance run repairs most of these by itself when it is running; `+ + `to see each one's state and repair the rest now, run ${fences.join(', ')} on the brain host (a read-only preview that prints the apply command).`] : []),];- return { argv: first.route ? holdRepairSteps(first.source_id, first.route).argv : repairArgv(first.source_id), consent: [], actor: 'host_admin', requires_exclusive: false, why,+ return { argv: holdRepairSteps(first.source_id, first.route ?? { fences: 0, others: 1 }).argv, consent: [], actor: 'host_admin', requires_exclusive: false, why,user_message: `Some files in your brain could not be imported, so answers from it can miss or show outdated notes. ${parts.join(' ')}` };}@@ -131,15 +136,22 @@ export function recordRoute(record: Pick<GitHoldRecord, 'code'>): HoldRepairRoutreturn record.code === 'invalid_fence' ? { fences: 1, others: 0 } : { fences: 0, others: 1 };}-/** `get_page.file_held` for a page whose newer file is held; the path only for trusted local callers. */+/**+ * `get_page.file_held` for a page whose newer file is held; the path only for+ * trusted local callers. A fence hold's fix follows its state (D17): locally+ * the step `gitHoldFix` names, remotely the owner-host relay saying whether it+ * clears by itself (Codex CEO #7).+ */export function fileHeldField(held: HeldPage, remote: boolean): FileHeld {const { record } = held;- const fix = remote- ? hostOperatorFix([{ source_id: record.source_id, route: recordRoute(record) }], `The canonical file of this page is held (${record.code}${record.meta.reason ? `, ${record.meta.reason}` : ''}): sync cannot import its newer version, so this page shows its last good revision and is read-only for put_page until the brain host operator repairs the file.`)- : gitHoldFix(record);- const fence = record.meta.fence ? (remote ? { ...record.meta.fence, rows: [] } : record.meta.fence) : undefined;+ const fence = record.code === 'invalid_fence';+ const why = `The canonical file of this page is held (${record.code}${record.meta.reason ? `, ${record.meta.reason}` : ''}): sync cannot import its newer version, so this page shows its last good revision `+ + `and is read-only for put_page until ${fence ? 'the file is repaired' : 'the brain host operator repairs the file'}.`;+ const fix = !remote ? gitHoldFix(record, held.fenceAuto)+ : fence ? fenceHoldRelay(record, held.fenceAuto, why) : hostOperatorFix([{ source_id: record.source_id, route: recordRoute(record) }], why);+ const location = fence ? fenceHoldLocation(record.meta, held.fenceAuto, remote) : undefined;return { code: record.code, ...(record.meta.reason ? { reason: record.meta.reason } : {}), ...(record.meta.key ? { key: record.meta.key } : {}),- ...(record.meta.line !== undefined ? { line: record.meta.line } : {}), ...(fence ? { fence } : {}), since: record.held_at, ...(remote ? {} : { path: record.path }),+ ...(record.meta.line !== undefined ? { line: record.meta.line } : {}), ...(location ? { fence: location } : {}), since: record.held_at, ...(remote ? {} : { path: record.path }),fix, docs: gitHoldDocs(record.code, record.meta.reason) };}@@ -178,6 +190,6 @@ export function heldFilesNotice(coverage: HeldCoverage[], remote: boolean): Noti? `gbrain sources status ${ids[0]} lists each held file; ${single.text}.`: `Previews the fix for each held file in source ${ids[0]} (gbrain sources status ${ids[0]} lists them); nothing is written until a hash-bound apply.` }: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,- why: `Doctor lists the held files of each source with its next step (${coverage.map(source => holdRepairSteps(source.source_id, coverageRoute(source)).commands[0]).join('; ')}).` };+ why: `Doctor lists the held files of each source with its next step (${coverage.map(source => holdRepairSteps(source.source_id, coverageRoute(source)).commands.join(', ')).join('; ')}).` };return { code: 'held_files', kind: 'degraded', why, fix };}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 4dc48cfe10..1b0fd1727b 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -19,9 +19,11 @@* source's summary row first, so concurrent cursors of one source serialize.* Rows carry key name, line, code and a location-only message, never a raw* frontmatter value. #6188 `invalid_fence` holds carry the fence, section,- * reason, problem classes and parsed row numbers, never a cell value; the+ * reason, parsed row numbers and the file line, never a cell value; the* summary also counts them (`fences`) so every surface can route a source to- * the right repair (`holdRepairRoute`, D6).+ * the right repair (`holdRepairSteps`, D6): `gbrain repair fences` for fence+ * holds, `gbrain repair frontmatter` for the rest. A fence hold's own fix+ * depends on its state (`fence-repair/hold-fix.ts`, D17).*/import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';@@ -29,7 +31,8 @@ import type { ContentRefusal } from '../import-screen.ts';import { RECOVERY_VERSION, type InvalidFrontmatterReason } from '../markdown.ts';import { FENCE_REASONS, type FenceMessageLocation } from '../fence-repair/reasons.ts';import type { FenceReason, FenceTier, GateLetter } from '../fence-repair/types.ts';-import { FENCE_VERSION, fenceWhere } from '../fence-repair/refusal.ts';+import { FENCE_VERSION } from '../fence-repair/refusal.ts';+import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';import { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/report.ts';import type { SyncRename } from './sync-discovery.ts';@@ -117,8 +120,8 @@ export interface GitHoldItem {reason?: GitHoldReason;key?: string;line?: number;- /** #6188 `invalid_fence`: the fence location (reason, fence, section, rows, columns, line). */- fence?: FenceMessageLocation;+ /** #6188 `invalid_fence` (D16): reason, fence, section, rows, columns, section line, classes, planned tier, auto_retry and next_attempt_after. */+ fence?: FenceHoldLocation;message: string;slug: string | null;/** True when a page exists and keeps its last good revision; false when the file's page is missing. */@@ -299,47 +302,46 @@ export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, re}/**- * D6: which repairs a source's holds need. Fence holds are fixed by editing- * the named fence in the file and syncing; every other hold routes to the- * frontmatter repair preview. A source with both names both.+ * D6: which repairs a source's holds need. Fence holds route to the fence+ * repair preview, every other hold to the frontmatter repair preview; a+ * source with both names both.*/export interface HoldRepairRoute { fences: number; others: number }-/** The source-level next step every surface prints for `route` (sync results, doctor, read notices, the banner, retry-held). */-export function holdRepairSteps(sourceId: string, route: HoldRepairRoute): { argv: string[]; commands: string[]; text: string } {- const status = ['gbrain', 'sources', 'status', sourceId, '--json'];+/**+ * The source-level next step every surface prints for `route` (sync results,+ * doctor, read notices, the banner, retry-held). `auto`, when the caller read+ * it, says whether the maintenance run repairs fence holds by itself.+ */+export function holdRepairSteps(sourceId: string, route: HoldRepairRoute, auto?: FenceAutoRepair): { argv: string[]; commands: string[]; text: string } {+ const fences = fencePreviewArgv(sourceId);const frontmatter = ['gbrain', 'repair', 'frontmatter', '--source', sourceId];- const sync = `gbrain sync --source ${sourceId} --no-pull`;- const fenceText = `for each fence hold, read the page (gbrain get --source ${sourceId} -- <slug>), edit the fence that gbrain sources status ${sourceId} names in its file, commit, then run ${sync}`;+ const automatic = !auto ? '' : auto.active ? 'the next maintenance run repairs the fence holds it can by itself; '+ : `nothing repairs the fence holds by itself (${auto.enabled ? 'no maintenance run is active' : 'fences.repair.enabled is false'}), so `;+ const fenceText = `${automatic}preview the fence repairs with ${fences.join(' ')} `+ + '(read-only, no model call: it lists each held file with its planned repair or the exact edit, and prints the apply command with --expect <hash>)'+ + (auto?.active ? '' : ', then run the apply command it prints');const frontmatterText = `preview the frontmatter and other fixes with ${frontmatter.join(' ')} (writes nothing until a hash-bound apply)`;- if (route.fences && !route.others) return { argv: status, commands: [status.join(' '), sync], text: fenceText };- if (route.fences) return { argv: frontmatter, commands: [frontmatter.join(' '), status.join(' '), sync], text: `${frontmatterText}; ${fenceText}` };+ if (route.fences && !route.others) return { argv: fences, commands: [fences.join(' ')], text: fenceText };+ if (route.fences) return { argv: frontmatter, commands: [frontmatter.join(' '), fences.join(' ')], text: `${frontmatterText}; ${fenceText}` };return { argv: frontmatter, commands: [frontmatter.join(' ')], text: frontmatterText };}/*** The exact next step for one hold: the repair preview for frontmatter, the- * split or exclude for size, and for a fence hold the page read, the edit of- * the named fence and the sync that imports it.+ * split or exclude for size, and for a fence hold the step its state calls+ * for (`fenceHoldFix`: that file's `gbrain repair fences --only <path>`+ * preview, then the apply, the edit or the paid setting). `auto` is what the+ * caller read about the maintenance run (undefined: unknown).*/-export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'code' | 'meta'> & Partial<Pick<GitHoldRecord, 'slug' | 'page_id'>>): Action {+export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'code' | 'meta'> & Partial<Pick<GitHoldRecord, 'slug' | 'page_id'>>, auto?: FenceAutoRepair): Action {const source = record.source_id;const repair = (ambiguous: boolean, why: string): Action => ({ argv: ['gbrain', 'repair', 'frontmatter', '--source', source, ...(ambiguous ? ['--include-ambiguous'] : [])],consent: [], actor: 'agent', requires_exclusive: false, why,verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } });switch (record.code) {- case 'invalid_fence': {- const fence = record.meta.fence;- const sync = ['gbrain', 'sync', '--source', source, '--no-pull'];- const read = record.slug && record.page_id != null ? ['gbrain', 'get', '--source', source, '--', record.slug] : null;- const why = `${record.path} is held because ${fenceWhere(fence)} ${record.meta.reason === 'prepare_time' ? 'was refused against the stored page' : 'cannot be imported'}`- + ` (${fence?.reason ?? record.meta.reason ?? 'invalid_fence'}). ${read ? 'Read the page, then edit' : 'Edit'} that fence in ${record.path}, commit, and run ${sync.join(' ')}; the file imports and the hold clears. `- + 'The rest of the source is not blocked. Edit only the named fence; never the frontmatter.';- return { argv: read ?? ['gbrain', 'sources', 'status', source, '--json'], consent: [], actor: 'agent', requires_exclusive: false, why,- then: { argv: sync, consent: [], actor: 'agent', requires_exclusive: false, why: `Imports the corrected ${record.path}; a fence that still does not parse stays held without blocking the sync.`,- verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } },- verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };- }+ case 'invalid_fence':+ return fenceHoldFix(record, auto);case 'file_too_large':return { argv: ['gbrain', 'config', 'get', 'sync.exclude'], consent: [], actor: 'agent', requires_exclusive: false,why: `The size limit is fixed. Split ${record.path} into smaller files and commit, or leave it out of the source: read the current sync.exclude list, then run gbrain config set sync.exclude '<current list>,${record.path}'. The next gbrain sync --source ${source} --no-pull clears the hold.`,@@ -374,12 +376,19 @@ export function gitHoldDocs(code: GitHoldCode, reason?: GitHoldReason): string {return `docs/guides/write-refusals.md#${reason ? `${code}-${reason}` : code}`;}-export function gitHoldItem(record: GitHoldRecord): GitHoldItem {+/** One hold as surfaces list it; `auto` (what the caller read about the maintenance run) decides a fence hold's fix and `auto_retry`. */+export function gitHoldItem(record: GitHoldRecord, auto?: FenceAutoRepair): GitHoldItem {+ const fence = record.code === 'invalid_fence' ? fenceHoldLocation(record.meta, auto) : undefined;return { path: record.path, code: record.code, ...(record.meta.reason ? { reason: record.meta.reason } : {}),...(record.meta.key ? { key: record.meta.key } : {}), ...(record.meta.line !== undefined ? { line: record.meta.line } : {}),- ...(record.meta.fence ? { fence: record.meta.fence } : {}),+ ...(fence ? { fence } : {}),message: record.message, slug: record.slug, stale: record.page_id !== null, held_since: record.held_at,- fix: gitHoldFix(record), docs: gitHoldDocs(record.code, record.meta.reason) };+ fix: gitHoldFix(record, auto), docs: gitHoldDocs(record.code, record.meta.reason) };+}++/** What the maintenance run does about fence holds, read only when some of these holds are fence holds. */+export async function fenceAutoRepairFor(engine: Exec, records: ReadonlyArray<Pick<GitHoldRecord, 'code'>>): Promise<FenceAutoRepair | undefined> {+ return records.some(record => record.code === 'invalid_fence') ? readFenceAutoRepair(engine) : undefined;}/** A blocked sync request a run converted in place: held (the file is refused) or re-frozen (the file now imports). */@@ -582,7 +591,8 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; iconst escalated = holdsEscalated(input.policy, outstanding - Number(summary?.images ?? 0),{ held: runHolds.filter(hold => !imageWeight(hold)).length, screened: input.screened });const fences = Math.max(Number(summary?.fences ?? 0), runHolds.filter(hold => fenceWeight(hold)).length);- const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences) });+ const auto = fences ? await readFenceAutoRepair(engine) : undefined;+ const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences) }, auto);const verify = { argv: ['gbrain', 'sources', 'status', input.sourceId, '--json'] };if (input.remote) return { held_count: runHolds.length, holds_fix: { argv: steps.argv, consent: [], actor: 'host_admin', requires_exclusive: false, verify,why: `${outstanding} file(s) in source ${input.sourceId} are held and not imported; only the brain host can inspect and repair them.`,@@ -591,7 +601,7 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; iwhy: `${runHolds.length} file(s) held this run, ${outstanding} held in source ${input.sourceId}; they do not block sync. Inspect them with 'gbrain sources status ${input.sourceId}'; `+ (fences ? `then ${steps.text}.` : 'the repair preview proposes each fix and writes nothing.')+ (escalated ? ' Escalated: more files are held than a source should carry, so a generator or a gbrain upgrade is likely writing or reading them wrong; fix the cause before the backlog grows.' : '') };- return { held: runHolds.slice(0, input.policy.cap).map(gitHoldItem), held_count: runHolds.length, holds_outstanding: outstanding,+ return { held: runHolds.slice(0, input.policy.cap).map(hold => gitHoldItem(hold, auto)), held_count: runHolds.length, holds_outstanding: outstanding,...(escalated ? { holds_escalated: true } : {}), ...(runHolds.length > input.policy.cap ? { holds_truncated: true } : {}),...(input.pendingScreen ? { holds_pending_screen: true } : {}), holds_fix: fix };}diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex e2dace22f8..28092d188b 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -19,6 +19,7 @@ import type { FenceFix } from '../fence-repair/types.ts';import { parseMarkdown, RECOVERY_VERSION } from '../markdown.ts';import { fenceMessage, type FenceMessageLocation } from '../fence-repair/reasons.ts';import { completeFenceLocation, FENCE_VERSION, type ReceiptFenceLocation } from '../fence-repair/refusal.ts';+import { fenceFileLine } from '../fence-repair/hold-fix.ts';import { slugConflictHoldMessage } from '../import-file.ts';import { isImageFilePath, resolveSlugForPath } from '../sync.ts';import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';@@ -62,9 +63,10 @@ export function pinnedBlob(discovery: Pick<SyncDiscovery, 'root' | 'gitRoot' | 'function heldEntry(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null,refusal: { code: GitHoldRecord['code']; reason?: GitHoldRecord['meta']['reason']; key?: string; line?: number; message: string; fence?: FenceMessageLocation },content: string | null, blob: Pick<TreeBlob, 'oid'> | null | undefined): HeldEntry {+ const line = refusal.line ?? (refusal.fence && content !== null ? fenceFileLine(content, parseMarkdown(content, entry.path), refusal.fence) ?? undefined : undefined);return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code: refusal.code, message: refusal.message,upstream_version: content === null ? null : sha256(content),- meta: { ...(refusal.reason ? { reason: refusal.reason } : {}), ...(refusal.key ? { key: refusal.key } : {}), ...(refusal.line !== undefined ? { line: refusal.line } : {}),+ meta: { ...(refusal.reason ? { reason: refusal.reason } : {}), ...(refusal.key ? { key: refusal.key } : {}), ...(line !== undefined ? { line } : {}),recovery_version: RECOVERY_VERSION, ...(refusal.fence ? { fence: refusal.fence, fence_version: FENCE_VERSION } : {}),...(blob ? { blob_oid: blob.oid } : {}), ...(entry.working ? { working: true } : {}),...(entry.renameFrom ?? entry.renameHeld ? { rename_from: entry.renameFrom ?? entry.renameHeld } : {}) } };diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 73fc36b13b..216481ba56 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -25,9 +25,9 @@ export function heldFileMessage(kind: 'drift' | 'occupied', code: string): strinexport function heldFileDiagnostic(message: string | null | undefined, sourceId = '<source>'): { reason: string; message: string; suggestion: string } | null {const held = message ? HELD_FILE.exec(message) : null;if (!held) return null;- // #6188 (D6): a fence hold is fixed by editing the named fence and syncing, never by frontmatter repair.+ // #6188 (D6): a fence hold routes to the fence repair, never to frontmatter repair.const repair = held[1] === 'invalid_fence'- ? `edit the facts or takes fence gbrain sources status ${sourceId} names in that file, commit, and run gbrain sync --source ${sourceId} --no-pull`+ ? `the maintenance run repairs most fence holds by itself; to repair it now, preview with gbrain repair fences --source ${sourceId} (read-only: it names the planned repair or the exact edit) and run the apply command it prints`: `frontmatter holds: preview the fix with gbrain repair frontmatter --source ${sourceId} and apply it; file_too_large: split the file`;return { reason: held[2] === 'and differs from the page' ? 'file_database_drift' : 'canonical_path_occupied', message: message!,suggestion: `Sync holds this page's file because gbrain cannot import it; gbrain sources status ${sourceId} names the file${held[1] === 'invalid_fence' ? ', fence and reason' : ', line and key'}. `@@ -100,8 +100,8 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {suggestion: `The target page's stored ${fenceWhere(fence)} does not parse, so nothing was changed. Read the page with get_page, fix that fence `+ '(or write the whole page with put_page, which normalizes what it can and names every row it cannot), then retry.' };if (fence) return { reason: 'invalid_fence', message: message!,- suggestion: `Edit ${fenceWhere(fence)} in the file as the message says and commit the change; never edit the frontmatter for it. `- + 'A managed sync with sync.holds=hold holds such a file instead of blocking; under sync.holds=fail and on company-brain sources it blocks until the file is fixed.' };+ suggestion: `Edit ${fenceWhere(fence)} in the file as the message says and commit the change, or preview its repair with gbrain repair fences --source <source>; never edit the frontmatter for it. `+ + 'A managed sync with sync.holds=hold holds such a file instead of blocking, and the maintenance run repairs the held fences it can; under sync.holds=fail and on company-brain sources it blocks until the file is fixed in the repository.' };// #6188 (UC3): a company-brain source names the fence correction it will not write; the repository commit is the fix.if (code === 'source_writeback_required' && message?.startsWith('Canonical preparation would normalize a facts or takes fence (')) return { reason: code, message,suggestion: 'A company-brain source never rewrites repository files: fix the named fence in the repository, commit it, and resume the sync.' };diff --git a/test/doctor-fence-integrity.test.ts b/test/doctor-fence-integrity.test.tsindex 98fffc26e7..c4cb370147 100644--- a/test/doctor-fence-integrity.test.ts+++ b/test/doctor-fence-integrity.test.ts@@ -3,14 +3,19 @@** 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.+ * with the oldest hold and the `gbrain repair fences --source <id>` preview as+ * the fix for every bucket (#6188 PR4); what the next maintenance run repairs+ * is described as "repaired automatically by the next maintenance run" only+ * while one is active, otherwise the preview then the apply; model-tier+ * fences say why they wait (fences.repair.llm off, budget spent); 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; the WAVE_CHECKS entry counts details.total; 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.+ * twice, the trend threshold is off by one, the fix keeps the edit-and-sync+ * step, "no action needed" appears with no maintenance run, or a cell value+ * reaches the check.* PGLite in-memory ($0); synthetic content only.*/import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';@@ -25,6 +30,11 @@ import { FENCE_NORMALIZATION_WARN_7D, fenceIntegrityResult } from '../src/commanimport { 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';+import { WAVE_CHECKS, remoteWaveHandoff } from '../src/commands/doctor/wave-checks.ts';+import { bannerFindingLine } from '../src/commands/doctor/upgrade-banner.ts';+import { repairForCheck } from '../src/core/repair/registry.ts';+import { LAST_GLOBAL_MAINTENANCE_KEY } from '../src/core/fence-repair/hold-fix.ts';+import { LAST_GLOBAL_AT_KEY } from '../src/core/cycle.ts';const T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';@@ -54,7 +64,7 @@ afterAll(async () => { await engine.disconnect(); for (const root of roots) rmSy// 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);+ for (const key of ['fences.repair.max_usd_per_day', 'fences.repair.max_usd_per_page', 'fences.repair.llm', 'fences.repair.enabled', LAST_GLOBAL_AT_KEY]) await engine.unsetConfig(key);});async function source(files: Record<string, string> = {}) {@@ -85,7 +95,7 @@ describe('fence_integrity doctor check', () => {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 () => {+ test('counts each waiting fence once per source by bucket and tier, names the oldest hold and the fence repair preview', 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);@@ -101,19 +111,81 @@ describe('fence_integrity doctor check', () => {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`);+ // No maintenance run has completed on this brain: never "repaired automatically", the preview then the apply.+ expect(check.message).toContain('not repaired automatically (no maintenance run has completed in the last 24 h)');+ expect(check.message).toContain(`Preview: gbrain repair fences --source ${s.id}`);+ expect(check.fix).toMatchObject({ argv: ['gbrain', 'repair', 'fences', '--source', s.id], actor: 'agent',+ then: { argv: ['gbrain', 'repair', 'fences', '--source', s.id, '--apply'] } });+ expect(check.fix!.why).toContain('--expect <hash>');+ expect(check.fix!.why).toContain('1 need a manual edit');+ expect(details.auto_repair).toMatchObject({ enabled: true, llm: true, active: false, last_maintenance_at: null });const text = JSON.stringify(check);- expect(text).not.toMatch(/repair fences/);+ expect(text).not.toContain('repair frontmatter');+ expect(text).not.toContain('after the user agrees');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 () => {+ test('a stored-page-only source gets the same preview; with a maintenance run active it is repaired automatically by the next run', 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']);+ expect(check.fix!.argv).toEqual(['gbrain', 'repair', 'fences', '--source', s.id]);+ await engine.setConfig(LAST_GLOBAL_AT_KEY, new Date(NOW.getTime() - 3_600_000).toISOString());+ const active = await result();+ expect(active.message).toContain('The deterministic, resolver and model-tier ones are repaired automatically by the next maintenance run');+ expect(active.fix).toMatchObject({ argv: ['gbrain', 'repair', 'fences', '--source', s.id] });+ expect(active.fix!.then).toBeUndefined();+ expect(active.fix!.why).toContain('no action is needed');+ // The maintenance stamp is cycle.ts's key; a stamp older than a day is not an active job, and the pause switch wins.+ expect(LAST_GLOBAL_MAINTENANCE_KEY).toBe(LAST_GLOBAL_AT_KEY);+ await engine.setConfig(LAST_GLOBAL_AT_KEY, new Date(NOW.getTime() - 25 * 3_600_000).toISOString());+ expect((await result()).fix!.then?.argv).toEqual(['gbrain', 'repair', 'fences', '--source', s.id, '--apply']);+ await engine.setConfig(LAST_GLOBAL_AT_KEY, NOW.toISOString());+ await engine.setConfig('fences.repair.enabled', 'false');+ expect((await result()).message).toContain('not repaired automatically (fences.repair.enabled is false)');+ });++ test('model-tier fences say why they wait: model repair off, or today\'s budget spent', async () => {+ const s = await source();+ await stored(s.id, 'notes/model', LLM);+ await engine.setConfig('fences.repair.llm', 'false');+ const off = await result();+ expect(off.message).toContain('Model repair (Tier 3) is off (fences.repair.llm false), so 1 model-tier fence(s) wait');+ expect(off.message).toContain('gbrain config set fences.repair.llm true');+ expect(off.message).toContain('The deterministic and resolver ones are');+ await engine.unsetConfig('fences.repair.llm');+ await engine.setConfig('fences.repair.max_usd_per_day', '0.1');+ const day = new Date('2026-10-03T12:00:00Z');+ const ledger = dailyLedger(engine, FENCE_REPAIR_LEDGER, { now: () => day });+ const held = await ledger.reserve(0.1, { capUsd: 0.1 });+ if (!held.ok) throw new Error('expected a reservation');+ await ledger.dispatch(held.reservation.id);+ await ledger.settle(held.reservation.id, 0.1);+ const spent = await fenceIntegrityResult(engine, { timeoutMs: 60_000, now: () => day });+ expect(spent.message).toContain('Today\'s model repair budget is spent ($0.10 of $0.10), so 1 model-tier fence(s) wait until after 00:00 UTC');+ expect(spent.message).toContain('gbrain config set fences.repair.max_usd_per_day <usd>');+ });++ test('the WAVE_CHECKS entry counts details.total, routes to the fences kind and its banner and remote lines say who repairs it, with no path or claim', async () => {+ const spec = WAVE_CHECKS.find(entry => entry.id === 'fence_integrity')!;+ expect(spec).toMatchObject({ resolution: 'repair', registration: 'doctor.ts' });+ expect(spec.hostOnly).toBeUndefined();+ expect(repairForCheck('fence_integrity')?.kind).toBe('fences');+ const s = await source({ 'notes/held.md': md('Held', MANUAL) });+ await stored(s.id, 'notes/db-only', DETERMINISTIC);+ const check = await spec.run(engine, { sourceIds: [s.id] });+ expect(spec.count(check.details ?? {})).toBe(2);+ const line = bannerFindingLine({ spec, check, state: 'finding' });+ expect(line).toBe('[AGENT] fence_integrity: 2 (not repaired automatically (no maintenance run is active); preview with: gbrain repair fences)');+ await engine.setConfig(LAST_GLOBAL_AT_KEY, new Date().toISOString());+ const active = await spec.run(engine, { sourceIds: [s.id] });+ expect(bannerFindingLine({ spec, check: active, state: 'finding' })).toBe('[AGENT] fence_integrity: 2 (repaired automatically by the next maintenance run, except 1 that need a manual edit; preview with: gbrain repair fences)');+ const remote = (await remoteWaveHandoff(engine, [s.id])).find(entry => entry.name === 'fence_integrity')!;+ expect(remote).toMatchObject({ status: 'warn', details: { host_action: { check_id: 'fence_integrity', state: 'action_required' } } });+ const text = JSON.stringify(remote);+ for (const leak of ['notes/held', 'notes/db-only', s.root, ...SECRETS]) expect(text).not.toContain(leak);+ for (const blob of [line, JSON.stringify(check)]) for (const secret of SECRETS) expect(blob).not.toContain(secret);});test('a census the scan did not finish is partial and never ok, even with nothing found so far', async () => {diff --git a/test/fence-hold-surfaces.test.ts b/test/fence-hold-surfaces.test.tsindex 3cbff60594..b8f1db2a2c 100644--- a/test/fence-hold-surfaces.test.ts+++ b/test/fence-hold-surfaces.test.ts@@ -1,114 +1,254 @@/**- * #6188 PR1 (D6): one hold-repair router. Every surface maps a fence hold to- * reading the page, editing the named fence and syncing; frontmatter holds keep- * their repair preview; a mixed source names both. Remote callers get the- * owner handoff (`tell_user_to_run`). Never frontmatter advice for a fence.+ * #6188 (D6, D16, D17, E35, Codex CEO #7, Codex DX #6): what a fence hold+ * tells an agent on every surface.+ *+ * Protects: one hold-repair router: a fence-only source names+ * `gbrain repair fences --source <id>` and never frontmatter, a+ * frontmatter-only source never names the fence repair, a mixed source names+ * both; a single fence hold's fix is that file's preview+ * (`--only <path>`). The fix follows the hold's state: auto-repair pending+ * with an active maintenance run says no action is needed (read-only+ * preview), an inactive run names the preview then the apply, a manual-only+ * reason or gate rejection names the exact edit, a paid wait names the exact+ * config or pricing command with consent `paid` (renders ask_user), the owner+ * state names the owner host; remote callers get `tell_user_to_run` with a+ * user_message saying whether it clears by itself. Hold items carry the D16+ * structured location and holdLine renders it. No claim, holder or kind text+ * reaches any surface.+ * Fails when: a surface keeps the old "edit the fence then sync" next step,+ * routes a fence hold to frontmatter repair, says "no action needed" with no+ * active maintenance run, renders a paid step as `run`, or copies a cell value.+ * Why new: PR1 pinned the edit-and-sync router; PR4 replaces that contract+ * with the repair command and state-dependent fixes.+ * Seams: none (pure functions; the maintenance state is passed in).*/import { describe, expect, test } from 'bun:test';import { gitHoldDocs, gitHoldFix, gitHoldItem, holdRepairSteps, holdRescreenDue, type GitHoldRecord } from '../src/core/persistence/sync-holds.ts';import { coverageRoute, fileHeldField, heldFilesNotice, hostOperatorFix, recordRoute } from '../src/core/persistence/held-reads.ts';import { heldFileDiagnostic, heldFileMessage, writeFailureDiagnostic } from '../src/core/persistence/verb-errors.ts';import { holdLine } from '../src/commands/sync-diagnostics.ts';-import { deriveNext } from '../src/core/agent-output.ts';+import { deriveNext, renderAction, type Action } from '../src/core/agent-output.ts';import { fenceMessage } from '../src/core/fence-repair/reasons.ts';import { FENCE_VERSION } from '../src/core/fence-repair/refusal.ts';-import { RECOVERY_VERSION } from '../src/core/markdown.ts';+import { fenceFileLine, fenceHoldStatus, type FenceAutoRepair } from '../src/core/fence-repair/hold-fix.ts';+import { parseMarkdown, RECOVERY_VERSION } from '../src/core/markdown.ts';const location = { reason: 'holder_unresolved', fence: 'takes', section: 'body', rows: [3], columns: ['who'], line: 7 } as const;const fenceHold = (extra: Partial<GitHoldRecord> = {}): GitHoldRecord => ({- version: 1, source_id: 'notes-example', incarnation: 'inc', path: 'people/a-founder.md', source_path: 'people/a-founder.md', slug: 'people/a-founder', page_id: 12,+ version: 1, source_id: 'notes-example', incarnation: 'inc', path: 'people/alice-example.md', source_path: 'people/alice-example.md', slug: 'people/alice-example', page_id: 12,code: 'invalid_fence', message: fenceMessage({ ...location, rows: [...location.rows], columns: [...location.columns] }), upstream_version: 'sha', observed_at: '2026-10-01T00:00:00.000Z',held_at: '2026-10-01T00:00:00.000Z', updated_at: '2026-10-01T00:00:00.000Z', run_id: 'run', mode: 'managed',- meta: { reason: 'holder_unresolved', recovery_version: RECOVERY_VERSION, fence: { ...location, rows: [...location.rows], columns: [...location.columns] }, fence_version: FENCE_VERSION },+ meta: { reason: 'holder_unresolved', line: 12, recovery_version: RECOVERY_VERSION, fence: { ...location, rows: [...location.rows], columns: [...location.columns] }, fence_version: FENCE_VERSION },...extra,});+const withMeta = (meta: Partial<GitHoldRecord['meta']>) => fenceHold({ meta: { ...fenceHold().meta, ...meta } });+const manualHold = () => withMeta({ reason: 'takes_kind_unsupported', fence: { reason: 'takes_kind_unsupported', fence: 'takes', section: 'body', rows: [2], columns: ['kind'], line: 6 } });+const tier3Hold = () => withMeta({ reason: 'short_row', fence: { reason: 'short_row', fence: 'facts', section: 'body', rows: [4], columns: [], line: 9 } });const frontmatterHold = (): GitHoldRecord => ({ ...fenceHold(), path: 'notes/broken.md', code: 'invalid_frontmatter',message: 'Invalid YAML frontmatter: key "title" at line 2 continues on unquoted lines.', meta: { reason: 'needs_interpretation', key: 'title', line: 2, recovery_version: RECOVERY_VERSION } });+const repaired = (reason: string, next: string | null, extra: Record<string, unknown> = {}) =>+ ({ reason, tier: 'llm', at: '2026-10-05T00:00:00.000Z', next_attempt_after: next, ...extra }) as GitHoldRecord['meta']['fence_repair'];++const ACTIVE: FenceAutoRepair = { enabled: true, llm: true, last_maintenance_at: '2026-10-06T00:00:00.000Z', active: true };+const INACTIVE: FenceAutoRepair = { enabled: true, llm: true, last_maintenance_at: null, active: false };+const PAUSED: FenceAutoRepair = { enabled: false, llm: true, last_maintenance_at: '2026-10-06T00:00:00.000Z', active: false };+const LLM_OFF: FenceAutoRepair = { ...ACTIVE, llm: false };+const cli = { transport: 'cli' as const, isCallable: () => false, preapproved: () => false, routing: {} } as never;const http = { transport: 'http' as const, isCallable: () => false, preapproved: () => false, routing: {} } as never;+const next = (fix: Action, ctx: never) => renderAction(fix, ctx).next;+const preview = (path?: string) => ['gbrain', 'repair', 'fences', '--source', 'notes-example', ...(path ? ['--only', path] : [])];++describe('one fence hold: the fix by state (D17, E35)', () => {+ test('auto-repair pending with an active maintenance run: no action needed, the read-only preview of that file', () => {+ const fix = gitHoldFix(fenceHold({ meta: { ...fenceHold().meta, fence_repair: repaired('llm_unavailable', '2026-10-06T09:00:00.000Z') } }), ACTIVE);+ expect(fix.argv).toEqual(preview('people/alice-example.md'));+ expect(fix.then).toBeUndefined();+ expect(fix.why).toContain('No action is needed: the next maintenance run repairs it automatically (next attempt after 2026-10-06T09:00:00.000Z)');+ expect([next(fix, cli), next(fix, http)]).toEqual(['run', 'tell_user_to_run']);+ });++ test('maintenance inactive or paused: the preview, then the apply; never "no action needed"', () => {+ for (const auto of [INACTIVE, PAUSED, undefined]) {+ const fix = gitHoldFix(fenceHold(), auto);+ expect(fix.argv).toEqual(preview('people/alice-example.md'));+ expect(fix.then?.argv).toEqual([...preview('people/alice-example.md'), '--apply']);+ expect(fix.why).toContain('--expect <hash>');+ expect(fix.why).not.toContain('No action is needed');+ expect(next(fix, cli)).toBe('run');+ }+ expect(gitHoldFix(fenceHold(), INACTIVE).why).toContain('No maintenance run is active');+ expect(gitHoldFix(fenceHold(), PAUSED).why).toContain('fences.repair.enabled false');+ });++ test('manual-only reasons, gate rejections and model failures name the exact edit through the preview, then the sync', () => {+ const manual = gitHoldFix(manualHold(), ACTIVE);+ expect(manual.argv).toEqual(preview('people/alice-example.md'));+ expect(manual.why).toContain('gbrain will not guess this repair');+ expect(manual.why).toContain('Column `kind` of row(s) 2 in the takes fence');+ expect(manual.then?.argv).toEqual(['gbrain', 'sync', '--source', 'notes-example', '--no-pull']);+ expect(next(manual, cli)).toBe('run');+ const gate = gitHoldFix(withMeta({ fence_repair: repaired('cell_changed', null, { gate: 'f', rows: [3] }) }), ACTIVE);+ expect(fenceHoldStatus(withMeta({ fence_repair: repaired('cell_changed', null, { gate: 'f', rows: [3] }) }).meta, ACTIVE)).toMatchObject({ state: 'manual', reason: 'cell_changed' });+ expect(gate.why).toContain('The proposed repair failed gate f');+ expect(fenceHoldStatus(withMeta({ fence_repair: repaired('llm_malformed', null) }).meta, ACTIVE).state).toBe('manual');+ });++ test('budget, model switch and pricing waits: the exact command with consent paid, which renders ask_user', () => {+ const cases: Array<[string, Partial<GitHoldRecord['meta']>, FenceAutoRepair, string[]]> = [+ ['budget_exhausted', { fence_repair: repaired('budget_exhausted', '2026-10-07T00:00:00.000Z') }, ACTIVE, ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<usd>']],+ ['llm_disabled', {}, LLM_OFF, ['gbrain', 'config', 'set', 'fences.repair.llm', 'true']],+ ['no_pricing', { fence_repair: repaired('no_pricing', null) }, ACTIVE, ['gbrain', 'pricing', 'set', '<model>', '--input', '<usd>', '--output', '<usd>']],+ ];+ for (const [reason, meta, auto, argv] of cases) {+ const record = reason === 'llm_disabled' ? tier3Hold() : withMeta(meta);+ const fix = gitHoldFix(record, auto);+ expect([reason, fenceHoldStatus(record.meta, auto).state]).toEqual([reason, 'paid']);+ expect(fix).toMatchObject({ argv, consent: ['paid'], actor: 'agent', preview_argv: reason === 'llm_disabled' ? preview('people/alice-example.md') : preview('people/alice-example.md') });+ expect(next(fix, cli)).toBe('ask_user');+ expect(fix.why).toContain("the user's call");+ expect(fix.user_message).toContain(argv.join(' '));+ }+ // With the model on, the same Tier 3 hold is ordinary auto-repair work.+ expect(fenceHoldStatus(tier3Hold().meta, ACTIVE).state).toBe('auto');+ });-describe('the per-hold fix', () => {- test('a fence hold with a page reads it, then syncs; a new file lists the hold first; neither mentions frontmatter', () => {- const withPage = gitHoldFix(fenceHold());- expect(withPage.argv).toEqual(['gbrain', 'get', '--source', 'notes-example', '--', 'people/a-founder']);- expect(withPage.then?.argv).toEqual(['gbrain', 'sync', '--source', 'notes-example', '--no-pull']);- expect(withPage.why).toContain('the takes fence (body), row 3, column who, at line 7');- expect(deriveNext(withPage, cli)).toBe('run');- const missing = gitHoldFix(fenceHold({ page_id: null }));- expect(missing.argv).toEqual(['gbrain', 'sources', 'status', 'notes-example', '--json']);- for (const fix of [withPage, missing]) expect(JSON.stringify(fix)).not.toContain('repair frontmatter');- expect(gitHoldFix(frontmatterHold()).argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', 'notes-example', '--include-ambiguous']);+ test('owner_unavailable names the owner-host command for the host operator', () => {+ const fix = gitHoldFix(withMeta({ fence_repair: repaired('owner_unavailable', '2026-10-06T09:00:00.000Z') }), ACTIVE);+ expect(fix).toMatchObject({ argv: preview('people/alice-example.md'), actor: 'host_admin' });+ expect(fix.why).toContain('owner host');+ expect(next(fix, cli)).toBe('tell_user_to_run');});- test('items carry the fence location and the reason anchor; the hold line names the location and the sync', () => {- const item = gitHoldItem(fenceHold());- expect(item).toMatchObject({ code: 'invalid_fence', reason: 'holder_unresolved', fence: location, docs: 'docs/guides/write-refusals.md#fence-holder_unresolved' });+ test('a prepare-time hold reads its receipt reason; a stored-row collision is a manual edit', () => {+ const hold = withMeta({ reason: 'prepare_time', fence: { reason: 'stored_row_collision', fence: 'takes', section: 'body', rows: [2], columns: [], line: null } });+ expect(fenceHoldStatus(hold.meta, ACTIVE).state).toBe('manual');+ expect(gitHoldFix(hold, ACTIVE).why).toContain('was refused against the stored page (stored_row_collision)');+ });+});++describe('structured location (D16)', () => {+ test('items carry fence, section, rows, columns, classes, tier, auto_retry, next_attempt_after and the file line; holdLine renders it', () => {+ const record = withMeta({ fence_repair: repaired('llm_unavailable', '2026-10-06T09:00:00.000Z', { tier: 'resolver' }) });+ const item = gitHoldItem(record, ACTIVE);+ expect(item).toMatchObject({ code: 'invalid_fence', reason: 'holder_unresolved', line: 12, docs: 'docs/guides/write-refusals.md#fence-holder_unresolved',+ fence: { reason: 'holder_unresolved', fence: 'takes', section: 'body', rows: [3], columns: ['who'], line: 7, classes: ['holder_unresolved'], tier: 'resolver',+ auto_retry: true, next_attempt_after: '2026-10-06T09:00:00.000Z' } });+ expect(holdLine(item, 'Held')).toBe(' Held people/alice-example.md: invalid_fence (holder_unresolved) in the takes fence (body), row 3, column who, at line 12; '+ + 'its page keeps its last good revision and is read-only for put_page until the file is repaired. No action needed: the next maintenance run repairs it. '+ + 'Preview: gbrain repair fences --source notes-example --only people/alice-example.md (docs/guides/write-refusals.md#fence-holder_unresolved)');+ expect(holdLine(gitHoldItem(fenceHold(), INACTIVE), 'Held')).toContain('Next: gbrain repair fences --source notes-example --only people/alice-example.md, '+ + 'then gbrain repair fences --source notes-example --only people/alice-example.md --apply');+ expect(holdLine(gitHoldItem(tier3Hold(), LLM_OFF), 'Held')).toContain('Ask the user first, then: gbrain config set fences.repair.llm true');+ expect(gitHoldItem(fenceHold(), INACTIVE).fence).toMatchObject({ auto_retry: false, next_attempt_after: null });expect(gitHoldDocs('invalid_fence', 'prepare_time')).toBe('docs/guides/write-refusals.md#fence-prepare_time');expect(gitHoldDocs('invalid_frontmatter', 'yaml_parse')).toBe('docs/guides/write-refusals.md#invalid_frontmatter-yaml_parse');- const line = holdLine(item, 'Held');- expect(line).toContain('invalid_fence (holder_unresolved) in the takes fence (body), row 3, column who, at line 7');- expect(line).toContain('then gbrain sync --source notes-example --no-pull');+ });++ test('fenceFileLine adds the section start to the section line, for the body and the timeline', () => {+ const content = '---\ntitle: Example\n---\n\n# Example\n\nIntro.\n\n<!--- gbrain:takes:begin -->\n| # | claim |\n<!--- gbrain:takes:end -->\n\n<!-- timeline -->\n\n- 2026-01-01: an event\n';+ const page = parseMarkdown(content, 'people/example.md');+ const lines = content.split('\n');+ const bodyLine = page.compiled_truth.split('\n').indexOf('| # | claim |') + 1;+ expect(lines[fenceFileLine(content, page, { section: 'body', line: bodyLine })! - 1]).toBe('| # | claim |');+ const timelineLine = page.timeline.split('\n').indexOf('- 2026-01-01: an event') + 1;+ expect(lines[fenceFileLine(content, page, { section: 'timeline', line: timelineLine })! - 1]).toBe('- 2026-01-01: an event');+ expect(fenceFileLine(content, page, { section: 'body', line: null })).toBeNull();});test('a fence hold an older fence screen wrote is re-screened; a current one only when retried or its bytes change', () => {expect(holdRescreenDue(fenceHold(), false)).toBe(false);expect(holdRescreenDue(fenceHold(), true)).toBe(true);- expect(holdRescreenDue(fenceHold({ meta: { ...fenceHold().meta, fence_version: FENCE_VERSION - 1 } }), false)).toBe(true);- expect(holdRescreenDue(fenceHold({ meta: { ...fenceHold().meta, fence_version: undefined } }), false)).toBe(true);+ expect(holdRescreenDue(withMeta({ fence_version: FENCE_VERSION - 1 }), false)).toBe(true);+ expect(holdRescreenDue(withMeta({ fence_version: undefined }), false)).toBe(true);expect(holdRescreenDue({ ...frontmatterHold(), code: 'frontmatter_slug_conflict' }, false)).toBe(true);});});-describe('source-level routing (sync results, doctor, read notices, retry-held)', () => {- test('fence-only, frontmatter-only and mixed sources name the right steps', () => {+describe('source-level routing on every surface (D6)', () => {+ test('fence-only, frontmatter-only and mixed sources name the right repair commands', () => {const fences = holdRepairSteps('notes-example', { fences: 2, others: 0 });- expect(fences.argv).toEqual(['gbrain', 'sources', 'status', 'notes-example', '--json']);- expect(fences.text).toContain('gbrain sync --source notes-example --no-pull');+ expect(fences.argv).toEqual(preview());+ expect(fences.commands).toEqual(['gbrain repair fences --source notes-example']);expect(fences.text).not.toContain('frontmatter');const frontmatter = holdRepairSteps('notes-example', { fences: 0, others: 2 });expect(frontmatter.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', 'notes-example']);expect(frontmatter.text).not.toContain('fence');const mixed = holdRepairSteps('notes-example', { fences: 1, others: 1 });- expect(mixed.text).toContain('gbrain repair frontmatter --source notes-example');- expect(mixed.text).toContain('gbrain sync --source notes-example --no-pull');+ expect(mixed.commands).toEqual(['gbrain repair frontmatter --source notes-example', 'gbrain repair fences --source notes-example']);+ expect(holdRepairSteps('notes-example', { fences: 1, others: 0 }, ACTIVE).text).toContain('the next maintenance run repairs the fence holds it can by itself');+ expect(holdRepairSteps('notes-example', { fences: 1, others: 0 }, INACTIVE).text).toContain('nothing repairs the fence holds by itself (no maintenance run is active)');+ expect(holdRepairSteps('notes-example', { fences: 1, others: 0 }, INACTIVE).text).toContain('then run the apply command it prints');});- test('remote callers get the owner handoff for each kind, with no path', () => {- const fence = hostOperatorFix([{ source_id: 'notes-example', route: { fences: 1, others: 0 } }], 'Held.');- expect(deriveNext(fence, http)).toBe('tell_user_to_run');- expect(fence.user_message).toContain("'gbrain sync --source notes-example --no-pull'");- expect(fence.user_message).not.toContain('repair frontmatter');+ test('the held_files notice routes each kind; a remote caller gets the owner handoff with no path', () => {+ const fenceOnly = [{ source_id: 'notes-example', missing: 0, stale: 2, fences: 2 }];+ expect(coverageRoute(fenceOnly[0]!)).toEqual({ fences: 2, others: 0 });+ const local = heldFilesNotice(fenceOnly, false)!;+ expect(local.fix!.argv).toEqual(preview());+ expect(local.fix!.why).not.toContain('frontmatter');+ const remote = heldFilesNotice(fenceOnly, true)!;+ expect(remote.fix).toMatchObject({ actor: 'host_admin', argv: preview() });+ expect(remote.fix!.user_message).toContain("'gbrain repair fences --source notes-example'");+ expect(remote.fix!.user_message).not.toContain('frontmatter');+ expect(deriveNext(remote.fix!, http)).toBe('tell_user_to_run');+ expect(heldFilesNotice([{ source_id: 'notes-example', missing: 1, stale: 0 }], false)!.fix!.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', 'notes-example']);+ const mixed = hostOperatorFix([{ source_id: 'notes-example', route: { fences: 1, others: 1 } }], 'Held.');+ expect(mixed.user_message).toContain("'gbrain repair frontmatter --source notes-example'");+ expect(mixed.user_message).toContain("'gbrain repair fences --source notes-example'");const frontmatter = hostOperatorFix([{ source_id: 'notes-example' }], 'Held.');expect(frontmatter.user_message).toContain("'gbrain repair frontmatter --source notes-example' on the brain host");- const remote = fileHeldField({ record: fenceHold(), revision: 'r1' }, true);- expect(remote.path).toBeUndefined();- expect(remote.fence).toEqual({ ...location, rows: [] });- expect(remote.fix.actor).toBe('host_admin');- expect(fileHeldField({ record: fenceHold(), revision: 'r1' }, false)).toMatchObject({ path: 'people/a-founder.md', fence: location });+ expect(frontmatter.user_message).not.toContain('repair fences');expect(recordRoute(fenceHold())).toEqual({ fences: 1, others: 0 });});- test('the held_files notice routes a fence-only source to the status read and the sync', () => {- const coverage = [{ source_id: 'notes-example', missing: 0, stale: 2, fences: 2 }];- expect(coverageRoute(coverage[0]!)).toEqual({ fences: 2, others: 0 });- const local = heldFilesNotice(coverage, false)!;- expect(local.fix!.argv).toEqual(['gbrain', 'sources', 'status', 'notes-example', '--json']);- expect(local.fix!.why).toContain('gbrain sync --source notes-example --no-pull');- const remote = heldFilesNotice(coverage, true)!;- expect(remote.fix!.actor).toBe('host_admin');- expect(remote.fix!.user_message).not.toContain('repair frontmatter');- // A frontmatter-only source keeps its preview.- expect(heldFilesNotice([{ source_id: 'notes-example', missing: 1, stale: 0 }], false)!.fix!.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', 'notes-example']);+ test('get_page file_held: the local fix is that file\'s preview; the remote read gets tell_user_to_run saying whether it clears by itself (Codex CEO #7)', () => {+ expect(fileHeldField({ record: fenceHold(), revision: 'r1', fenceAuto: ACTIVE }, false)).toMatchObject({ path: 'people/alice-example.md',+ fence: { rows: [3], auto_retry: true }, fix: { argv: preview('people/alice-example.md') } });+ const auto = fileHeldField({ record: fenceHold(), revision: 'r1', fenceAuto: ACTIVE }, true);+ expect(auto.path).toBeUndefined();+ expect(auto.fence).toMatchObject({ rows: [], fence: 'takes', section: 'body' });+ expect(auto.fix).toMatchObject({ actor: 'host_admin', argv: preview() });+ expect(next(auto.fix, http)).toBe('tell_user_to_run');+ expect(auto.fix.user_message).toContain('It clears by itself');+ const inactive = fileHeldField({ record: fenceHold(), revision: 'r1', fenceAuto: INACTIVE }, true);+ expect(inactive.fix.user_message).toContain('It does not clear by itself because no maintenance run is active on the brain host');+ const manual = fileHeldField({ record: manualHold(), revision: 'r1', fenceAuto: ACTIVE }, true);+ expect(manual.fix.user_message).toContain('needs an edit gbrain will not guess');+ const paid = fileHeldField({ record: tier3Hold(), revision: 'r1', fenceAuto: LLM_OFF }, true);+ expect(paid.fix).toMatchObject({ argv: ['gbrain', 'config', 'set', 'fences.repair.llm', 'true'], consent: ['paid'], actor: 'host_admin' });+ expect(next(paid.fix, http)).toBe('tell_user_to_run');+ expect(paid.fix.user_message).toContain('your call');+ for (const field of [auto, inactive, manual, paid]) expect(JSON.stringify(field)).not.toContain('alice-example.md');});- test('write refusals over a held fence file and a blocked fence receipt name the fence edit, never frontmatter', () => {+ test('write refusals over a held fence file name the fence repair, never frontmatter; a blocked fence receipt names both the edit and the preview', () => {const held = heldFileDiagnostic(heldFileMessage('drift', 'invalid_fence'), 'notes-example')!;- expect(held.suggestion).toContain('gbrain sync --source notes-example --no-pull');+ expect(held.suggestion).toContain('gbrain repair fences --source notes-example');expect(held.suggestion).not.toContain('repair frontmatter');expect(heldFileDiagnostic(heldFileMessage('drift', 'invalid_frontmatter'), 'notes-example')!.suggestion).toContain('gbrain repair frontmatter --source notes-example');+ expect(heldFileDiagnostic(heldFileMessage('drift', 'invalid_frontmatter'), 'notes-example')!.suggestion).not.toContain('repair fences');const blocked = writeFailureDiagnostic('invalid_params', fenceHold().message);expect(blocked).toMatchObject({ reason: 'invalid_fence', message: fenceHold().message });expect(blocked.suggestion).toContain('the takes fence (body), row 3');+ expect(blocked.suggestion).toContain('gbrain repair fences');expect(writeFailureDiagnostic('invalid_params', 'The value is invalid.').reason).toBe('invalid_params');});});++describe('location-only privacy (sentinel)', () => {+ test('no claim, holder or kind text reaches a hold item, fix, line, file_held or relay in any state', () => {+ const SECRETS = ['Sentinelclaimq81 renews', 'Sentinelholderq81 Example', 'sentinelkindq81'];+ const records = [fenceHold(), manualHold(), tier3Hold(), withMeta({ fence_repair: repaired('cell_changed', null, { gate: 'f', rows: [3] }) }),+ withMeta({ fence_repair: repaired('budget_exhausted', '2026-10-07T00:00:00.000Z') }), withMeta({ fence_repair: repaired('owner_unavailable', null) })];+ for (const record of records) {+ for (const auto of [ACTIVE, INACTIVE, LLM_OFF, undefined]) {+ const item = gitHoldItem(record, auto);+ const text = JSON.stringify([item, holdLine(item, 'Held'), renderAction(item.fix, cli), renderAction(item.fix, http),+ fileHeldField({ record, revision: 'r1', fenceAuto: auto }, true), fileHeldField({ record, revision: 'r1', fenceAuto: auto }, false)]);+ for (const secret of SECRETS) expect(text).not.toContain(secret);+ expect(text).not.toContain('repair frontmatter');+ }+ }+ });+});diff --git a/test/fence-refusal.test.ts b/test/fence-refusal.test.tsindex 63da5147a7..2821a322e4 100644--- a/test/fence-refusal.test.ts+++ b/test/fence-refusal.test.ts@@ -107,15 +107,14 @@ describe('the shared fence check', () => {});/**- * Every reason PR1 can put in a refusal, hold or receipt. `gbrain repair fences`- * ships in a later release, so none of their messages or fixes may name it.+ * Every reason the screen and the projection can put in a refusal, hold or+ * receipt. #6188 PR4: their holds and source steps route to `gbrain repair+ * fences` (D6), never to frontmatter repair.*/const PR1_REASONS: readonly FenceReason[] = ['repeated_marker', 'missing_begin', 'marker_near_miss', 'unparseable', 'no_header', 'row_before_header','short_row', 'extra_cells', 'enum_unmapped', 'takes_kind_unsupported', 'confidence_out_of_range', 'claim_value_invalid', 'weight_missing','holder_unresolved', 'row_collision', 'quoted_fence_rows', 'stored_row_collision', 'withdrawn_claim_in_malformed_fence', 'prepare_time'];-const UNSHIPPED = /repair fences|repair pass/;--describe('no PR1 message or fix names a command that has not shipped', () => {+describe('every PR1 reason routes to the fence repair, never to frontmatter repair', () => {test('every reason the screen and the projection emit is one PR1 accounts for', () => {for (const [, body, timeline] of cases) expect(PR1_REASONS).toContain(scanCanonicalFences(page(body, timeline)).defects[0]!.reason);});@@ -129,7 +128,7 @@ describe('no PR1 message or fix names a command that has not shipped', () => {}});- test('messages, suggestions and fixes for every PR1 reason point at the page read, the fence edit and the sync', () => {+ test('hold fixes and source steps for every PR1 reason name gbrain repair fences; messages, suggestions and fixes never name frontmatter repair', () => {for (const reason of PR1_REASONS) {const location: FenceMessageLocation = { reason, fence: 'takes', section: 'body', rows: [2], columns: ['who'], line: 5 };const error = fenceOperationError(location, 'notes/example', 'default');@@ -137,9 +136,12 @@ describe('no PR1 message or fix names a command that has not shipped', () => {const hold = prepareTimeFenceHold({ path: 'notes/example.md', sourcePath: 'notes/example.md', working: false }, 'notes/example', 1, location, 'Body.', null);const fix = gitHoldFix({ source_id: 'default', path: 'notes/example.md', code: 'invalid_fence', slug: 'notes/example', page_id: 1,meta: { reason, recovery_version: RECOVERY_VERSION, fence: location } });+ const steps = holdRepairSteps('default', { fences: 1, others: 0 });+ expect(fix.argv).toEqual(['gbrain', 'repair', 'fences', '--source', 'default', '--only', 'notes/example.md']);+ expect(steps.argv).toEqual(['gbrain', 'repair', 'fences', '--source', 'default']);const texts = [error.message, error.suggestion, JSON.stringify(error.fix), receipt?.suggestion, hold.message, JSON.stringify(fix),- writeFailureDiagnostic('invalid_params', error.message).suggestion, holdRepairSteps('default', { fences: 1, others: 0 }).text];- for (const text of texts) expect(text ?? '').not.toMatch(UNSHIPPED);+ writeFailureDiagnostic('invalid_params', error.message).suggestion, steps.text];+ for (const text of texts) expect(text ?? '').not.toContain('repair frontmatter');}});});diff --git a/test/persistence-sync-fence-holds.test.ts b/test/persistence-sync-fence-holds.test.tsindex ba012b3d37..368906dc15 100644--- a/test/persistence-sync-fence-holds.test.ts+++ b/test/persistence-sync-fence-holds.test.ts@@ -1,6 +1,7 @@/**- * #6188 PR1: a malformed facts or takes fence never blocks a managed sync; the- * file is held. A fence the screen refuses is held at freeze; a fence refused+ * #6188: a malformed facts or takes fence never blocks a managed sync; the+ * file is held, and every surface routes it to `gbrain repair fences` (that+ * file's preview for one hold, the source's for a source). A fence the screen refuses is held at freeze; a fence refused* only while being prepared against the stored page (a stored-row collision)* is held in the same invocation from its failed receipt; a cursor an older* release blocked converts on the next sync with no `--retry-failed`.@@ -24,6 +25,8 @@ import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';import { gitHoldStatusLines, readGitHoldStatuses } from '../src/core/persistence/connector-status.ts';import { gitHeldFilesCheck, fenceHoldsBannerNote, frontmatterHoldsBannerNote } from '../src/commands/doctor/checks/git-holds.ts';import { retryHeld } from '../src/commands/sources-retry-held.ts';+import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';+import { remoteWaveHandoff } from '../src/commands/doctor/wave-checks.ts';import { printSyncResult, type SyncOpts, type SyncResult } from '../src/commands/sync.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';@@ -109,29 +112,33 @@ test('a malformed fence among clean files: the sync finishes, holds that file wiexpect(await engine.getPage('people/malformed', { sourceId: s.id })).toBeNull();expect(result.held![0]).toMatchObject({ path: 'people/malformed.md', code: 'invalid_fence', reason: 'holder_unresolved', stale: false,fence: { reason: 'holder_unresolved', fence: 'takes', section: 'body', rows: [1], columns: ['who'] }, docs: 'docs/guides/write-refusals.md#fence-holder_unresolved' });- // A new file has no page to read: the fix lists the hold, then the sync that imports the corrected file. Never frontmatter advice.- expect(result.held![0]!.fix.argv).toEqual(['gbrain', 'sources', 'status', s.id, '--json']);- expect(result.held![0]!.fix.then?.argv).toEqual(['gbrain', 'sync', '--source', s.id, '--no-pull']);- expect(result.holds_fix!.argv).toEqual(['gbrain', 'sources', 'status', s.id, '--json']);+ // #6188 PR4 (D6, Codex DX #6): the hold's fix is that file's fence repair preview, the source's is the source preview. Never frontmatter advice.+ // No maintenance run is active in this brain, so the fix is the preview, then the apply (E35), and the hold records the file line (D16).+ const preview = ['gbrain', 'repair', 'fences', '--source', s.id, '--only', 'people/malformed.md'];+ expect(result.held![0]!.fix.argv).toEqual(preview);+ expect(result.held![0]!.fix.then?.argv).toEqual([...preview, '--apply']);+ expect(result.held![0]).toMatchObject({ line: 9, fence: { tier: 'resolver', auto_retry: false, next_attempt_after: null, classes: ['holder_unresolved'] } });+ expect(result.holds_fix!.argv).toEqual(['gbrain', 'repair', 'fences', '--source', s.id]);for (const text of [JSON.stringify(result.held), result.holds_fix!.why]) expect(text).not.toContain('repair frontmatter');const text = printed(result);- expect(text).toContain('Held people/malformed.md: invalid_fence (holder_unresolved) in the takes fence (body), row 1, column who, at line');- expect(text).toContain(`gbrain sync --source ${s.id} --no-pull`);+ expect(text).toContain('Held people/malformed.md: invalid_fence (holder_unresolved) in the takes fence (body), row 1, column who, at line 9');+ expect(text).toContain(`gbrain repair fences --source ${s.id} --only people/malformed.md`);const status = (await readGitHoldStatuses(engine, [s.id])).get(s.id)!;const lines = gitHoldStatusLines(s.id, status).join('\n');expect(lines).toContain('people/malformed.md: invalid_fence (holder_unresolved) in the takes fence (body)');// Privacy sentinel: no claim, holder or kind text in holds, results, printed output or status.const rows = await engine.executeRaw<{ completed_keys: unknown }>("SELECT completed_keys FROM op_checkpoints WHERE op LIKE 'sync-hold%' AND fingerprint LIKE $1", [`${s.id}:%`]);for (const blob of [JSON.stringify(rows), JSON.stringify(result), text, lines, JSON.stringify(status)]) expectNoSecrets(blob);- // `gbrain repair fences` has not shipped: nothing PR1 prints may send an agent to it.- for (const blob of [JSON.stringify(result), text, lines]) expect(blob).not.toMatch(/repair fences|repair pass/);- // Doctor routes a fence-only source to the status read and the sync, never to frontmatter repair.+ expect(lines).toContain(`gbrain repair fences --source ${s.id} --only people/malformed.md`);+ // Doctor routes a fence-only source to the fence repair preview, never to frontmatter repair.const doctor = await gitHeldFilesCheck(engine, [s.id]);- expect(doctor).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'sources', 'status', s.id, '--json'] } });- expect(doctor.message).toContain(`gbrain sync --source ${s.id} --no-pull`);+ expect(doctor).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'repair', 'fences', '--source', s.id] }, details: { fences: 1, auto_repair: { active: false } } });+ expect(doctor.message).toContain(`gbrain repair fences --source ${s.id}`);expect(doctor.message).not.toContain('repair frontmatter');- // retry-held names the fence edit for what still refuses.- expect((await retryHeld(engine, s.id, { dryRun: false })).next_action).toContain('edit the fence');+ // retry-held names the fence repair preview for what still refuses.+ const retry = (await retryHeld(engine, s.id, { dryRun: false })).next_action;+ expect(retry).toContain(`gbrain repair fences --source ${s.id}`);+ expect(retry).not.toContain('repair frontmatter');s.write('people/malformed.md', takesPage('Malformed', take(1, 'Synthetic take', 'world'))); commit(s.root, 'fix the holder');const fixed = await s.sync();@@ -160,12 +167,13 @@ test('forced probe: a fence that passes the screen but collides with a stored taexpect(await s.ledger()).toEqual([]);expect(result.held![0]).toMatchObject({ path: 'people/probe.md', code: 'invalid_fence', reason: 'prepare_time', stale: true,fence: { reason: 'stored_row_collision', fence: 'takes', section: 'body', rows: [2] }, docs: 'docs/guides/write-refusals.md#fence-prepare_time' });- // A page exists, so the fix reads it first.- expect(result.held![0]!.fix.argv).toEqual(['gbrain', 'get', '--source', s.id, '--', 'people/probe']);+ // A stored-row collision is a manual edit: that file's preview names it, then the sync imports the corrected file.+ expect(result.held![0]!.fix.argv).toEqual(['gbrain', 'repair', 'fences', '--source', s.id, '--only', 'people/probe.md']);+ expect(result.held![0]!.fix.then?.argv).toEqual(['gbrain', 'sync', '--source', s.id, '--no-pull']);expect((await engine.readPageSnapshot('people/probe', { sourceId: s.id }))!.revision).toBe(before);expect(await engine.executeRaw('SELECT row_num,claim FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY row_num', [s.id, 'people/probe'])).toEqual([{ row_num: 1, claim: 'Synthetic take' }, { row_num: 2, claim: 'Database-only take' }]);- for (const blob of [JSON.stringify(result), printed(result), JSON.stringify(failed)]) { expectNoSecrets(blob); expect(blob).not.toMatch(/repair fences|repair pass/); }+ for (const blob of [JSON.stringify(result), printed(result), JSON.stringify(failed)]) { expectNoSecrets(blob); expect(blob).not.toContain('repair frontmatter'); }// The next run neither re-admits the held bytes nor mints another receipt.expect(await s.sync()).toMatchObject({ status: 'up_to_date', holds_outstanding: 1 });expect(await s.failedRequests()).toHaveLength(1);@@ -181,7 +189,23 @@ test('sync.holds=fail blocks with the typed refusal; the next sync after the upg// The exact text a pre-#6188 release stored for this refusal, with no durable detail.await engine.executeRaw('UPDATE persistence_requests SET error_message=$2,error_detail=NULL WHERE request_id=$1::uuid',[failed!.request_id, 'A canonical facts or takes fence cannot be parsed losslessly.']);- expect((await fenceHoldsBannerNote(engine)) ?? '').toContain(`gbrain sync --source ${s.id} --no-pull`);+ const fenceNote = (await fenceHoldsBannerNote(engine)) ?? '';+ for (const part of [`gbrain sync --source ${s.id} --no-pull`, 'recovers each with no command', 'malformed fence(s) are known so far',+ 'nothing repairs them by itself until a maintenance run is active', 'Preview (read-only, no model call): gbrain repair fences',+ 'gbrain config set fences.repair.enabled false']) expect(fenceNote).toContain(part);+ expect(fenceNote).not.toMatch(/--apply|repairable after the user agrees/);+ expectNoSecrets(fenceNote);+ // The whole banner: the fence_holds note, the fence_integrity finding (no maintenance run is active here) and no applying command.+ const banner = (await postUpgradeRecoveryBanner(engine, 'host')).join('\n');+ expect(banner).toContain('[AGENT] fence_holds: ');+ expect(banner).toMatch(/\[AGENT\] {3}fence_integrity: \d+ \(not repaired automatically \(no maintenance run is active\); preview with: gbrain repair fences\)/);+ expect(banner).not.toMatch(/--apply|--yes/);+ expectNoSecrets(banner);+ // The remote doctor's host-action line names no path and no claim.+ const remote = (await remoteWaveHandoff(engine, [s.id])).find(line => line.name === 'fence_integrity')!;+ expect(remote).toMatchObject({ status: 'warn', details: { host_action: { check_id: 'fence_integrity', state: 'action_required' } } });+ for (const leak of ['people/malformed', s.root]) expect(JSON.stringify(remote)).not.toContain(leak);+ expectNoSecrets(JSON.stringify(remote));expect((await frontmatterHoldsBannerNote(engine)) ?? '').not.toContain(s.id);await engine.unsetConfig('sync.holds');const converted = await s.sync();diff --git a/test/post-upgrade-banner.test.ts b/test/post-upgrade-banner.test.tsindex 02e8c16478..8e41263073 100644--- a/test/post-upgrade-banner.test.ts+++ b/test/post-upgrade-banner.test.ts@@ -16,6 +16,8 @@ import { upsertOpenLoop } from '../src/core/loops/loops-store.ts';import { managedBrain } from './helpers/managed-brain.ts';import { withEnv } from './helpers/with-env.ts';import { put, waveBrain } from './helpers/wave-fixture.ts';+import { bannerFindingLine } from '../src/commands/doctor/upgrade-banner.ts';+import { WAVE_CHECKS } from '../src/commands/doctor/wave-checks.ts';/** A CLAUDE_CONFIG_DIR holding one gbrain claude-cli scratch-project transcript (session `sess-self`). */function selfCaptureHost(): string {@@ -82,6 +84,32 @@ describe('post-upgrade recovery banner', () => {});+describe('fence findings in the banner (#6188, D7)', () => {+ const spec = (id: string) => WAVE_CHECKS.find(entry => entry.id === id)!;+ const line = (id: string, details: Record<string, unknown>) => bannerFindingLine({ spec: spec(id), check: { name: id, status: 'warn', message: '', details }, state: 'finding' });+ const sources = [{ by_tier: { manual: 1 } }, { by_tier: { manual: 0 } }];++ test('fence_integrity is repaired automatically by the next maintenance run while one is active, and says why not otherwise', () => {+ expect(line('fence_integrity', { total: 3, sources, auto_repair: { enabled: true, active: true } }))+ .toBe('[AGENT] fence_integrity: 3 (repaired automatically by the next maintenance run, except 1 that need a manual edit; preview with: gbrain repair fences)');+ expect(line('fence_integrity', { total: 3, sources, auto_repair: { enabled: true, active: false } }))+ .toBe('[AGENT] fence_integrity: 3 (not repaired automatically (no maintenance run is active); preview with: gbrain repair fences)');+ expect(line('fence_integrity', { total: 3, sources, auto_repair: { enabled: false, active: false } })).toContain('(not repaired automatically (fences.repair.enabled is false)');+ for (const details of [{ total: 3, auto_repair: { active: true } }, { total: 3, auto_repair: { active: false } }]) {+ expect(line('fence_integrity', details)).not.toMatch(/after the user agrees|--apply|--yes/);+ }+ });++ test('a fence-only git_held_files finding names the fence repair; a mixed one names both previews', () => {+ const fenceOnly = line('git_held_files', { held: 2, fences: 2, source_ids: ['notes-example'], auto_repair: { enabled: true, active: true } });+ expect(fenceOnly).toBe('[AGENT] git_held_files: 2 (fence holds: repaired automatically by the next maintenance run; preview with: gbrain repair fences --source notes-example)');+ const mixed = line('git_held_files', { held: 3, fences: 1, source_ids: ['notes-example'], auto_repair: { enabled: true, active: false } });+ expect(mixed).toContain('explicit_kind_required; preview with: gbrain repair frontmatter --source notes-example');+ expect(mixed).toContain('fence holds: not repaired automatically (no maintenance run is active); preview with: gbrain repair fences --source notes-example');+ expect(line('git_held_files', { held: 2, source_ids: ['notes-example'] })).toBe('[AGENT] git_held_files: 2 (explicit_kind_required; preview with: gbrain repair frontmatter --source notes-example)');+ });+});+describe('gbrain post-upgrade', () => {const home = mkdtempSync(join(tmpdir(), 'gbrain-banner-cli-'));const claude = selfCaptureHost();diff --git a/test/sync-hold-surfaces.test.ts b/test/sync-hold-surfaces.test.tsindex 184b753161..68f3d89d7a 100644--- a/test/sync-hold-surfaces.test.ts+++ b/test/sync-hold-surfaces.test.ts@@ -5,6 +5,16 @@* `sync --retry-held` refuses with the pointer; Git holds never block writer* deactivation or activation (X14); a put_page refused over a held file names* the hold instead of reconciliation (E26).+ *+ * #6188 PR4 (D6, D16, D17, E35, Codex CEO #7): for a fence-only, a+ * frontmatter-only and a mixed source, every DB-backed surface (sources+ * status JSON and text, retry-held, doctor git_held_files and its banner+ * line, the sync hold report, get_page file_held, the held_files notice, the+ * held-file write refusal) names the right repair command and a fence-only+ * source never mentions frontmatter; a fence hold's rendered next follows its+ * state on the CLI and HTTP transports with the maintenance run active and+ * inactive; a remote status read returns the owner handoff; no claim, holder+ * or kind text reaches any of them.*/import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';import { randomUUID } from 'node:crypto';@@ -30,6 +40,16 @@ import { managedBrain } from './helpers/managed-brain.ts';import { waitFor } from './helpers/wait-for.ts';import { put } from './helpers/wave-fixture.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { buildHoldReport, readSyncHoldPolicy } from '../src/core/persistence/sync-holds.ts';+import { heldFilesNotice, readHeldCoverage } from '../src/core/persistence/held-reads.ts';+import { heldFileDiagnostic } from '../src/core/persistence/verb-errors.ts';+import { gitHeldFilesCheck } from '../src/commands/doctor/checks/git-holds.ts';+import { WAVE_CHECKS } from '../src/commands/doctor/wave-checks.ts';+import { bannerFindingLine } from '../src/commands/doctor/upgrade-banner.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { cliRenderContext, renderAction, type Action } from '../src/core/agent-output.ts';+import { fenceMessage } from '../src/core/fence-repair/reasons.ts';+import { RECOVERY_VERSION } from '../src/core/markdown.ts';type HoldInput = Omit<GitHoldRecord, 'version' | 'held_at' | 'updated_at'>;@@ -287,3 +307,147 @@ describe('Git holds and writer mode changes (X14)', () => {await writeGitHold(engine, hold('default', await incarnationOf(engine, 'default'), 'notes/held.md', { run_id: randomUUID() }));} }), 180_000);});++describe('#6188 fence holds on every DB-backed surface: the router and the fix by state', () => {+ let engine: PGLiteEngine;+ let home: string;+ const SECRETS = ['Sentinelclaimq92 renews yearly', 'Sentinelholderq92 Example', 'sentinelkindq92'];+ const http = { transport: 'http' as const, isCallable: () => false, preapproved: () => false, routing: {} } as never;+ const cli = cliRenderContext();+ const getPage = operations.find(op => op.name === 'get_page')!;+ const fenceAt = { reason: 'holder_unresolved' as const, fence: 'takes' as const, section: 'body' as const, rows: [3], columns: ['who'], line: 7 };+ const fenceHold = (sourceId: string, incarnation: string, path: string, pageId: number | null, extra: Partial<HoldInput['meta']> = {}): HoldInput => hold(sourceId, incarnation, path, {+ code: 'invalid_fence', page_id: pageId, message: fenceMessage(fenceAt),+ meta: { reason: 'holder_unresolved', line: 12, recovery_version: RECOVERY_VERSION, fence: fenceAt, fence_version: 1, ...extra } });+ const ctx = (sourceId: string, remote: boolean) => ({ engine, config: { engine: 'pglite', embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} },+ dryRun: false, remote, sourceId, emitNotice() {}, emitResponseMeta() {} }) as unknown as OperationContext;+ const pageId = async (sourceId: string, slug: string) => {+ await engine.putPage(slug, { type: 'note', title: 'Held page', compiled_truth: 'Last good body.' }, { sourceId });+ return Number((await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]!.id);+ };++ beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ home = mkdtempSync(join(tmpdir(), 'gbrain-fence-surfaces-'));+ for (const id of ['fences-only', 'frontmatter-only', 'mixed-holds']) {+ mkdirSync(join(home, id));+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, join(home, id)]);+ }+ const fenceInc = await incarnationOf(engine, 'fences-only');+ await writeGitHold(engine, fenceHold('fences-only', fenceInc, 'people/held-a.md', await pageId('fences-only', 'people/held-a')));+ await writeGitHold(engine, fenceHold('fences-only', fenceInc, 'people/held-b.md', null, {+ reason: 'takes_kind_unsupported', fence: { reason: 'takes_kind_unsupported', fence: 'takes', section: 'body', rows: [2], columns: ['kind'], line: 6 } }));+ await writeGitHold(engine, hold('frontmatter-only', await incarnationOf(engine, 'frontmatter-only'), 'notes/broken.md'));+ const mixedInc = await incarnationOf(engine, 'mixed-holds');+ await writeGitHold(engine, hold('mixed-holds', mixedInc, 'notes/broken.md'));+ await writeGitHold(engine, fenceHold('mixed-holds', mixedInc, 'people/held-c.md', null));+ }, 120_000);++ afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); }, 60_000);++ const expectRoute = (text: string, kind: 'fences' | 'frontmatter' | 'mixed', sourceId: string) => {+ if (kind !== 'frontmatter') expect(text).toContain(`gbrain repair fences --source ${sourceId}`);+ if (kind !== 'fences') expect(text).toContain(`gbrain repair frontmatter --source ${sourceId}`);+ if (kind === 'fences') expect(text).not.toContain('repair frontmatter');+ if (kind === 'frontmatter') expect(text).not.toContain('repair fences');+ for (const secret of SECRETS) expect(text).not.toContain(secret);+ };+ const SOURCES = [['fences-only', 'fences'], ['frontmatter-only', 'frontmatter'], ['mixed-holds', 'mixed']] as const;++ test('every surface names the right repair command for fence-only, frontmatter-only and mixed sources (D6)', async () => {+ for (const [sourceId, kind] of SOURCES) {+ const status = JSON.parse(await captured(() => runSources(engine, ['status', sourceId, '--json']))).sources[0].git_holds;+ for (const item of status.items) {+ if (item.code === 'invalid_fence') expect(item.fix.argv).toEqual(['gbrain', 'repair', 'fences', '--source', sourceId, '--only', item.path]);+ else expect(item.fix.argv.slice(0, 3)).toEqual(['gbrain', 'repair', 'frontmatter']);+ }+ const text = await captured(() => runSources(engine, ['status', sourceId]));+ if (kind !== 'frontmatter') expect(text).toContain(`gbrain repair fences --source ${sourceId} --only`);+ if (kind === 'fences') expect(text).not.toContain('repair frontmatter');+ expectRoute((await retryHeld(engine, sourceId, { dryRun: false })).next_action, kind, sourceId);+ const doctor = await gitHeldFilesCheck(engine, [sourceId]);+ expectRoute(doctor.message, kind, sourceId);+ expect(doctor.fix!.argv).toEqual(kind === 'fences' ? ['gbrain', 'repair', 'fences', '--source', sourceId] : ['gbrain', 'repair', 'frontmatter', '--source', sourceId]);+ const banner = bannerFindingLine({ spec: WAVE_CHECKS.find(spec => spec.id === 'git_held_files')!, check: doctor, state: 'finding' });+ expectRoute(banner, kind, sourceId);+ const report = await buildHoldReport(engine, { sourceId, incarnation: await incarnationOf(engine, sourceId), runId: 'none', remote: false,+ policy: await readSyncHoldPolicy(engine), screened: 0 });+ expectRoute(`${report.holds_fix!.argv!.join(' ')} ${report.holds_fix!.why}`, kind, sourceId);+ const remote = await buildHoldReport(engine, { sourceId, incarnation: await incarnationOf(engine, sourceId), runId: 'none', remote: true,+ policy: await readSyncHoldPolicy(engine), screened: 0 });+ expect(remote.holds_fix!.actor).toBe('host_admin');+ expectRoute(remote.holds_fix!.user_message!, kind, sourceId);+ const coverage = await readHeldCoverage(engine, { sourceId });+ const notice = heldFilesNotice(coverage, false)!.fix!;+ expectRoute(`${notice.argv!.join(' ')} ${notice.why}`, kind, sourceId);+ expectRoute(heldFilesNotice(coverage, true)!.fix!.user_message!, kind, sourceId);+ }+ expect(heldFileDiagnostic(heldFileMessage('drift', 'invalid_fence'), 'fences-only')!.suggestion).toContain('gbrain repair fences --source fences-only');+ });++ test('a fence hold\'s rendered next follows its state on CLI and HTTP, with the maintenance run inactive and active (D17, E35)', async () => {+ const items = async () => {+ const status = JSON.parse(await captured(() => runSources(engine, ['status', 'fences-only', '--json']))).sources[0].git_holds.items as Array<{ path: string; fix: Action; fence: Record<string, unknown> }>;+ return Object.fromEntries(status.map(item => [item.path, item]));+ };+ const inactive = await items();+ // Inactive: the auto-retry hold is the preview, then the apply; the manual one is the preview, then the sync. Never "no action needed".+ expect(renderAction(inactive['people/held-a.md']!.fix, cli)).toMatchObject({ next: 'run', then: { argv: ['gbrain', 'repair', 'fences', '--source', 'fences-only', '--only', 'people/held-a.md', '--apply'] } });+ expect(inactive['people/held-a.md']!.fix.why).not.toContain('No action is needed');+ expect(inactive['people/held-a.md']!.fence).toMatchObject({ tier: 'resolver', auto_retry: false, classes: ['holder_unresolved'] });+ expect(renderAction(inactive['people/held-b.md']!.fix, cli)).toMatchObject({ next: 'run', then: { argv: ['gbrain', 'sync', '--source', 'fences-only', '--no-pull'] } });+ for (const item of Object.values(inactive)) expect(renderAction(item.fix, http).next).toBe('tell_user_to_run');++ // A completed brain-wide maintenance job is the evidence that the maintenance run is active.+ await engine.executeRaw(`INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'autopilot-global-maintenance', 'completed', '{}'::jsonb, 'default', 0, now(), now())`);+ try {+ const active = await items();+ expect(active['people/held-a.md']!.fix.why).toContain('No action is needed: the next maintenance run repairs it automatically');+ expect(active['people/held-a.md']!.fix.then).toBeUndefined();+ expect(active['people/held-a.md']!.fence).toMatchObject({ auto_retry: true });+ expect(renderAction(active['people/held-a.md']!.fix, cli).next).toBe('run');+ expect(active['people/held-b.md']!.fix.why).toContain('gbrain will not guess this repair');+ // Model repair off: a Tier 3 hold waits on a paid setting, which the CLI renders as ask_user.+ await engine.setConfig('fences.repair.llm', 'false');+ await writeGitHold(engine, fenceHold('fences-only', await incarnationOf(engine, 'fences-only'), 'people/held-d.md', null, {+ reason: 'short_row', fence: { reason: 'short_row', fence: 'facts', section: 'body', rows: [4], columns: [], line: 9 } }));+ const paid = (await items())['people/held-d.md']!;+ expect(renderAction(paid.fix, cli)).toMatchObject({ next: 'ask_user', consent: ['paid'], argv: ['gbrain', 'config', 'set', 'fences.repair.llm', 'true'] });+ expect(renderAction(paid.fix, http).next).toBe('tell_user_to_run');+ const text = await captured(() => runSources(engine, ['status', 'fences-only']));+ expect(text).toContain('No action needed: the next maintenance run repairs it.');+ expect(text).toContain('Ask the user first, then: gbrain config set fences.repair.llm true');+ } finally {+ await engine.executeRaw("DELETE FROM minion_jobs WHERE name='autopilot-global-maintenance'");+ await engine.unsetConfig('fences.repair.llm');+ await clearHold('fences-only', 'people/held-d.md');+ }+ });++ test('a remote status read of a held fence returns the owner handoff, saying whether it clears by itself, with no path (Codex CEO #7)', async () => {+ const local = await getPage.handler(ctx('fences-only', false), { slug: 'people/held-a' }) as Record<string, any>;+ expect(local.file_held).toMatchObject({ code: 'invalid_fence', path: 'people/held-a.md', line: 12,+ fence: { fence: 'takes', section: 'body', rows: [3], columns: ['who'], classes: ['holder_unresolved'] },+ fix: { argv: ['gbrain', 'repair', 'fences', '--source', 'fences-only', '--only', 'people/held-a.md'] } });+ const remote = await getPage.handler(ctx('fences-only', true), { slug: 'people/held-a' }) as Record<string, any>;+ expect(remote.file_held.path).toBeUndefined();+ expect(remote.file_held.fence.rows).toEqual([]);+ expect(remote.file_held.fix).toMatchObject({ actor: 'host_admin', argv: ['gbrain', 'repair', 'fences', '--source', 'fences-only'] });+ expect(renderAction(remote.file_held.fix, http).next).toBe('tell_user_to_run');+ expect(remote.file_held.fix.user_message).toContain('It does not clear by itself because no maintenance run is active on the brain host');+ await engine.setConfig('autopilot.last_global_at', new Date().toISOString());+ try {+ const active = await getPage.handler(ctx('fences-only', true), { slug: 'people/held-a' }) as Record<string, any>;+ expect(active.file_held.fix.user_message).toContain('It clears by itself');+ expect(active.file_held.fence.auto_retry).toBe(true);+ } finally { await engine.unsetConfig('autopilot.last_global_at'); }+ const text = JSON.stringify(remote.file_held);+ for (const hidden of ['people/held-a.md', home, ...SECRETS]) expect(text).not.toContain(hidden);+ });++ async function clearHold(sourceId: string, path: string) {+ const { clearGitHold } = await import('../src/core/persistence/sync-holds.ts');+ await clearGitHold(engine, { sourceId, incarnation: await incarnationOf(engine, sourceId), path, observedAt: '2999-01-01T00:00:00.000Z' });+ }+});