Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): content lane runner, gbrain repair content, content_repair cycle phase, sync unblock repairs, docs (#6377 lane C)
garrytan8a94aa6fba5b
diff --git a/AGENTS.md b/AGENTS.mdindex d7d6652484..de3cb2cf65 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -130,14 +130,19 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contfiles through `put_page`/`capture` or a YAML serializer and check generatedcontent with `gbrain frontmatter validate --stdin --path <p>`. Walkthrough:[held files](docs/guides/repair.md#held-files). A hold with code- `invalid_fence` is a facts or takes table, not frontmatter, and clears- automatically on the next maintenance run. `gbrain repair fences --source <id>`- previews the repair and its printed apply command runs it now, with no- extra consent; a `manual` reason needs the edit the hold names (read the- page with `gbrain get --source <id> -- <slug>`, edit only that fence,- commit, `gbrain sync --source <id> --no-pull`). Raising spend+ `invalid_fence` or `frontmatter_slug_conflict` is about the file's content,+ not its YAML, and the content-repair lane clears it by itself: the next+ maintenance run repairs what it can, `gbrain sync unblock --source <id>+ --apply` does it now with a receipt per file, and+ `gbrain repair content --source <id>` previews every lane kind (its printed+ apply command runs with no extra consent). A hold the lane marks+ `needs_human` (a manual fence edit, a recommended page merge, an exposed+ tail on a world page) is listed in `gbrain sync status --source <id> --json`+ with its paragraph: relay it, make or approve the edit it names, commit,+ `gbrain sync --source <id> --no-pull`. Raising spend(`fences.repair.max_usd_per_day`, `fences.repair.llm true`) is the user's- call ([fence holds](docs/guides/write-refusals.md#invalid_fence)). A hold+ call ([the lane](docs/guides/repair.md#content-lane),+ [fence holds](docs/guides/write-refusals.md#invalid_fence)). A holdwith code `preparation_stalled` (or a managed catch-up that stops`preparation_abandoned` / `preparation_systemic`, or a write receipt with thatcode) means the write owner stalled, not the file: no repair applies. Rundiff --git a/TODOS.md b/TODOS.mdindex 7b98ad92e8..f02bacd035 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,12 @@# TODOS+## Content-repair lane follow-ups (filed 2026-10-09, GBRA-72, #6377)++Deferred by the plan (`docs/plans/2026-10-09-001-fix-content-repair-lane-6377-plan.md`, §2 B4 and §8 rows 4-7). The lane recommends a page merge and never executes one; interpretive frontmatter fixes stay consent-gated.++- [ ] **P2 — A page merge executor for `merge_recommended` holds.** **What:** a `frontmatter_slug_conflict` hold whose two pages describe the same thing ends in `merge_recommended` (`meta.content_repair.action: merge_into`, the canonical slug on the hold, the paragraph in `sync status`), and a person merges the unique sections by hand. The only merge primitive is the phantom-redirect shape (`cycle/phantom-redirect.ts`, `phantom-redirect-managed.ts`), which refuses custom frontmatter and timeline residue; `deletePageThrough` is best-effort and takes no commit subject. **Fix (Codex's requirements, outside review of the plan):** a coordinated two-page intent that binds both page ids, both revisions, the source incarnation, the owner epoch and both file hashes, so a concurrent writer on either page fails the merge instead of being overwritten; withdrawals moved before facts (a withdrawn claim must stay withdrawn after the merge); metadata, visibility, tags and timeline rows preserved or the merge refused (never silently dropped, never loosened); a revision-bound deletion of the duplicate with a redirect alias left behind; database-aware recovery for a merge that dies between the two writes (the recovery path finds both halves from the receipt, not from the files); and a concurrent-writer test that edits the duplicate between the plan and the apply and proves nothing is lost. The eval's hard-failure rule (`evals/content-repair-judgment/`) gates which model may recommend a merge; the executor runs only on a recommendation the user approved by hash. Until then `gbrain sync status` names the canonical page and nothing is merged.+- [ ] **P3 — Unattended interpretation of recoverable frontmatter.** **What:** the issue's brain needed 198 YAML frontmatter repairs in one week (`invalid_frontmatter` with `needs_interpretation`: folded title lines, duplicated keys, unclosed lists), each applied by an external agent against `gbrain repair frontmatter --include-ambiguous`; the lane leaves them consent-gated because every one changes what the file says. **Fix:** classify the recoverable shapes whose interpretation is unique (a continuation line that can only belong to the previous key, a duplicate key with byte-identical values) and let the lane apply those unattended with a receipt, keeping the rest (`ambiguous_identity_key`, `ambiguous_protected_key`, a duplicate key with two values) on the hash-bound consent path; measure on the issue's week of repairs before turning any shape on by default.+## Managed sync reliability contract follow-ups (filed 2026-10-08, GBRA-61, #6317)Deferred by the plan (`docs/plans/2026-10-08-001-fix-managed-sync-reliability-contract-6317-plan.md`, §7 and ENG-10). One consumer per host ships as a preference; these are the pieces that would make it a guarantee or extend it.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex d3292cf533..9e76065c24 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -4,6 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `take-supersession` (#5886 relinks takes supersession chains from journal, stored-pointer or forced fence-structure evidence; ambiguous pages are reported with the manual edit, never rewritten; `src/core/repair/take-supersession.ts`), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `gbrain repair fences [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff] [--no-llm] [--max-usd <n>] [--apply [--expect <hash>]]` repairs malformed facts and takes fences (#6188, `src/core/repair/fences.ts`). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs; flags a kind does not take name the kinds that do (`--only`/`--skip`/`--diff`: frontmatter, fences; `--slug`: fences; `--yes`: frontmatter); `--expect` is accepted for explicit-only and preview-bound kinds, `--include-ambiguous` for explicit-only kinds; `--max-usd <n>` and `--no-llm` only for `spends: 'llm'` kinds (a non-negative USD amount that only lowers the kind's cap), and on any other kind `--max-usd` names the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>` (hash from `doctor --remediation-plan --json`), as `--max-cost` always does. Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. An apply with a report hook prints `repaired N; still waiting: <reason>=<count>` (never a repair count it did not make) and a partial scan; a stop prints its `fix` command and the consent it asks for. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost (plus, for a `spends: 'llm'` kind, the paid-model estimate or spend and what is left under today's cap) and capacity, and the apply command; `--json` has the same fields. The dry run lists the kinds that may queue paid embeddings and, when a result carries `cost.llm_usd`, `Kinds that may call a paid model` with the summed estimate and the cap left. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`.+- `src/commands/repair-content.ts` — `gbrain repair content [--source <id>] [--only <path>]... [--skip <path>]... [--no-llm] [--max-usd <n>] [--diff] [--apply [--expect <h1>[,<h2>]]] [--json]` (#6377): the content-repair lane as one command. `content` is parsed by `repair.ts`'s strict flag grammar like a kind (`CONTENT_LANE`; `--only`/`--skip`/`--diff`, `--no-llm`, `--max-usd` and `--expect` are accepted for it, `--slug`, `--yes`, `--include-ambiguous` and `--all` refuse) and dispatched before the kind check; it is a lane, not a `RepairKind`: no registry entry, no cursor of its own, listed under "Lanes:" in `REPAIR_HELP`. `runRepairContentCommand` resolves the scope, runs `runContentLane` and prints each kind's result through `renderRepairResult` plus a lane line (spend, allowance left, each kind's hash, every stop, the apply command); `--json` prints `{ lane, scope, mode, kinds, results[] (with `paid`), preview_hashes, cost, stopped, paid_kinds, apply_command }`. A kind's stop sets exit verdict 1; a wrong `--expect` count is `invalid_params` with the preview as its fix. Test: `test/repair-content.test.ts`.- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--yes] [--max-usd USD] [--repo PATH]`. W4.5: re-embedding is paid, so `runReindex(engine, args, { authorized?, interactive? })` calls `requireReindexConsent` (`src/core/reindex-consent.ts`) after the dry-run return and before the managed dispatch for every caller unless `--no-embed` or `authorized` (the upgrade path's TTY yes, the job handler's stored spend record); `src/cli/commands/reindex.ts` renders the exit-3 consent refusal and `cost_cap_exceeded`. The approved finite cap runs the inline pass (and the managed dispatch) under a `BudgetTracker` via `withBudgetTracker`; once it is exhausted (an import swallows the refused embedding) the loop stops at the next page and `reportBudgetStop` exits 1 with `budget_exhausted` in `--json`. `countPending` is exported for `jobs submit reindex` and the mode-switch prompt. The writer pool is sized once from the run's page target (pending, capped by `--limit`) through `resolveWorkersWithClamp`, so Postgres runs over 100 pages default to `DEFAULT_PARALLEL_WORKERS` while PGLite stays at one; `--workers` overrides and the used count is reported as `workers` in the result and JSON (pinned by `test/e2e/reindex-auto-workers-5181.test.ts`). Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`. #5377: on a managed brain (`managedPersistenceEnabled`) the `--markdown` sweep delegates to the projection repairs through `runRepair` (`safe-chunks`, then `contextual-mode` unless `--no-embed`), so it never takes the legacy writer and changes no page revision, journal request or canonical file; `--type` is refused there with the repair commands, and pages the repairs cannot rebuild are reported as `unsupported_pages`. The doctor, upgrade and post-upgrade hints that name `gbrain reindex --markdown` therefore work on both brain modes (C-NEW-5).- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `pg_input_is_valid(..., 'jsonb')` (PG16+ floor, same as the IS JSON predicate `updateSourceConfig` relies on) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex b6a0a21feb..0fd5d9ecf4 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -51,5 +51,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/phase-containment.ts` — `timeContainedPhase` is the timer every `runCycle` phase runs under: a phase runner that throws returns a `fail` phase result carrying `{ class, code, message }` and `details.contained`, so later phases in the job still run while the report stays partial/failed (global freshness is not stamped; `gbrain dream` exits non-zero). Cancellation (an aborted cycle signal or `AbortError`), `LockStolenError` and `BudgetExhausted` are never contained. Successful `gateway.chat` calls inside the phase are counted through `withChatCallMeter` (`ai/chat-usage.ts`); a contained failure after at least one paid call is recorded under `dream:phase:<phase>:<source>` for `dream_paid_loop`. Tests: `test/cycle-phase-containment.test.ts`. Each phase also runs under `withAIAttribution({ phase: 'cycle:<phase>' })`, so model calls it makes carry the phase in invocation observers and `GBRAIN_AI_CALL_LOG`.- `src/core/cycle/fence-repair.ts` — the `fence_repair` maintenance phase: `runFenceRepairPhase(engine, { dryRun, signal?, deadlineAtMs?, registry?, now? })` runs the `fences` repair kind (`src/core/repair/fences.ts`) once through the trusted `repairRunner` (apply; a preview on a dry run) over every active source, with no rule logic of its own: the kind plans from its census, skips sources this host may not write (an owner reason such as `host_mismatch`, `owner_unavailable` as the fallback) and the candidates a running sync still names (`sync_in_progress`; the rest of a syncing source is repaired), reads `fences.repair.llm` and the daily USD ledger, and re-plans on the next run. `fences.repair.enabled` false skips it without calling the kind (the summary names `gbrain config set fences.repair.enabled true`). The run's deadline is min(`FENCE_REPAIR_PHASE_BUDGET_MS` = 300 s, a third of the maintenance job's remaining time), 300 s without a job deadline; past it `runRepair` stops before the next item with `time_budget` (status ok, resumed by the next run). Details read the kind's `FenceRepairVerification`: `candidates`, `repaired`, `repaired_by_tier`, `held_by_reason`, `llm_usd`, `llm_usd_per_repair`, `oldest_hold_at`/`oldest_hold_age_hours`, `llm_enabled`, `scan_partial`, `time_budget_ms`, `stopped_reason`; the summary says when Tier 3 is off and how many fences need a manual edit (`fix`: `gbrain repair fences`). Any other stop reports `warn` with the kind's fix; an internal error reports `warn` with its code only (no message, which could carry fence content) unless the cycle is aborted. Brain-global, after `sync` in `ALL_PHASES`, classified `writes`. Test: `test/cycle-fence-repair.test.ts`.+- `src/core/cycle/content-repair.ts` — the `content_repair` maintenance phase (#6377): `runContentRepairPhase(engine, { dryRun, signal?, deadlineAtMs?, kinds?, registry?, now? })` runs the content-repair lane (`src/core/repair/content-lane.ts`) minus `fences`, which `fence_repair` just ran (`contentRepairPhaseKinds()`; with `CONTENT_REPAIR_KINDS` holding only `fences` the phase runs nothing and reports `skipped` / `no_kinds`), through the shared trusted `repairRunner` over every active source: an apply, or a preview on a dry run. Gated on `fences.repair.enabled` (one switch for the whole lane; the summary names `gbrain config set fences.repair.enabled true` and `gbrain repair content`). Deadline min(`CONTENT_REPAIR_PHASE_BUDGET_MS` = 120 s, a third of the maintenance job's remaining time); past it the lane's kind stops `time_budget` (status ok, the next run resumes). Details: `kinds`, `candidates`, `repaired`, `held_by_reason` (each kind's `remaining`, else its per-item outcome reasons), `by_kind` (mode, counts by outcome, spend, oldest hold, stop), `llm_usd`, `oldest_hold_at` / `oldest_hold_age_hours`, `time_budget_ms`, `stopped_reason`; the summary counts holds that wait for a person (`merge_recommended`, `content_repair_needs_human`) and points at `gbrain sync status`. Any stop other than the time budget reports `warn` with the kind's fix; an internal error reports `warn` with its code only unless the cycle is aborted. Brain-global, right after `fence_repair` in `ALL_PHASES`, classified `writes`. Test: `test/cycle-content-repair.test.ts`.- `src/core/cycle/phase-table.ts` — `MANAGED_PHASE_TABLE` classifies every `ALL_PHASES` entry for managed brains as `writes` (publishes through the coordinator), `no_coordinated_write` (derived projections, side tables, audit-only) or `managed_skip`, each with its reason; `isManagedBrain` is what `runPhaseLint` uses to report issues without rewriting managed canonical files. The managed phase matrix test fails for an unclassified phase.diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex ffd5299446..edd66b3df7 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -10,11 +10,13 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/fence-repair/{types,schema,raw-rows,reasons}.ts` — #6188 the shared fence vocabulary, all location-only. `types.ts`: `FenceIssue`, `FenceFix`, `FenceCtx`, `FenceReason`, `FixClass`. `schema.ts`: canonical columns, accepted widths (facts 9/10/14, takes 6/7/13), header aliases, enum and kind synonym tables (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/merge.ts` — #6377 (Lane A1) the Tier 1 `merge_fences` fix class that clears `repeated_marker`: when one section holds several balanced fences of one kind whose headers map to the canonical columns, the later fences' rows are appended to the primary fence in document order, a row whose cells (every column but the number) equal a kept row's after trimming is dropped as an exact duplicate (near-duplicates both stay; the contradiction machinery owns them), a colliding row number is renumbered above the page's highest (stored rows consulted as `renumber` does; `superseded by #N` references follow), the later markers, tables and a duplicated section heading above them are removed and blank lines collapse. Anything else (an unbalanced repeat, a header that does not map, non-table text in the repeated region) stays `repeated_marker` manual. `validate.ts` gains the merge mapping the gates run through: before rows are the concatenation of every fence's rows by occurrence, each mapped to an after row or marked `duplicate_of`; gate (e) accepts exactly the marked duplicates and only when the kept row's cells are byte-equal after trimming. The receipt carries `merged: { fences, rows: [{ occurrence, from_fence, kept_as | duplicate_of }] }`, never cell text. Tests: `test/fence-repair-structure.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 (the OWNER list routes `owner_unavailable`, `owner_cli_required` and the #6278 owner conditions `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing` to state `owner`). `readFenceAutoRepair` (two reads: `fences.repair.enabled`, `fences.repair.llm` and `autopilot.last_global_at` from `config`, plus the last completed `autopilot-global-maintenance` job) says whether the maintenance run repairs fences by itself (active within `FENCE_MAINTENANCE_ACTIVE_MS`, 24 h). `fenceHoldStatus` derives the state from the reason table and `meta.fence_repair`: `auto` (no action needed, the read-only preview), `apply` (preview, then apply), `manual` (manual-only reason, gate rejection or a model failure the run does not retry: the preview names the edit, then the sync), `paid` (`budget_exhausted`, `llm_disabled`, `no_pricing`: the exact config or `pricing set` command with consent `paid`), `owner` (the owner-host command, actor `host_admin`). `fenceHoldFix` is the local fix (`gbrain repair fences --source <id> --only <path>`), `fenceHoldRelay` the remote one (`tell_user_to_run`, no path), `fenceHoldLocation` the D16 object, `fenceFileLine` the file line of a section line. Location only. Tests: `test/fence-hold-surfaces.test.ts`, `test/sync-hold-surfaces.test.ts`.- `src/core/fence-repair/{census,census-store}.ts` — #6188 the fence census: discovery only, nothing repairs. `runFenceCensus(engine, { sourceIds, deadline, now })` advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill over `pages.id`, then incremental passes over `updated_at >= watermark`, where each new watermark is the previous pass's start minus the oldest open writer transaction in `pg_stat_activity` and `LATE_COMMIT_GRACE_MS`, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk of `isFrontmatterScannablePath` files via `collectGitVisibleFiles`/`walkDir`, then only `git diff <walked commit>` files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the census `partial`. `judgeFences` runs the coordinated `fenceStep` (normalization on): `deterministic` when Tier 1 fixes it, else the highest `FENCE_REASONS` tier of its residual reasons (`reasonTier`; manual-only or page-dependent counts as manual). `listFenceCandidates` dedupes by page slug across `invalid_fence` holds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/`updated_at`/`content_hash`, file sha256/mtime, hold `upstream_version`); `summarizeFenceCensus` counts per source by bucket and tier with the oldest hold and scan state. `census-store.ts`: `op_checkpoints` rows `fence-candidate` (one per source incarnation and slug, `page`/`file` parts), `fence-scan` (cursors and last census) and `fence-trend` (one row per sync run, keyed by run id: a managed run's total is rewritten in the same transaction as each cursor step that changes it, so the trend never differs from the cursor, and a legacy run writes its total when it ends; plus one row per normalized page write via `recordPublicationFenceTrend`, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests: `test/fence-census.test.ts` (+ `test/e2e/fence-census-postgres.test.ts`), `test/doctor-fence-integrity.test.ts`.- `src/core/fence-repair/{llm,repair-tiers}.ts` — #6188 Tier 2 and Tier 3 for one candidate. `analyzeFences`: Tier 1 (`safeNormalizeFences`, stored rows loaded only for `renumber`), Tier 2 (`resolveStrictEntityReference` without the same-name arm per `holder_unresolved` cell, only `people/`/`companies/` slugs, private pages excluded on a world page; hits feed `verifiedHolders`), then `proposal` (validated by gates (a)-(g) and a fixed point), `llm` (only `TIER3_REASONS` residuals left; a fence with stray text lines or no end marker is not eligible) or `manual`. `llm.ts`: `tier3Requests` (per fence: the header line and the residual rows, every row for a fence-level issue), `buildTier3Prompt` (schema, vocabulary, reason codes, page visibility, and rule 8: answer `HOLD` when a row has more than one reasonable reading; pinned by a prompt-bytes digest and `FENCE_REPAIR_PROMPT_VERSION`, 2), the layout (wide when the header names a wide column or, headerless, a row as written is wider than the narrow layout), `tier3TokenBudget` (the table's size plus `TIER3_REASONING_TOKENS` for a model whose reasoning the call cannot switch off, raised to the gateway's thinking headroom where the route has no switch: the estimate reserves what the gateway sends), `callTier3` (gateway `chat`, no tools, no fallback, thinking off; `llm_unavailable` when the provider throws, `llm_refused`, `llm_truncated` for any stop but a normal end, `llm_declined` for HOLD, `llm_malformed`/`llm_empty` from `extractSingleTable`, a wrong row count is a gate (e) failure), `spliceTier3` (rebuilds only that fence: canonical header, then every row in order with the sent rows replaced). `runTier3` claims the attempt (a rejected memo returns its verdict), checks the per-page cap and the run allowance, reserves on the daily ledger before each call (a refusal stops the run), settles actual tokens (an answerless call at its estimate), normalizes and validates the spliced page against the bytes as read, and re-asks once with the failed gate letter and rows only after a structural failure (gate (a) or (e)); any other gate or a HOLD is final and consumes the memo. `TIER3_REASONS` is the reason table's screen reasons of tier `llm`. Tests: `test/fence-repair-llm.test.ts`, `test/repair-fences.test.ts`.+- `src/core/fence-repair/llm-tail.ts` — #6377 (Lane A3) the Tier 3 request kind `tail`: when a fence has no end marker and lines follow its last row on a world-visible page, the model sees only the fence's begin line, header, every row and the trailing lines to the section end (never the rest of the page) and answers one JSON object `{"tail": "prose" | "rows" | "unsure"}` through the same gateway call, caps, daily ledger and attempt memo as the row requests (memo key: the fence region's sha256 + model + prompt version, so an unchanged tail never costs twice and a transient `llm_unavailable` does not consume it). `prose` makes the close previewable under the `tail_exposure_approval` reason (the preview prints the exact exposed lines and the hash binds them; unattended runs record `needs_human` with the paragraph and the `gbrain repair content --only <path> --apply --expect <hash>` command); `rows` and `unsure` render `unclosed_ambiguous_tail` (manual, the exact edit). On a private page the model is never called: `structure.ts` closes the fence after the last row deterministically (`trailing_lines` on the receipt), because the privacy boundary hides nothing from anyone there. Tests: `test/fence-repair-llm.test.ts`.- `src/core/fence-repair/stray-cells.ts` — #6188 Tier 1 `stray_empty_cell` (`strayCellPass`, run by `normalizeFences` after the structural pass): in a balanced primary fence with a canonical header, a row with more cells than the layout loses empty cells (slot removed, every other byte kept) only when exactly one distinct deletion leaves every validated column valid; otherwise it stays `extra_cells`, now manual. In a fence with no header, `headerlessMisfit` reads a row that starts with a row number by position: a `kind` cell that is not a kind word is `claim_split`, a row wider than any layout with an invalid validated column is `extra_cells` (after the same empty-cell removal), and `content.ts` holds both as manual, so a claim an unescaped `|` cut never reaches Tier 3. `rules.ts` `kindWord` keeps facts `kind_map` to a kind word (at most three words, no sentence punctuation, link or strikethrough); other text is `claim_split` (manual), never a kind note. Tests: `test/fence-repair-normalize.test.ts`.- `src/core/fence-repair/{measured,model}.ts` — #6188 the Tier 3 eval's verdicts and the model they pick. `measured.ts`: `FENCE_REPAIR_MEASURED_MODELS` (the models that met the preregistered rule, best first) and `FENCE_REPAIR_MEASURED` (the behavior notice's accuracy sentence), updated together by the next eval. `model.ts`: `resolveFenceRepairModel(WithSource)`: an explicit `models.fence_repair` always (any model, priced or not); unset, the first measured model whose provider key the merged env has; else null (`no_measured_model`, a paid hold whose fix is `gbrain config set models.fence_repair <model>`). `gbrain models` reports the row through it (`measured default`). Tests: `test/repair-fences.test.ts`.- `src/core/fence-repair/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource(engine, sourceId, { remote })`: managed owner root, or the `OwnerRefusal` row (`persistence/owner-refusal.ts`) that says why this host may not write it (a remote caller's row names no local path), legacy checkout, mirror flag, and the `RepairBusySet` (`persistence/repair-busy.ts`: in-flight writes plus the not-yet-admitted entries of every unfinished sync cursor, failing closed); an unfinished sync no longer marks the whole source busy. `writeFenceRepair` turns a `sync_in_progress` raised at the write's admission into `{ ok: false, reason: 'sync_in_progress' }`. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `git add`/`git commit` step, dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.diff --git a/docs/architecture/key-files/core-services-1-continued.md b/docs/architecture/key-files/core-services-1-continued.mdindex cecdf7fc31..30e1ffb89d 100644--- a/docs/architecture/key-files/core-services-1-continued.md+++ b/docs/architecture/key-files/core-services-1-continued.md@@ -2,7 +2,10 @@[Subsystem index](../KEY_FILES.md) · [Previous entries](core-services-1.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-The Retrieval Reflex and session-context helpers under `src/core/context/`.+The content-repair judgment tier under `src/core/content-repair/`, then the Retrieval Reflex and session-context helpers under `src/core/context/`.++- `src/core/content-repair/judgment.ts` — #6377 (Lane B3) the content-repair lane's model tier for a slug conflict: `judgeSlugConflict` builds the prompt from both files' frontmatter, headings and first 60 lines of body plus every line that mentions the other's slug anywhere in either body (evidence past line 60 counts), both slugs and paths, the hold's reason and the allowed answers, and parses exactly one JSON object `{"action":"remove_slug"}`, `{"action":"merge_into","canonical":"<one of the two slugs>"}` or `{"action":"needs_human"}` with an optional `why` sentence that reaches the run's output only, never hold metadata. The same failure classes, `thinkingOffControl` and output ceiling as the fence tier; a `canonical` outside the two slugs is `llm_malformed`. Memo key: sha256 of both participants' content + both ids + model + prompt version + rules version. The model is `models.content_repair` (an explicit model always runs), else `models.fence_repair`, else `CONTENT_REPAIR_MEASURED_MODELS` (the eval's qualifiers, best first, ties to the cheaper), else the fence list. Tests: `test/repair-slug-conflicts.test.ts`.+- `src/core/content-repair/llm.ts` — #6377 (Lane B3) the paid call behind `judgment.ts`: one gateway chat under the fence repair's caps and ledger (`FENCE_REPAIR_LEDGER`, so one `fences.repair.max_usd_per_day` covers the whole lane and today's fence spend counts; the per-page cap applies per candidate), `fences.repair.llm=false` and `--no-llm` turn it off, the attempt memo keeps rejected bytes from costing twice, and a transient `llm_unavailable` does not consume the memo. Spend is reported as the item's `llm_usd` and carried into the `content_repair` receipt (`model`, `cost`); prompts never include the rest of either page.- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; `visibility: private` (and derived-private) pages never resolve on any arm unless the caller passes `excludePrivate: false` (default true, the remote-search predicate `privatePagesFilterFragment`; only `volunteer_context` widens, via `resolveExcludePrivatePages` for a trusted local caller — gbrain-evals N8-1/N8-2, pinned by `test/reflex-private-visibility.test.ts`); capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract), a writeback turn whose facts preflight finds the canonical writer busy (`writer_lock_unavailable`, before any model call) re-queued after 5, 15 and 45 s (`writer_busy_requeued`; the retry skips admission, a pending retry dedups a re-schedule as `already_queued`, shutdown clears pending retries) while a compact segment's busy refusal stays an error the sweep resumes, and error reasons that keep the error's code or `reason` within the 48-char reason-code shape (`operationerror:writer_lock_unavailable`), the first failure of each reason logged to stderr once per serve run — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and pass `excludePrivate: true` on every arm, so private pages never reach the compiled file; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT. #6195: `entity-salience.extractCandidates` also emits lowercase 2-3-word weak n-grams (`multiToken`, own budget `MAX_WEAK_NGRAM_CANDIDATES` = 16, never across punctuation, never all stopwords/common words) that ride the exact weak-alias fold, and `retrieval-reflex` arm 2.6 (`weak-title`, 0.72, behind `lexicalArms`, private pages hidden by default) matches them to the exact title of a person/company/organization page whose title is globally unique; single lowercase words stay alias-only.- `src/core/context/hook-heartbeat.ts` — the hooks telemetry plane under `<gbrain home>/integrations/hooks/` (`heartbeat.jsonl`, `status.json`, session receipts, the memorable relay log; directories 0700, appends 0600). Entries hold counters, durations and codes only: `HEARTBEAT_ALLOWED_KEYS` is the full key allowlist CI greps the fixture against, and includes `pattern` (scanner pattern name), `fingerprint` (`sha256:<16 hex>`) and `hint` (fixed text) for refusals. `near_duplicate` is the shadow count on the `writeback_dedup` event that `facts/capture-dedup.ts` appends (lane in `reason`, exact drops in `duplicate`). `relayRefusalHeartbeat(hit)` builds the line `context-engine.ts` writes when its high-entropy re-scan refuses a memorable relay (`event: relay`, `outcome: degraded`, `reason: secret_scan_refused`); the receipt and relay are skipped for that compaction window and the checkpoint is kept. `memorableGateAllowed` gates the relay lane; span redaction runs `redactFindings` with `highEntropy: true`. Tests: `test/context-engine-checkpoint.serial.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 3af90a075b..35297fd5bb 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -14,6 +14,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/timeline-comments.ts` — `gbrain repair timeline-comments` (#6184), explicit-only. The plan lists pages with timeline rows whose source, summary or detail carries `<!--`/`-->` or whose body has a materialized bullet carrying markup (`dropCommentBullets`), with residuals `comment_only_rows`, `comment_bearing_rows`, `pages_with_comment_bullets`. Apply: one revision-bound `put_page` per page dropping those generated bullets (user-written bullets are left), then one transaction under the page lock (`withCoordinatedWrite` with maintenance attribution on managed brains) that deletes comment-only rows and rewrites the rest to their stripped tuple, or deletes them when the page already has it. Idempotent. `timeline.ts` warns `timeline_comment_markup` naming this kind while such rows exist.- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (`host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`; `owner_unavailable` is the fallback; the skip's detail carries `why`, the read-only fix and `retryable`), a candidate a write in flight or an unfinished sync's frozen manifest still names is `sync_in_progress` (#6278: checked at plan, at apply and again at the write's admission in `file-repair.ts`; the rest of the source repairs while the sync runs, and a held path is not busy); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.+- `src/core/repair/content-lane.ts` — the content-repair lane (#6377). `CONTENT_REPAIR_KINDS` is the ordered list of repair kinds that clear managed-sync content holds (today `fences`; the GBRA-72 integration appends `slug-conflicts`), read by `gbrain repair content` (`src/commands/repair-content.ts`), the `content_repair` cycle phase and `gbrain sync unblock --apply`, so a new kind plugs in with one entry. `CONTENT_REPAIR_HOLD_KINDS` maps a hold code to the kind that clears it (`invalid_fence` → `fences`; `frontmatter_slug_conflict` → `null` until Lane B's kind lands, which keeps the surfaces' refusal text). `runContentLane(engine, scope, { apply, kinds?, only, skip, expect?, noLlm, maxLlmUsd, deadline, registry? })` has no rule logic: it runs each kind through `repairRunner` in order, passing the run's paid allowance minus what earlier kinds spent (read from each result's `cost.llm_usd`; the daily ledger is `FENCE_REPAIR_LEDGER` for every kind) and one absolute deadline (a `time_budget` stop ends the pass; any other stop lets the next kind run), and returns per-kind results, each kind's own `preview_hash` (no combined hash: `--expect` is one hash per kind in lane order, `parseContentLaneExpect` refuses a wrong count with `invalid_params` before any kind runs), the lane's spend and remaining allowance, and `apply_command` (`contentLaneArgv`). A preview plans every kind before any mutation; `--apply --expect` binds each kind to its approved set; a bare apply runs each kind's own plan-and-apply (`changed_since_read` binding, held reasons recorded on the holds). `contentHoldDisposition(record, auto)` reads a hold's stored repair state (`fenceHoldStatus` for a fence hold; `meta.content_repair.action` for a slug-conflict hold, read loosely) and says whether an unattended surface may run the kind (`repair`), must list it (`listed`: `needs_human` for a manual reason or a recommended merge, `paid`, `owner`) or has no kind for it (`unsupported`). Output is counts, codes, hashes and paths only. Tests: `test/cycle-content-repair.test.ts` (stub kinds), `test/repair-content.test.ts` (the real `fences` kind through the CLI).+- `src/core/repair/slug-conflicts.ts` — `gbrain repair slug-conflicts` (#6377, Lane B), the lane kind that clears `frontmatter_slug_conflict` holds: preview-bound, `spends: 'llm'`, `checks: []` (doctor keeps `git_held_files` on `frontmatter`), not explicit-only. Candidates are the source's slug-conflict holds (plus `--only <path>`); identity is resolved, not textual: the frontmatter slug is normalized the way the screen does and resolved through `slug_aliases` to a page id in the same source (a slug resolving to the held file's own page is exempt; a held file with no page yet is a normal candidate). Deterministic tier (`remove_slug`, confidence high): the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token; the one-line edit publishes through the frontmatter repair's coordinated path (`prepareRepairPublication` / `submitManagedFileRepair`: bytes bound to the sha256 the preview read, import, hold clear and Git effect in one write). Everything else goes to the model tier (`src/core/content-repair/judgment.ts`): `remove_slug` applies the same way, `merge_into <canonical>` and `needs_human` are recorded on the hold as codes and slugs only (`recordContentHoldRepair`, `meta.content_repair`) and rendered by `sync status` as `needs_human` paragraphs; nothing merges pages. Caps and ledger are the fence repair's (`FENCE_REPAIR_LEDGER`, `fences.repair.max_usd_per_page` / `_per_day`, `fences.repair.llm`, `--no-llm`, `--max-usd`); the receipt is a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256) carried by the write and the commit trailer `gbrain-repair: <hold_code> <tier> <confidence>`. Tests: `test/repair-slug-conflicts.test.ts`.- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`.- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex b53e01e329..f0716eba3b 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -19,7 +19,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. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) cancels a head whose predecessor ended without committing, and under lanes a member whose predecessor is unfinished releases its claim and waits; `cancelOrphanedLaneRows` uses the same rule, so a member released mid-group (its group fell back to the single path and an earlier member went back to the queue) never publishes after that member fails. Test: `test/sync-group-member-order.test.ts`.- **`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. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. 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. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out.-- **`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`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `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`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB per slice, blobs over the read bound excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `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; `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; 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/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 and slug-conflict holds (`HoldRepairRoute.fences` + `slug_conflicts`) preview the content-repair lane, `gbrain repair content --source <id>` (`contentRepairArgv`, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself when `FenceAutoRepair.active`), other holds preview `gbrain repair frontmatter`, a mixed source names both; one fence hold's own fix stays that file's `gbrain repair fences --only <path>` preview (`fenceHoldFix`). 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`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `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`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB per slice, blobs over the read bound excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `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; `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; 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). `managedRepairRoot` resolves the owner through `checkOwner` (`owner-refusal.ts`) and refuses `owner_unavailable` with the condition as its reason; `submitManagedFileRepair` re-reads the source's `RepairBusySet` (`repair-busy.ts`) right before admission and refuses `sync_in_progress` when a write in flight or an unfinished sync's frozen manifest names the path, origin, slug or a rename endpoint (#6278: a sync can start while a fence repair waits on its model call). 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`. `syncGitTopLevel` answers the checkout's `git rev-parse --show-toplevel` once per root and sync run, reading it again when the top level's `.git` entry is replaced or removed or a `.git` appears between it and the root. #6278: `prepareManagedSyncMutation` calls `enterClaimStep` at each await boundary (`managed_sync_active`, `authority`, `worktree_binding`, `configured_root`, `knowledge_publication`, `manifest_entry`, `git_rev_parse`, `origin_check`, `page_snapshot`, `import_screen`, `import_content`, `canonical_projections` and the rest, each naming `git`, `fs` or `db` where it knows), so a stall reports its step; the consumer's budget and the cancellation reaching those boundaries are in persistence-stalls.md.- **`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/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex fe0bbecc0f..edb4e94865 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -38,7 +38,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.- `src/core/persistence/sync-page-fault.ts` — #6340: a page that moved under a managed catch-up holds the page, not the run. `headCommittedBytes` returns the working-tree bytes of a path when their blob id equals `HEAD:<path>` (sha1 or sha256 by HEAD's id length), so `freezeEntry` imports bytes committed past the pinned target as HEAD has them (the later pin..HEAD diff re-imports them as a no-op; idea and first test from PR #6323, which this supersedes) and `prepareManagedSyncMutation`'s `newerWorkingTree` screen never sees them. `pageChangeProof` is #6194's revision-linked proof usable at freeze time; `pageChangedHold` builds the `concurrent_write` hold for a database page that was edited, deleted or re-bound after enumeration (with the competing request when proven, else `page_revision` + `expected_revision`), `worktreeDirtyHold` the new `worktree_dirty` hold (pinned `blob_oid`, `working_hash`) for uncommitted bytes that match neither the pin nor the page, `pinnedWorktreeConflict` recognizes that receipt and `pageMovedSinceAdmission` a `revision_conflict` receipt whose page really moved (a run-level conflict with the page where it was still blocks). In `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws (`page_identity_changed`, `revision_conflict`, the renamed-source conflict) into holds when holds are on (a page that still holds exactly what the import carries is re-bound to its new revision and passed by the waiver screen; `sync.holds=fail` and company-brain cursors keep the refusals), `holdFailedFenceRequest` converts the two receipts (imports and deletes) through `receiptPageFaultHold`, re-freezes an entry once under a fresh request when its file changed between admission and publication (`fileChangedAfterAdmission`, the `raw_file_changed` receipt: committed bytes then import as HEAD has them, a second change under the re-frozen request is held `worktree_dirty`; `holdUnderGate` takes `refrozen` in place of `hold` and records the conversion as `refrozen`), `convertBlockedCursor` converts a cursor an older release left blocked (re-freezing a dirty file that is committed now), `originFaultHold` holds an entry whose recorded origin no longer identifies the enumerated page (`assertSyncPageOrigin` at freeze), every page-fault hold marks the cursor `overtaken` (#5522: another cursor may have checkpointed this target), and the `--retry-failed` start tries that conversion before rediscovering, so the frozen manifest survives. `writeGitHold` counts `meta.attempts` per re-hold with the same code; `HOLD_ATTEMPTS_NEEDS_HUMAN` (3) turns a page hold into `needs_human`. The run's catch skips the failure ledger for `isRetryableConnError` / statement timeouts. Tests: `test/managed-sync-page-fault-holds.test.ts` (freeze-time DB edit → hold, same content → re-bind, dirty → `worktree_dirty` → commit → import, committed past pin → HEAD bytes, old blocked cursor → in-place conversion with attempts, connection death → no ledger row, same run on relaunch, one extra pass), the updated expectations in `test/persistence-managed-sync.test.ts` and `test/managed-sync-concurrent-write-hold.test.ts`.- `src/core/persistence/sync-write-diagnostic.ts` — `managedSyncWriteDiagnostic`, the `managedWrite` block of a managed sync result (terminal receipt reason, suggestion with the retry command, the CRLF-only note), moved unchanged out of `sync-run.ts` by #6340.-- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). `unblockSync` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold, refuses `still_dirty`, `concurrent_write`, exhausted and repair-class holds by name with their fix, previews without `--apply`, and is idempotent. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them) print the envelope with `next` rendered through `renderAction`. Tests: `test/sync-status-unblock.test.ts`.+- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file. Tests: `test/sync-status-unblock.test.ts`.- `src/core/persistence/sync-drain.ts` (#6340 additions) — `isConnectionDrop` (a retryable connection error that is not #6329's `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` settle discard; `retry-matcher.ts` now matches `ECONNABORTED`, `ETIMEDOUT` and `EPIPE` beside `ECONNRESET`); `runDrain` reconnects (`DrainInput.reconnect`, `engine.reconnect` from `drainManagedSync`) and retries a dropped pass on `CONNECTION_RETRY_MS` (5/15/45 s), resets the count on every committed page, and after `CONNECTION_STRIKES` drops with no commit between them ends `blocked` / `connection_lost` with `drain.connection { drops, last_error }` (URLs stripped) and the resume command as a loopable `next` (`sync_drain_connection_lost` in the catalogue, `connection_lost` in the registry). `drainManagedSync` takes exactly one extra pass (`drain.extra_pass { from, to }`, counts merged by `mergeExtraPass`) when HEAD moved past the pinned target during a `synced` run, so a live checkout ends at HEAD without looping. Tests: `test/sync-drain-connection.test.ts`.- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). Tests: `test/persistence-manifest-git-scope.test.ts`, `test/hardened-git-filters.test.ts`.- `src/core/git-checkout.ts` — #6210 (fix wave 12): `classifyGitCheckout(dir, env = process.env): 'git' | 'not_git' | 'unknown'` decides from the filesystem alone whether a directory is inside a Git checkout: `not_git` only when the directory exists and no `.git` entry (directory or gitdir file) is at or above it and `GIT_DIR` is unset; `unknown` for a missing directory or any lookup error other than absence. Git's own exit 128 is locale-dependent and also means a damaged HEAD, a bad gitdir or dubious ownership, so callers that soften "not a checkout" use this instead. `isDurabilityHardenedAsync` (`brain-repo-durability.ts`) returns false only for `not_git` or an absent hook; every other failure (a git probe run with `LC_ALL=C` failing, a timeout, an unreadable hook) rejects `git_unavailable`, and `runPersistenceEffects` (`persistence/effects.ts`) settles each cached per-root probe to `{durable}|{error}` and records the error on every coalesced effect, so the effects stay queued (and park after repeated failures) instead of completing as `durability_not_enabled`. Tests: `test/git-checkout.test.ts`, the `#6210` block of `test/persistence-git-coalescing-5530.slow.test.ts` (Postgres via its e2e twin).diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 4081f81232..20ac0d659b 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2536,6 +2536,16 @@ Reasons: `content_directory`.|---|---|---|---|---|---|---|| Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug. | The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull --retry-failed. | host_admin | `gbrain doctor --json` | 1 | no |+### tail_exposure_approval++<a id="tail_exposure_approval"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A fence on a world-visible page has no end marker and prose follows its table; closing it after the last row is safe for the table but makes those lines visible to remote readers, so the content-repair lane previews the close and waits for a hash-bound approval instead of applying it unattended. | Everything after an unpaired begin marker is hidden by the privacy boundary. The repair model read the tail as prose (not rows), so the only judgment left is whether those exact lines may become visible, and that is the user's: the preview prints them and the hash binds them. On a private page nothing new is disclosed and the lane closes the fence by itself. | Show the user the preview's exposed lines (gbrain repair content --source <id> --only <path>, read-only), then run the printed gbrain repair content --source <id> --only <path> --apply --expect <hash> only after they agree; a changed tail invalidates the hash. By hand: add the end marker directly after the last table row and move the trailing text where it belongs, commit, then gbrain sync --source <id> --no-pull. | user | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#tail_exposure_approval](../../docs/guides/write-refusals.md#tail_exposure_approval)+### take_row_collision<a id="take_row_collision"></a>@@ -2632,6 +2642,16 @@ More: [docs/guides/troubleshooting.md#two-consumers-on-host](../../docs/guides/t|---|---|---|---|---|---|---|| A required dependency or capability cannot serve this request. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |+### unclosed_ambiguous_tail++<a id="unclosed_ambiguous_tail"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A fence has no end marker and text follows its table, and the repair model read that tail as table rows written without pipes or could not tell, so gbrain will not choose where the fence ends; nothing was written. | Closing after the wrong row would hide rows behind the privacy boundary or expose text; a deterministic rule cannot place the end marker and the model declined to, so a person decides. The attempt memo keeps the same bytes from costing a second model call. | Read the page (gbrain get --source <id> -- <slug>), add the end marker after the last real row of the named fence (moving any rows the tail holds into the table), commit, then gbrain sync --source <id> --no-pull. The preview (gbrain repair fences --source <id> --only <path>, read-only) names the fence, section and last row. Run: gbrain repair fences --source '{source_id}' | user | `gbrain sources status '{source_id}' --json` | 1 | no |++More: [docs/guides/write-refusals.md#unclosed_ambiguous_tail](../../docs/guides/write-refusals.md#unclosed_ambiguous_tail)+### unexpected_file_bytes<a id="unexpected_file_bytes"></a>diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex f6a346a1cb..9f2a76cf27 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -929,6 +929,77 @@ writing it, and install the staged-content pre-commit hook with`gbrain frontmatter install-hook` (the user's decision: it writes into theirrepository). See the `frontmatter-guard` skill.+<a id="content-lane"></a>+#### The content-repair lane (#6377)++The walkthrough above is the interpretive path: frontmatter fixes change what+a file says, so each one is approved by hash. Holds about a file's *content*+(`invalid_fence`, and `frontmatter_slug_conflict` once its lane kind ships)+take a different path and clear with no one acting. The content-repair lane+(`src/core/repair/content-lane.ts`) is the ordered list of repair kinds that+clear them, today `fences`, run under one paid-model allowance and one+deadline: what the first kind spends on the model is gone for the next, and+every kind keeps its own census, owner checks, caps, daily ledger+(`fences.repair.max_usd_per_page`, `fences.repair.max_usd_per_day`, shared by+the whole lane), attempt memo and validation gates. It runs from three places:++- The maintenance run: `fence_repair` runs the `fences` kind right after+ `sync`, and `content_repair` runs every other lane kind right after it, both+ gated on `fences.repair.enabled`, so a hold the sync just wrote is repaired+ before the extract phases read the page.+- `gbrain sync unblock --source <source> --apply` runs the lane on exactly the+ held paths now, one bounded apply, then schedules the re-screen and prints+ the sync. Each path reports `repaired`, `held`, `needs_human` or `skipped`+ with its reason code, receipt and next step; `--no-llm` keeps to the free+ tiers and `--no-repair` restores the refuse-only behaviour+ ([runbook](sync-unblock-runbook.md)).+- By hand:++```bash+gbrain repair content --source <source> # preview: every lane kind, read-only, no model call; one hash per kind+gbrain repair content --source <source> --apply --expect <hash>[,<hash>] # the apply command the preview prints: exactly those sets+gbrain repair content --source <source> --only <path> --apply # one file, each kind's current plan+```++The preview plans every kind before anything is written and prints each+kind's own hash and the apply command; there is no combined hash, and a wrong+hash count refuses (`invalid_params`) before any kind runs. `--max-usd <n>` is+the lane's allowance for the run; `--no-llm` keeps every kind to its free+tiers. `--apply` alone applies each kind's current plan as `gbrain repair+<kind> --apply` does, each file bound to the bytes the plan read+(`changed_since_read`).++**What a repair proves.** Every repair is one coordinated write. On a managed+source the file is rewritten, imported, its hold cleared and the commit queued+through the Git effect, whose subject is `gbrain: repair fence in <path>+(<classes>)` and whose trailer `gbrain-repair: <hold_code> <tier> <confidence>`+names what was repaired, which tier decided it and how sure the rule was. The+receipt the write carries (location-only: mode, tier, classes, rows, columns,+`before_sha256`, `after_sha256`, `committed: effect | commit_step |+not_in_git`, and for a merge the merged fence occurrences, never a cell) is+parsed before it reaches a commit message, so nothing forged lands there.+`git revert` of that one commit restores the bytes; the hold then re-screens.+A legacy source is backed up under `~/.gbrain/backups/` and prints the commit+step with the same `-m` pair.++**What the model decides, and what it never does.** The deterministic tiers+run first and the model sees only the cases they mark ambiguous: the trailing+lines after an unclosed fence on a world-visible page (prose, rows or unsure)+and a slug conflict whose two pages might be the same thing (`remove_slug`,+`merge_into <canonical>` or `needs_human`). The model chooses among coded+answers; every byte written comes from a rule and passes the gates. Merges are+**recommended, not executed**: a `merge_into` answer becomes a `needs_human`+hold naming the canonical page ([`merge_recommended`](write-refusals.md#merge_recommended)),+and a world-page close that would expose text waits for the hash-bound+approval ([`tail_exposure_approval`](write-refusals.md#tail_exposure_approval)).+`gbrain sync status --source <source> --json` lists each such hold with its+paragraph in `human_reason`; `fences.repair.llm false` turns the model tier+off for the whole lane.++**Say to your agent:** *"Sync is holding a few files over their tables or+slugs. Repair what gbrain can by itself and tell me what it wants me to+decide."*+<a id="frontmatter"></a>### Frontmatter@@ -1061,7 +1132,7 @@ exists). An older gbrain blocked the source on the first fence it refused.+1 added, ~0 modified, -0 soft-deleted (recoverable 72h), R0 renamedHeld companies/acme-example.md: invalid_fence (no_header) in the facts fence (body), at line 6; its page is missing until the file imports. Next: gbrain repair fences --source notes --only companies/acme-example.md, then gbrain repair fences --source notes --only companies/acme-example.md --apply (docs/guides/write-refusals.md#fence-no_header)Held projects/widget-launch.md: invalid_fence (holder_unresolved) in the takes fence (body), row 1, column who, at line 9; its page is missing until the file imports. Next: gbrain repair fences --source notes --only projects/widget-launch.md, then gbrain repair fences --source notes --only projects/widget-launch.md --apply (docs/guides/write-refusals.md#fence-holder_unresolved)- 2 file(s) held this run, 2 held in source notes; they do not block sync. Inspect them with 'gbrain sources status notes'; then nothing repairs the fence holds by itself (no maintenance run is active), so preview the fence repairs with gbrain repair fences --source notes (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>), then run the apply command it prints. Preview the repair: gbrain repair fences --source notes+ 2 file(s) held this run, 2 held in source notes; they do not block sync. Inspect them with 'gbrain sources status notes'; then nothing repairs the fence and slug-conflict holds by itself (no maintenance run is active), so preview the content repairs with gbrain repair content --source notes (read-only, no model call: it lists each held file with its planned repair or the exact edit, kind by kind, and prints the apply command with --expect <hash>[,<hash>]), then run the apply command it prints. Preview the repair: gbrain repair content --source notesConverted 1 failed request(s) of the blocked cursor in place: <id>.Normalized fences in 1 file(s) (kind_map x1, close_fence x1). 1 file(s) under meetings/ had a malformed facts or takes fence that sync rewrote losslessly and committed (claims and existing row numbers unchanged); whatever writes them emits fences gbrain has to repair. Write facts with `remember` and takes with `takes_add` (or emit the canonical columns) so rows never need normalizing. Re-read a normalized page before editing it.```diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 08b8c78c7b..8b639ef64f 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -19,13 +19,25 @@ gbrain sync unblock --source <id> --apply --json # when committed_last_10m is 0gbrain sync <next.argv...> # the sync unblock (or status) names: the cursor's own options```+**Say to your agent:** *"Repair the files sync held and get the catch-up+moving again; ask me only about the ones gbrain will not decide by itself."*+1. Read `status`. `cursor` is where the run stands (`index/total`, the`pinned_target` commit, `last_advance_at`); `committed_last_10m` is thesignal that data is moving (a live process with a flat cursor is notprogress). `holds` and `last_error` each carry the triple below.2. If `needs_human` is false and nothing committed in the last ten minutes,run `unblock --apply`: it performs the safe action for every hold that has- one, refuses the rest by name, and prints the sync to run.+ one, refuses the rest by name, and prints the sync to run. For a content+ hold (`invalid_fence`; `frontmatter_slug_conflict` once its lane kind+ ships) the safe action is `repair`: unblock runs the content-repair lane+ (`gbrain repair content`, the same kinds the maintenance run uses) on+ exactly those paths as one bounded apply under the `fences.repair` caps,+ each file bound to the bytes the plan read, and reports every path as+ `repaired`, `held`, `needs_human` or `skipped` with the reason code, the+ location-only receipt (mode, tier, classes, commit state) and the next+ step. `--no-llm` keeps the repairs to their free tiers; `--no-repair`+ refuses every repair-class hold instead, as releases before #6377 did.3. Run that sync. It re-screens the scheduled files, imports each one that nowpasses and holds again what still fails; the rest of the source is neverblocked. With `--retry-failed` a cursor an older release left blocked on a@@ -33,9 +45,13 @@ gbrain sync <next.argv...> # the sync unblock (or status)4. If `needs_human` is true, stop looping and page a person with the slug and`human_reason` from `status` (`next.user_message` is written for relay).-`unblock` is idempotent, writes no page, clears no hold and drops nothing:-refusing is the only way it leaves a file out, and each refusal names the file,-why, and its fix.+`unblock` is idempotent and drops nothing: the only pages it writes are the+hash-bound repairs it prints a receipt for, the only holds it clears are the+ones those repairs import, and refusing is the only way it leaves a file out.+Each refusal names the file, why, and its fix. A hold whose stored repair+state says a person decides (a manual fence reason, a gate rejection, a paid+wait on a setting only the user changes, a recommended page merge) is listed+`needs_human` and never retried until the file changes.## The triple@@ -54,7 +70,12 @@ Every hold and error has three fields, from one table- `needs_human`: a person has to choose or act before it clears;`human_reason` says what. A page held three times with the same code(`attempts`) is `needs_human` whatever its code says: it keeps moving under- the sync.+ the sync. A repair-class hold is `needs_human` when its stored repair state+ says so: a fence hold the lane marked `manual` (a manual-only reason, a gate+ rejection, a model answer the run does not retry) or `paid` (spend only the+ user raises), and a slug-conflict hold the lane decided a person must settle+ ([`merge_recommended`](write-refusals.md#merge_recommended),+ [`content_repair_needs_human`](write-refusals.md#content_repair_needs_human)).## Decision table@@ -114,8 +135,15 @@ it and kept going; the receipt lists the hold (`held`, `held_count`) and- `preparation_stalled`: the write owner, not the file, stalled;`gbrain sources writer status --source <id> --json` names the step.`unblock --apply` schedules the re-screen.-- The repair codes (`invalid_fence`, `invalid_frontmatter`, …) have their own- previews: [held files](write-refusals.md#held-files-and-content-refusals).+- `invalid_fence` and `frontmatter_slug_conflict`: the content-repair lane+ clears them. `unblock --apply` runs it on the held paths now; the maintenance+ run's `fence_repair` and `content_repair` phases run it by themselves;+ `gbrain repair content --source <id>` previews it. A hold the lane will not+ decide is `needs_human` with the paragraph in `human_reason`+ ([held files](repair.md#held-files)).+- The other repair codes (`invalid_frontmatter`, `rename_held`) stay+ consent-gated: unblock refuses them with the frontmatter repair preview to+ run ([held files](write-refusals.md#held-files-and-content-refusals)).- `revision_conflict`, `page_identity_changed`, `pinned_git_worktree_conflict`as a `last_error` come from a run on an older release; this release holdsthem. Rerun with `--retry-failed`: the stopped entry converts in place, thediff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 64b89a67b1..46b23f9ead 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -151,7 +151,7 @@ with each file and fix the ones that need no guessing."*| <a id="invalid_frontmatter-needs_interpretation"></a>`invalid_frontmatter` (`needs_interpretation`) | Reading it means choosing an interpretation: unquoted continuation lines after a value, a duplicated key, an unclosed `[` or `{`. gbrain never imports a guess. | `gbrain repair frontmatter --source <source> --include-ambiguous` shows the exact interpretation per file. Show the user each diff; apply only what they approve (`--only <path>` / `--skip <path>` select files). || <a id="invalid_frontmatter-ambiguous_identity_key"></a>`invalid_frontmatter` (`ambiguous_identity_key`) | `slug`, `type`, `id` or `source_id` appears twice, or its line was swallowed into another value, so gbrain cannot tell which page the file is. | Edit the file by hand: keep exactly one line for the key. The user decides which value is right. || <a id="invalid_frontmatter-ambiguous_protected_key"></a>`invalid_frontmatter` (`ambiguous_protected_key`) | A key that decides access or provenance (`visibility`, `derived_from`, …) is malformed, duplicated, swallowed into another value, rewritten by quoting, or inside an unclosed fence. gbrain never reads such a key as a broader value. | Edit the file by hand: write the key on one line with one quoted value. Ask the user which visibility is intended; never guess it. |-| <a id="frontmatter_slug_conflict"></a>`frontmatter_slug_conflict` | The file's frontmatter `slug:` names a different page than its path does (earlier releases reported this as `invalid_params`). The path decides the slug. | Remove the `slug:` line or make it match the path, or move the file to the path its slug names; `gbrain repair frontmatter --source <source> --include-ambiguous` proposes removing the line. Commit and sync. |+| <a id="frontmatter_slug_conflict"></a>`frontmatter_slug_conflict` | The file's frontmatter `slug:` names a different page than its path does (earlier releases reported this as `invalid_params`). The path decides the slug. The hold has three outcomes once the content-repair lane's `slug-conflicts` kind runs it (the maintenance run's `content_repair` phase, `gbrain sync unblock --apply`, or `gbrain repair content --source <source>`): **removed** (the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token: the stray `slug:` line is removed, the file imported and committed, the hold cleared, with a receipt; a model under the `fences.repair` caps makes the same call when the two pages are not obviously different), **merge recommended** ([`merge_recommended`](#merge_recommended): the two files describe the same thing; gbrain recommends the merge and names the canonical page but never merges pages by itself), or **undecided** ([`content_repair_needs_human`](#content_repair_needs_human)). Until that kind ships, the lane leaves the hold to the frontmatter repair preview below. | Nothing to run when the lane removes the line: the hold clears on the sync it prints. For a recommendation or an undecided hold, `gbrain sync status --source <source> --json` carries the paragraph (`human_reason`): merge the unique sections into the canonical page by hand or decide which page keeps the slug, delete or edit the file, commit, then `gbrain sync --source <source> --no-pull`. By hand at any time: remove the `slug:` line or make it match the path, or move the file to the path its slug names (`gbrain repair frontmatter --source <source> --include-ambiguous` proposes removing the line, for approval). || <a id="file_too_large"></a>`file_too_large` | Over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read). The limit is fixed. | Split the file into smaller files and commit, or leave it out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`. The next `gbrain sync --source <source> --no-pull` clears the hold. || <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | With multimodal embedding on (`embedding_multimodal` / `GBRAIN_EMBEDDING_MULTIMODAL`), sync admits image files, but managed sync has no image importer yet. Each image import is held instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken; keeping them held is fine. To stop holding images, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`) or turn multimodal embedding off; either clears the holds on the next `gbrain sync --source <source> --no-pull`. A held image is re-screened when it changes and on `gbrain sources retry-held <source>`. || <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. |@@ -161,7 +161,7 @@ with each file and fix the ones that need no guessing."*| <a id="preparation_stalled-hold"></a>`preparation_stalled` | The write for this file could not finish *preparing* within its attempt limit, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`preparation_stalled`](#preparation_stalled). | `gbrain sources writer status --source <source> --json` (read-only), fix what it names, then `gbrain sources retry-held <source>` and the same sync with its options. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). || <a id="worktree_dirty"></a>`worktree_dirty` | The working tree holds uncommitted bytes for this file that match neither the pinned commit nor the current page (an agent mid-edit on a live checkout), and importing the pinned version would discard them (#6340). Before this release the refusal (`source_changed` / `pinned_git_worktree_conflict`) stopped the whole run; now the file is held, the local edit is untouched and the rest of the source syncs. The hold keeps the pinned blob (`meta.blob_oid`) and a hash of the working bytes, counts `meta.attempts` each time the same file is held again, and a page held three times is reported `needs_human` by `gbrain sync status`. Bytes that are **committed at HEAD** past the pinned target are not a conflict at all: sync imports them as HEAD has them and the later pin..HEAD diff re-imports the same bytes as a no-op. | Commit the edit (or restore the file), then `gbrain sync unblock --source <source> --apply` re-screens every held file that is now committed and prints the sync to run (`gbrain sources retry-held <source>` does the same for all holds). A later commit that changes the file re-screens it on its own. Never discard or normalize the local bytes. Runbook: [sync unblock](sync-unblock-runbook.md). || <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `sync.parser_regression=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull --retry-failed`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). |-| <a id="changed_since_preview"></a>`changed_since_preview` | A hash-bound repair apply (`gbrain repair frontmatter --apply --expect <hash>`, `gbrain repair fences --apply --expect <hash>`) found a file, its proposed change or its page different from what the preview showed, so that item was not written; the rest of the approved set still applied. | Preview again with the same selection and apply the new hash. For frontmatter, show the user the new diff first; a fence repair needs no extra consent ([fence reason](#fence-changed_since_preview)). |+| <a id="changed_since_preview"></a>`changed_since_preview` | A hash-bound repair apply (`gbrain repair frontmatter --apply --expect <hash>`, `gbrain repair fences --apply --expect <hash>`, `gbrain repair content --apply --expect <h1>[,<h2>]`) found a file, its proposed change or its page different from what the preview showed, so that item was not written; the rest of the approved set still applied. | Preview again with the same selection and apply the new hash (for the content lane, one hash per kind in lane order). For frontmatter, show the user the new diff first; a fence repair needs no extra consent ([fence reason](#fence-changed_since_preview)). |<a id="invalid_fence"></a>### Fence holds (`invalid_fence`)@@ -318,9 +318,9 @@ clears or retries it with no one acting.| <a id="fence-holder_unresolved"></a>`holder_unresolved` | A takes `who` cell is not `world`, `brain`, `people/<slug>` or `companies/<slug>` (for example a person's display name). | `resolver` | yes | Rewritten by the next maintenance run when it resolves to exactly one verified `people/` or `companies/` page (never a private page on a world-visible page). Otherwise write one of those forms by hand. Format: [holders](fence-format.md#holders). || <a id="fence-missing_begin"></a>`missing_begin` | An end marker has no begin marker before it. | `manual` | no | Add the begin marker above the table, or delete the stray end marker. Format: [markers](fence-format.md#markers). || <a id="fence-split_rows"></a>`split_rows` | A fence has no end marker and its rows are split by blank lines or text, so gbrain cannot tell which rows belong to it. | `manual` | no | Join the rows into one table and add the end marker after the last row. Format: [markers](fence-format.md#markers). |-| <a id="fence-unclosed_trailing_content"></a>`unclosed_trailing_content` | A fence has no end marker and other text follows its table, so closing it automatically could expose text the privacy boundary hides. | `manual` | no | Add the end marker directly after the last table row, or wrap a mere mention of the marker in backticks. Format: [markers](fence-format.md#markers). |+| <a id="fence-unclosed_trailing_content"></a>`unclosed_trailing_content` | A fence has no end marker and other text follows its table (for example bullets an ingest job appended after an open fence). Everything after the unpaired begin marker is hidden by the privacy boundary, so closing the fence after its last row would make those lines visible to whatever reads through it. On a **private** page nothing new is disclosed (remote readers never see its body), so the lane closes the fence after the last row by itself and the receipt records `trailing_lines`. On a **world** page the repair model classifies the tail (it sees the fence's begin line, header, rows and the trailing lines to the section end, never the rest of the page): `prose` makes the close previewable under [`tail_exposure_approval`](#tail_exposure_approval), where the preview prints the exact lines that would become visible and only a hash-bound `--apply --expect` applies it; `rows` or `unsure` is [`unclosed_ambiguous_tail`](#unclosed_ambiguous_tail), a manual edit. A tail that mentions a marker stays `marker_near_miss`. | `manual` | no | Private page: nothing, the next maintenance run closes it (preview: `gbrain repair fences --source <source>`). World page: review the preview's exposed lines and run the printed `gbrain repair content --source <source> --only <path> --apply --expect <hash>`, or by hand add the end marker directly after the last table row and move the trailing text where it belongs. Format: [markers](fence-format.md#markers). || <a id="fence-marker_near_miss"></a>`marker_near_miss` | A line uses the two-dash takes marker (`<!-- gbrain:takes:begin -->`) or mentions it with no takes table after it. Two-dash markers directly above a takes table are rewritten by themselves. | `manual` | no | Use the exact three-dash markers around the takes table, or wrap a mere mention in backticks. Format: [markers](fence-format.md#markers). |-| <a id="fence-repeated_marker"></a>`repeated_marker` | A body or timeline section has a second begin or end marker for the same fence outside code. | `manual` | no | Keep one begin and one end marker per fence in that section, with every row in one table. Format: [markers](fence-format.md#markers). |+| <a id="fence-repeated_marker"></a>`repeated_marker` | A body or timeline section has a second begin or end marker for the same fence outside code: usually two `## Facts` tables in one page. When every fence of that kind in the section is balanced and its header maps to the canonical columns, the Tier 1 `merge_fences` rule repairs it with no model and no approval: the later fences' rows are appended to the first in document order, a row whose cells equal a kept row's after trimming is dropped as an exact duplicate (near-duplicates both stay; contradictions own that case), a colliding row number is renumbered above the page's highest, the extra markers and a duplicated heading are removed, and the merge validator proves every original row survived or the write is refused. Anything else (an unbalanced repeat, a header that does not map, text inside the repeated region) stays manual. | `manual` | no | Nothing when the merge applies: the next maintenance run (or `gbrain sync unblock --source <source> --apply`) repairs and commits it with a receipt listing the merged occurrences; `gbrain repair fences --source <source>` previews the merged table. Otherwise keep one begin and one end marker per fence in that section, with every row in one table. Format: [markers](fence-format.md#markers). || <a id="fence-takes_in_facts"></a>`takes_in_facts` | A facts fence holds a takes table. | `manual` | no | Move the rows into a takes fence (or add them with `takes_add`), or rewrite them as facts rows. Format: [takes](fence-format.md#takes-columns). || <a id="fence-superseded_ambiguous"></a>`superseded_ambiguous` | Two rows share a number and a `superseded by #N` reference names that number, so renumbering could repoint the reference. | `manual` | no | Decide which row keeps the number, give the other a number above every number on the page, and fix the reference. Format: [row numbers](fence-format.md#row-numbers). || <a id="fence-enum_unmapped"></a>`enum_unmapped` | A facts `kind`, `visibility` or `notability` cell holds a value outside the allowed list and its synonyms (the message names the column and the allowed values). | `manual` | no | Use one of the allowed values. Format: [facts](fence-format.md#facts-columns). |@@ -382,6 +382,30 @@ than `sync.hold_escalate_pct` (default 5%) of a run's screened imports (atleast 40), sets `holds_escalated` and makes doctor `git_held_files` fail: agenerator or an upgrade is likely writing or reading files wrong.+<a id="content-repair-lane"></a>+### The content-repair lane++Fence and slug-conflict holds clear by themselves: the maintenance run's+`fence_repair` phase runs the `fences` kind and its `content_repair` phase+runs every other kind of the lane (`src/core/repair/content-lane.ts`), and+`gbrain sync unblock --source <source> --apply` runs the lane on the held paths+now. Each repair is a hash-bound write with a receipt and a Git trailer; a+model decides only the cases the deterministic rules mark ambiguous, under the+`fences.repair` caps, and every byte written comes from a rule and passes the+gates. The lane records four outcomes a person reads, each with the agent+operator envelope (`code`, `message`, `why`, `fix.next`); `gbrain errors <code>`+explains each offline. Walkthrough: [held files](repair.md#held-files).++**Say to your agent:** *"Sync is holding a few files. Repair the ones gbrain+can and tell me what it wants me to decide about the rest."*++| Code | What it means | Envelope |+| --- | --- | --- |+| <a id="unclosed_ambiguous_tail"></a>`unclosed_ambiguous_tail` | An `invalid_fence` reason: a fence has no end marker, text follows its table, and the repair model read the tail as table rows written without pipes (`rows`) or could not tell (`unsure`), so gbrain will not choose where the fence ends. Nothing was written; the memo keeps the same bytes from costing twice. | `fix.next: tell_user_to_run`, actor `user`: the hold's `fix` is the read-only preview naming the fence, section and last row; the person adds the end marker after the last real row (moving any rows the tail holds into the table), commits, then `gbrain sync --source <source> --no-pull`. `why`: closing after the wrong row would hide rows or expose text. |+| <a id="tail_exposure_approval"></a>`tail_exposure_approval` | An `invalid_fence` reason on a world-visible page: the repair model read the trailing lines as prose, so closing the fence after its last row is safe for the table but makes those lines visible to remote readers. The close is previewable, never unattended: the preview prints the exact lines (`L1-L2`) that would become visible and the hash binds them. `paid: false`. | `fix.next: ask_user`, actor `user`, `consent: []`: the hold's `fix` is `gbrain repair content --source <source> --only <path> --apply --expect <hash>` with `preview_argv` the lane preview and `plan_hash` the hash; relay the preview's exposed lines, run the fix only after the user agrees. A changed tail invalidates the hash (`changed_since_preview`). `why`: the privacy boundary hid those lines until now. |+| <a id="merge_recommended"></a>`merge_recommended` | A `frontmatter_slug_conflict` hold whose two files describe the same thing (a duplicate person or company page): the lane's deterministic tier found something to merge into and the model answered `merge_into <canonical>`, so removing the `slug:` line would have minted a second page. Nothing was written; the hold carries `meta.content_repair: { action: 'merge_into', canonical }` (codes and slugs only) and `sync status` renders the paragraph. gbrain does not merge pages by itself yet. | `fix.next: tell_user_to_run`, actor `user`: "This file and page `<canonical>` describe the same `<type>`; gbrain recommends merging the unique sections of `<path>` into `<canonical>` and deleting `<path>`, then committing; the hold clears on the next sync." `fix.argv` reads both pages (`gbrain get --source <source> -- <slug>`); `verify` is `gbrain sync status --source <source> --json`. Not retried until the file changes. |+| <a id="content_repair_needs_human"></a>`content_repair_needs_human` | A `frontmatter_slug_conflict` hold the lane could not decide: the deterministic tier marked it ambiguous and the model answered `needs_human` (or model repair is off, out of budget or unavailable for the day). Nothing was written; the hold carries `meta.content_repair: { action: 'needs_human' }` and `sync status` says `needs_human: true`. | `fix.next: tell_user_to_run`, actor `user`: "gbrain could not decide whether `<path>` and `<canonical>` are the same page; decide which keeps the slug: remove the `slug:` line, move the file, or merge the pages, then commit." A budget or model wait names its setting instead (`fences.repair.max_usd_per_day`, `fences.repair.llm`, consent `paid`, `fix.next: ask_user`). `verify` is `gbrain sync status --source <source> --json`. |+## Worktree refresh refusals`gbrain sources refresh <source>` is the one supported way to move a manageddiff --git a/docs/plans/2026-10-09-001-fix-content-repair-lane-6377-plan.md b/docs/plans/2026-10-09-001-fix-content-repair-lane-6377-plan.mdnew file mode 100644index 0000000000..958bb9fbf6--- /dev/null+++ b/docs/plans/2026-10-09-001-fix-content-repair-lane-6377-plan.md@@ -0,0 +1,122 @@+## Implementation plan+# Content-repair lane (#6377): sync holds clear themselves, a frontier model decides the cases that need judgment++Thread: GBRA-72. Issue: #6377. Builds on #5988 (holds), #6188 (fence repair tiers, gates, caps, maintenance phase), #6340/#6347 (`sync status` / `sync unblock`, the class / safe_actions / needs_human triple). One PR to `garrytan/gbrain`, version stamped at the merge slot (master + 1 PATCH; no migration expected). Paired gbrain-evals PR for the model-tier eval. Reviewed by /autoplan (CEO, DX, Eng; Codex gpt-6-astra outside voice, 13 findings; record in section 8).++## 0. Why now++Holding instead of failing (#5988, #6188, #6347) was the first half. The second half is still a person: every content hold ends with "gbrain will not guess this repair" and a `fix` that sends an operator to edit a file. On Garry's brain on 2026-10-09 five holds (`invalid_fence` ×2, `frontmatter_slug_conflict` ×3) sat 16 hours until an external agent fixed them by hand; the week before, the same brain needed 198 frontmatter repairs, 471 glued-fence repairs and 146 fence-adoption retries from an external agent writing ad-hoc scripts against gbrain's error messages. Four of the five holds were mechanical. The fifth (a duplicate person page) is the case where gbrain's deterministic proposal (delete the `slug:` line) would have made the brain worse: it would have minted a second page for the same person.++Goal: the end user never sees a content hold unless gbrain itself, after trying, says `needs_human` with a one-paragraph reason written for a person and the exact command that applies what it proposes.++## 1. What exists today (read on master dda603ac)++- Holds: `src/core/persistence/sync-holds.ts` (one `op_checkpoints` row per hold, `gitHoldFix` per code, `holdRepairSteps` per source; hold metadata is location-only by contract, `sync-holds.ts:20`). `sync status` / `sync unblock` (`src/core/persistence/sync-status.ts`, `sync-fault-class.ts`): both codes already carry `safe_actions: ['repair']` (`sync-fault-class.ts:46,48`); what is missing is execution: `unblock --apply` **refuses** them ("not something unblock performs; run the fix it names", `sync-status.ts:162`) and `UnblockOutcome.applied.action` admits only `retry` actions (`sync-status.ts:126`).+- Fence repair (`src/core/fence-repair/*`, `src/core/repair/fences.ts`): Tier 1 lossless rules (`normalize.ts`, `structure.ts`, `content.ts`), Tier 2 holder resolver, Tier 3 model (`llm.ts`: the model sees the header plus the residual rows only, returns one table; `TIER3_REASONS` = screen reasons with `tier: 'llm'`), gates (a)–(g) (`validate.ts`; pairs compare `primaryFence` only, `validate.ts:87`, positional rows, `validate.ts:105`), attempt memo, daily USD ledger (`FENCE_REPAIR_LEDGER = {scope:'llm_repair', resolver:'fences'}`, each key its own ceiling), caps `fences.repair.max_usd_per_page` ($0.30) / `_per_day` ($1), switches `fences.repair.enabled` / `fences.repair.llm` (default on), model `models.fence_repair` with the measured fallback list (`measured.ts`). The preview calls no model; model output is produced at apply time (`fences.ts:18`). The maintenance cycle runs it (`src/core/cycle/fence-repair.ts`, 300 s budget). Receipts ride the write (`receipt.ts`) and the commit subject is `gbrain: repair fence in <path> (<classes>)` (`effect-model.ts:18`).+- The two fence reasons in the issue are **manual-only** in the reason table (`reasons.ts`): `repeated_marker` and `unclosed_trailing_content`. `structure.ts planClose` (line 115) refuses to close when text trails the table because gate (g): everything after an unpaired begin marker is hidden by the privacy boundary (`page-checks.ts:7`, shared by remote sanitization, the chunker and the strip functions), and closing early would publish it. `fenceBlocked` skips any fence with a repeated marker.+- `frontmatter_slug_conflict` (`markdown.ts:542`): held when frontmatter `slug:` differs from the path slug after slug normalization and the `slugExempt` check (a declared slug that already is the page's own slug is exempt). `gbrain repair frontmatter --include-ambiguous` proposes removing the line (`repair/frontmatter.ts:175`); the kind is `explicit_only` + `consent: 'destructive'`, so nothing runs it unattended.+- Page merge primitives exist only for the narrow phantom shape (`cycle/phantom-redirect.ts`, `phantom-redirect-managed.ts`: both page keys locked, deletion bound to the merged revision, withdrawals moved before facts, custom frontmatter and timeline residue refused, `phantom-redirect.ts:455-509`). Nothing general; `deletePageThrough` (`write-through.ts:563`) is best-effort and takes no commit subject.++## 2. Design++One lane, two tiers, one contract. Every repair goes preview → hash-bound apply → receipt, and the maintenance cycle applies the current plan unattended under the caps, exactly as `fence_repair` does today. The model **chooses**; every byte written comes from a deterministic rule and passes the gates.++### Lane A: fence structure repairs become deterministic (Tier 1), with the model for the judgment residue++A1. **`merge_fences`** (new Tier 1 fix class; clears `repeated_marker`). When one section holds N > 1 fences of the same kind and each is balanced (begin and end marker) with a header that maps to the canonical columns: the later fences' rows are appended to the primary fence in document order; a row whose cells (every column except the row number) equal a kept row's cells after cell trimming is dropped as an exact duplicate; an appended row whose number collides with a kept row is renumbered above the page's highest number (stored rows consulted as the `renumber` rule does; `superseded by #N` references follow); the later fences' markers, tables and a duplicated section heading immediately above them (`## Facts` twice) are removed; blank lines collapse to one. Anything else (an unbalanced repeat, a header that does not map, a repeat whose region holds non-table text) stays `repeated_marker` manual. Near-duplicates (same claim, different confidence or date) are **not** deduped: both rows stay and the contradiction machinery owns that case.++ **Validator (Codex #3).** The gates pair `primaryFence` before and after, positionally, so a merge is invisible to them. `validate.ts` gains a merge mapping: when the before section holds several fences of a kind and the after holds one and the fixes include `merge_fences`, the before rows are the concatenation of every fence's rows in document order, each mapped to an after row by occurrence or marked `duplicate_of: <occurrence>`; gates (b) claims, (c) numbers, (d) visibility and (f) cells run through that mapping; gate (e) accepts exactly the rows marked duplicate and only when the kept row's cells are byte-equal after trimming. Gate (c) already skips a number that is not page-unique (`validate.ts:126`), so a renumbered colliding row passes it and every unique number keeps its claim. The receipt carries occurrence identities (`merged: {fences: N, rows: [{occurrence, from_fence, kept_as | duplicate_of}]}`), never cell text. T1 mutates a claim in the *second* fence and proves gate (b) rejects it.++A2. **Closing an unclosed fence ahead of trailing text** (clears `unclosed_trailing_content`; Codex #2 reshaped it). The fence has no end marker, its rows are one contiguous block, and lines follow the last row. Closing after the last row makes those lines visible to whatever reads through the privacy boundary. Two cases:+ - **No exposure**: the page is `private` (effective visibility: `effectiveVisibility`, the same read the fence ctx already makes). Remote readers never see a private page's body and local readers see everything, so nothing new is disclosed; the end marker is inserted after the last row deterministically (`close_fence`, as today when nothing trails) and the receipt records `trailing_lines: N`. Gate (g) is unchanged: on a private page the boundary hides nothing from anyone, and the gate exemption is keyed to that fact, not to the fix class.+ - **Exposure** (a `world` page): nothing unattended. The model tier (A3) classifies the tail; a `prose` verdict makes the close **previewable** (the preview prints the exact lines that would become visible and the hash binds them), and only an explicit `gbrain repair content --apply --expect <hash>` applies it. Unattended runs (cycle, `sync unblock`) record `needs_human` with the rendered paragraph: "gbrain can close the takes fence in the timeline after row N; lines L1–L2 would then be visible to readers of this page. Approve with: gbrain repair content --source <id> --only <path> --apply --expect <hash>". So the one judgment that discloses text is the user's, hash-bound, as Codex asked; everything else clears itself.+ - A tail that mentions a fence marker stays `marker_near_miss` manual as today.++A3. **Model tier for the tail** (new Tier 3 request kind `tail`, same gateway call, caps, ledger and memo as rows). The model sees the fence's begin line, header, every row and the trailing lines to the section end (never the rest of the page) and answers one JSON object `{"tail": "prose" | "rows" | "unsure"}`. `rows` (the tail holds table rows written without pipes) and `unsure` render `unclosed_ambiguous_tail` (new reason, manual, with the exact edit); `prose` on a world page yields the previewable close above; on a private page the model is never called (A2 closes deterministically). The memo key is the fence region's sha256 + model + prompt version, so an unchanged tail never costs twice and a transient `llm_unavailable` does not consume it. The `rows_through_line` realignment idea from the first draft is cut (Codex #1): once a fence is closed, the existing row rules and the row prompt handle its rows on the next normalization round.++### Lane B: `frontmatter_slug_conflict` gets a judgment tier; merging is recommended, not executed++B1. **New repair kind `slug-conflicts`** (`src/core/repair/slug-conflicts.ts`; `REPAIR_KINDS` + `registry.ts` with `preview_bound: true`, `spends: 'llm'`, `checks: []` so doctor's first-match lookup keeps `git_held_files` on `frontmatter` (Codex #12), **not** `explicit_only`, so `--all`, `doctor --remediate` and the cycle phase run it). Candidates: every `frontmatter_slug_conflict` hold of the sources in scope (plus `--only <path>`). Identity is resolved, not textual (Codex #8): the frontmatter slug is normalized the way the screen does, resolved through `slug_aliases` (`readPageSnapshot(..., {resolveAlias: true})`) to a page id in the same source; a slug that resolves to the held file's own page is `slugExempt` and never a candidate; the held file may have no page yet (`page_id: null`, a new file) and that is a normal candidate.++B2. **Deterministic tier** (no model, confidence `high`): `remove_slug` when the named slug resolves to **no page** and names no other file in the checkout (a stray `slug:` from a template or a renamed file; nothing to merge into), or when the named page has a different `type` **and** shares no title token with the held file (the two COMPENDIUM cases). The edit is the one line, applied through the frontmatter repair's existing publication path (`prepareRepairPublication` / `submitManagedFileRepair`: exact bytes bound to the sha256 the preview read, import, hold clear and Git target effect in one coordinated write; legacy sources back up, write, import, clear the hold and print the commit step). Everything else is `ambiguous` → B3.++B3. **Model tier** (`tier: 'llm'`). The model sees: both files' frontmatter, headings and first 60 lines of body plus any line that mentions the other's slug anywhere in either body (Codex #7: evidence beyond the first 60 lines), both slugs and paths, the hold's reason, and the allowed answers. It returns one JSON object: `{"action":"remove_slug"}`, `{"action":"merge_into","canonical":"<one of the two slugs>"}` or `{"action":"needs_human"}`, plus an optional `why` sentence that goes into the run's output only, never into hold metadata (Codex #11). Same provider path as the fence tier, same failure classes, same `thinkingOffControl` and output ceiling. Memo key: sha256 of both participants' content + both ids + model + prompt version + rules version. Model: `models.content_repair` (explicit always runs) else `models.fence_repair` else the content-repair measured list (section 4), else the fence list. **Caps and ledger (Codex #9):** the kind reserves against the existing `FENCE_REPAIR_LEDGER` identity (one `fences.repair.max_usd_per_day` for the whole lane, today's prior spend counted) and the same per-page cap; `repair content` passes the fences run's remaining allowance into the slug-conflicts run. `fences.repair.llm=false` turns the model tier off for both kinds; `--no-llm` per run.++B4. **Outcomes.** `remove_slug` (deterministic, or the model's answer) applies as in B2. `merge_into` is **not executed in this PR**: it becomes `needs_human` with the rendered paragraph "This file and page `<canonical>` describe the same `<type>`; gbrain recommends merging the unique sections of `<path>` into `<canonical>` and deleting `<path>`, then committing; the hold clears on the next sync. gbrain does not merge pages by itself yet." and the recommendation stored as codes and slugs on the hold (`meta.content_repair: {action:'merge_into', canonical, model, at}`). `needs_human` from the model renders the generic paragraph ("gbrain could not decide whether `<path>` and `<canonical>` are the same page; decide which keeps the slug …"). Codex #4–#7 show that a general lossless merge needs coordinated two-page intents (both ids, revisions, incarnation, owner epoch, file hashes), withdrawal and metadata preservation rules, revision-bound deletion and database-aware recovery that the phantom path has only for its narrow shape. That is a feature of its own, filed in TODOS.md with those requirements; the acceptance criterion for the duplicate case ("merge_into … or needs_human with that recommendation, not a slug deletion") is met by the recommendation.++B5. **Receipt, trailer and hold state (Codex #6, #11).** Every content repair commit (fence and slug-conflict) carries the Git trailer `gbrain-repair: <hold_code> <tier> <confidence>` through the commit note in `effect-model.ts` (`fenceRepairCommit` gains a trailer line the Git effect prints after a blank line; legacy commit steps print the same `-m` pair). The durable receipt is the write's outcome: the existing `fence_repair` receipt gains `merged`/`trailing_lines`; the slug-conflict write carries a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256), validated by a parser like `parseFenceRepairReceipt` so nothing forged reaches a commit message. Receipts distinguish `published` from the Git effect's own state (`committed: effect | commit_step | not_in_git`) as the fence receipt does today; no promise about reverting beyond "git revert of the single file commit restores the bytes; the hold then re-screens". Hold state: `meta.content_repair` is written with `recordContentHoldRepair` (conditional on the hold's `upstream_version`, like `recordFenceHoldRepair`), carries reason codes, slugs, `at` and `next_attempt_after` only, and `writeGitHold` keeps it when a re-screen rewrites a hold with the same `upstream_version` and code; a changed file drops it. `sync status` renders `needs_human: true` and the paragraph from those codes (`human_reason` templates in `sync-fault-class.ts`), never model prose. A hold the lane could not decide is retried on `next_attempt_after` (24 h for `llm_unavailable`/`budget_exhausted`, never for `needs_human` until the file changes).++### Lane C: the lane runs by itself++C1. **Cycle phase `content_repair`** (`src/core/cycle/content-repair.ts`, after `fence_repair` in the phase table): one bounded run of `slug-conflicts` through `repairRunner` (apply on a real run, preview on dry run), deadline min(120 s, a third of the job's remaining time), gated on `fences.repair.enabled`; reports counts by action and reason, spend and the oldest unresolved hold's age; never fails the cycle. `holdRepairSteps` says "the next maintenance run repairs the fence and slug-conflict holds it can by itself" when the lane is active. Every unresolved hold stays listed with its state (`needs_human`, `paid`, `owner`, `apply`): nothing hides budget-blocked or owner-unavailable work (Codex #12).++C2. **`sync unblock --apply`** performs `repair`: for `invalid_fence` holds it runs the `fences` kind on those paths, for `frontmatter_slug_conflict` the `slug-conflicts` kind, each a bounded apply under the caps, then schedules the re-screen and prints the sync. `UnblockOutcome.applied` gains `action: 'repair'` with per-path structured outcomes (`repaired | held | needs_human | skipped`, reason code, `llm_usd`, receipt ref, exact next action); `--no-llm` keeps to the free tiers; `--no-repair` restores the old refuse-only behaviour. The runbook sentence "unblock writes no page" changes to "unblock writes only hash-bound repairs and prints each receipt" (BEHAVIOR_CHANGES row). `invalid_frontmatter` and `rename_held` still route to `repair frontmatter` (interpretive YAML fixes stay consent-gated; TODOS entry with the weekly counts from the issue).++C3. **`gbrain repair content`** runs `fences` then `slug-conflicts` for the same `--source`/`--only` selection, printing each kind's own preview hash (no combined hash scheme); `--apply` without `--expect` applies both current plans (both kinds are `preview_bound` without `explicit_only`, as `fences` is today), `--apply --expect <fences-hash>[,<slug-hash>]` applies exactly those sets, `--max-usd` is the lane's allowance for the run (remaining allowance flows from the first kind to the second). Both component plans are built before the first mutation (Codex #10). `gitHoldFix` names this command for both codes.++C4. **Reason table and surfaces.** New reasons in `reasons.ts`: `unclosed_ambiguous_tail` (manual, exact edit), `tail_exposure_approval` (paid: false, actor `user`, the hash-bound approval above). Error registry rows with agent-operator envelopes for `unclosed_ambiguous_tail`, `tail_exposure_approval`, `content_repair_needs_human`, `merge_recommended`; `bun run build:error-codes`. `holdRescreenDue` is unchanged for slug conflicts (already unconditional, `sync-holds.ts:343`); `FENCE_RULES_VERSION` bumps so older fence holds re-screen under the widened rules.++### What this plan does not do++- No LLM-composed text, no model-executed merge: the model chooses among coded actions; every byte written comes from a deterministic rule and passes the gates.+- No page merge executor (B4; follow-up with Codex's requirements in TODOS.md).+- No YAML frontmatter interpretation unattended (the 198 weekly frontmatter repairs): TODOS.md.+- No change to what `put_page`/`capture` accept on write beyond the Tier 1 `merge_fences` rule, which `fences.normalize` already governs (lossless, gated).++## 3. Tests (smallest set that proves each claim)++- T1 `fence-repair-structure.test.ts`: A1 merges two balanced facts fences (3 rows + 85 rows, 3 exact duplicates) into one, removes the duplicate heading, renumbers collisions, records occurrences; a mutated claim in the **second** fence fails gate (b); a dropped non-duplicate fails (e); an unbalanced repeat or a non-mapping header stays manual; near-duplicates both kept. A2: a private page with two trailing bullets closes after the last row with `trailing_lines: 2`; a world page with the same tail is not closed unattended and renders `tail_exposure_approval`; a marker mention stays manual.+- T2 `fence-repair-llm.test.ts`: the tail prompt builds from the fence region only; `prose`/`rows`/`unsure` parse; malformed/truncated/refused classes; `prose` on a world page produces the previewable close whose hash covers the exposed lines; a changed tail invalidates the hash; the memo blocks a second paid call on unchanged bytes and does not consume on `llm_unavailable`.+- T2b (Codex #2): a world page whose unclosed tail holds a sentence; after an unattended cycle and `sync unblock --apply`, remote `get_page`, remote search and the chunker still do not return that sentence; after the explicit hash-bound apply they do.+- T3 `repair-slug-conflicts.test.ts` (PGLite + temp Git checkout, as `repair-fences.test.ts`): deterministic `remove_slug` when the named page is absent, or of another type with no shared title token; a slug resolving through an alias to the held file's own page is exempt; the duplicate-person pair (mutual hygiene notes) goes to the model tier; stubbed `merge_into` → hold carries `content_repair` codes, `sync status` shows `needs_human` with the rendered paragraph naming the canonical, nothing written; stubbed `remove_slug` applies through the coordinated path and clears the hold; preview writes nothing and calls no model; `changed_since_preview`; cap exhaustion → `budget_exhausted` and nothing applied; the ledger key is `FENCE_REPAIR_LEDGER` (a prior fences spend counts).+- T4 `sync-status-unblock.test.ts`: `unblock --apply` repairs an `invalid_fence` hold and a deterministic slug-conflict hold, lists structured per-path outcomes, schedules re-screens, prints the sync; `--no-llm` holds the model-tier candidate `llm_disabled`; `--no-repair` refuses as before; `needs_human` holds are listed and not retried.+- T5 `cycle-content-repair.test.ts`: the phase runs within budget, gates on `fences.repair.enabled`, reports counts, never fails the cycle.+- T6 Acceptance fixture (`test/fixtures/content-repair/`, placeholder names): the issue's five holds plus 45 seeded ones across `repeated_marker`, `unclosed_trailing_content` (private and world pages), `frontmatter_slug_conflict` (absent page, other type, duplicate pair, alias-exempt). One maintenance cycle with the transport stubbed, then the printed re-screen sync; assert the exact remaining hold set: the world-page tails as `tail_exposure_approval`, the duplicate pair as `merge_recommended`, everything else cleared with a receipt each (Codex #13).+- T7 Goldens: export surface, CLI flag registry, error-code registry, behavior-change notice, docs anchors, sync-runbook table pin.++## 4. Eval (gbrain-evals, paired PR)++`evals/content-repair-judgment/`: 48 synthetic pairs with placeholder names: 15 true duplicates with mutual notes, 10 true duplicates without notes, 10 stray template slugs onto unrelated pages, 8 adversarial (unrelated people with the same name, a misleading `-2` suffix on a different person, a forged "duplicate" note pointing at an unrelated page, identity evidence only after line 60), 5 genuinely ambiguous. Models per the project rule: `openai:gpt-6.1-sol`, `anthropic:claude-opus-5-5`, `anthropic:claude-sonnet-5-5` (no Fable, no gpt-5.4-mini, no older generations); 3 runs each. Preregistered rule (Codex #7): hard failures are `remove_slug` on a true duplicate and `merge_into` on an unrelated pair or with the wrong canonical; a model qualifies with zero hard failures and ≥ 80% `merge_into` with the right canonical on true duplicates; `needs_human` is always acceptable. Verdicts and preregistration mirrored into gbrain-evals; `CONTENT_REPAIR_MEASURED_MODELS` ships whatever met the rule, best first, ties to the cheaper model. If the eval is not done when the PR is otherwise ready, the fallback stays the fence list (both frontier) and the constant is filled by the gbrain-evals PR's follow-up; the CHANGELOG says so.++## 5. Docs, notices, release++- `docs/guides/write-refusals.md`: `repeated_marker` and `unclosed_trailing_content` say what repairs them and when the user's approval is needed; `frontmatter_slug_conflict` gets the three outcomes; new anchors `unclosed_ambiguous_tail`, `tail_exposure_approval`, `merge_recommended`, `content_repair_needs_human`. GBRA-57 (#6277 touches this guide) told before editing.+- `docs/guides/repair.md` "held files": the lane, `gbrain repair content`, the trailer, what a receipt proves. `docs/guides/sync-unblock-runbook.md`: unblock performs `repair` (hash-bound, receipts), `--no-repair`; decision-table rows updated and the pinned test regenerated.+- `docs/architecture/KEY_FILES.md` entries for `repair/slug-conflicts.ts`, `fence-repair/merge.ts`, `fence-repair/llm-tail.ts`, `cycle/content-repair.ts`. CLAUDE.md fence invariant amended (merge mapping; the private-page close).+- `src/core/behavior-change-notice.ts` rows: the maintenance run merges repeated fences, closes unclosed fences on private pages and clears stray slug conflicts by itself; a model (under the fence-repair caps) classifies ambiguous cases; `sync unblock --apply` now writes hash-bound repairs. CHANGELOG entry in the repo's voice. AGENTS.md "Sync held a file" paragraph points at the lane. TODOS.md: merge executor requirements, unattended frontmatter interpretation.+- Version: master + 1 PATCH at the merge slot (GBRA-40 confirms); every version stamp synced; `UBI_OWNER=gbra72` full gate.++## 6. Risks and the answer to each++- Disclosing hidden text → only private pages close unattended; world pages need the user's hash-bound approval of the exact lines (T2b proves remote reads stay clean until then).+- A wrong `remove_slug` mints a duplicate page → the deterministic tier removes a slug only when there is nothing to merge into (no page, or a different type with no title overlap); the model tier's hard-failure eval covers the rest; `merge_into` never deletes anything in this PR.+- Dedup drops a real row → byte equality after trimming only, recorded per occurrence; the validator mapping protects every kept row.+- Spend → one shared day cap (default $1), memo, per-page cap; `fences.repair.llm=false` is the kill switch; `--no-llm` per run.+- Racing a sync → both kinds use `repairBusy` admission re-reads and the coordinated file-repair intent's hash binding, as fences does today.+- Two threads editing `write-refusals.md` (GBRA-57) → coordinate before the docs lane; merge master before the gate.++## 7. Decisions for Garry++- D1. Duplicate pages: this PR recommends the merge (`needs_human` naming the canonical, nothing changed) instead of executing it; the executor ships separately once it has the coordinated two-page intent Codex specified. Plan: recommend now, execute in the follow-up.+- D2. Text hidden behind an unclosed fence on a world-visible page becomes visible only after you (or your agent) approve the exact lines with the hash-bound apply; private pages close by themselves. Plan: as stated.+- D3. One cap for the whole lane under the existing `fences.repair.*` keys (no new keys, no migration). Plan: keep the keys; docs call them the content-repair caps.++## 8. Review record++/autoplan 2026-10-09 (GBRA-72). Phases: CEO (scope), DX (agent operator contract), Eng (dual voices: Claude adversarial pass + Codex `gpt-6-astra` outside review, `~/.capy/work/gbra72/codex-review.md`, verdict needs-rework on draft 1). Decisions applied to draft 2 above, by principle (safety over convenience, reuse over new machinery, smallest change that meets acceptance, no guessing about privacy):++| # | Finding (Codex / own) | Decision |+|---|---|---|+| 1 | Scope: general merge system beyond acceptance; cut the structure classifier unless needed | Merge executor cut (B4 → recommendation + TODOS). Tail classifier kept, narrowed to one question (`prose|rows|unsure`); `rows_through_line` cut. |+| 2 | Blocker: pipe-free tail is no permission to expose text | Accepted. Unattended close only on private pages (no disclosure); world pages need the user's hash-bound approval of the exact lines; T2b proves remote reads stay clean. |+| 3 | Blocker: validator pairs primary fences only; gate (c) has no renumber exemption | Accepted. Merge mapping in `validate.ts` through every gate; (c) already tolerates non-unique numbers; receipts carry occurrences; T1 mutates the second fence. |+| 4–6 | Blockers: merge overwrites concurrent work, drops metadata/withdrawals, false two-commit revert claim | Accepted by removing merge execution from this PR; requirements recorded in TODOS.md for the follow-up. |+| 7 | Blocker: corroboration and eval do not guard false merges | Eval rule rewritten with hard failures and adversarial pairs; no unattended merge at all in this PR. |+| 8 | Identity: aliases, pageless held files, slug exemptions | Accepted (B1). |+| 9 | Ledger: new resolver key is a new bucket | Accepted: reuse `FENCE_REPAIR_LEDGER`; remaining allowance flows between kinds; memo keyed on both participants. |+| 10 | Explicit approval must bind a concrete decision | Accepted where it still applies: the tail approval hash binds the exact exposed lines; both component plans built before the first mutation. |+| 11 | Hold metadata contract; model prose | Accepted: codes and slugs only on the hold, templates render the paragraph, conditional writes carried across re-screens. |+| 12 | JSON/doctor integration | Accepted: structured per-path unblock outcomes, `checks: []` on the new kind, nothing hidden. |+| 13 | Tests do not prove safety | T2b and T6 (exact remaining set after the printed sync) added; the concurrent-writer deletion test moves with the merge executor. |+| own | Tier 1 rules also run on write paths under `fences.normalize` | `merge_fences` is lossless and gated, so it runs there too; the private-page close as well; nothing exposes on world pages without approval. |+| own | DX: `needs_human` paragraphs must carry the exact apply command | Templates include the `--apply --expect <hash>` command where one exists. |diff --git a/llms-full.txt b/llms-full.txtindex 0e43f0be6b..b8c75236a4 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1815,14 +1815,19 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contfiles through `put_page`/`capture` or a YAML serializer and check generatedcontent with `gbrain frontmatter validate --stdin --path <p>`. Walkthrough:[held files](docs/guides/repair.md#held-files). A hold with code- `invalid_fence` is a facts or takes table, not frontmatter, and clears- automatically on the next maintenance run. `gbrain repair fences --source <id>`- previews the repair and its printed apply command runs it now, with no- extra consent; a `manual` reason needs the edit the hold names (read the- page with `gbrain get --source <id> -- <slug>`, edit only that fence,- commit, `gbrain sync --source <id> --no-pull`). Raising spend+ `invalid_fence` or `frontmatter_slug_conflict` is about the file's content,+ not its YAML, and the content-repair lane clears it by itself: the next+ maintenance run repairs what it can, `gbrain sync unblock --source <id>+ --apply` does it now with a receipt per file, and+ `gbrain repair content --source <id>` previews every lane kind (its printed+ apply command runs with no extra consent). A hold the lane marks+ `needs_human` (a manual fence edit, a recommended page merge, an exposed+ tail on a world page) is listed in `gbrain sync status --source <id> --json`+ with its paragraph: relay it, make or approve the edit it names, commit,+ `gbrain sync --source <id> --no-pull`. Raising spend(`fences.repair.max_usd_per_day`, `fences.repair.llm true`) is the user's- call ([fence holds](docs/guides/write-refusals.md#invalid_fence)). A hold+ call ([the lane](docs/guides/repair.md#content-lane),+ [fence holds](docs/guides/write-refusals.md#invalid_fence)). A holdwith code `preparation_stalled` (or a managed catch-up that stops`preparation_abandoned` / `preparation_systemic`, or a write receipt with thatcode) means the write owner stalled, not the file: no repair applies. Run@@ -6880,13 +6885,25 @@ gbrain sync unblock --source <id> --apply --json # when committed_last_10m is 0gbrain sync <next.argv...> # the sync unblock (or status) names: the cursor's own options```+**Say to your agent:** *"Repair the files sync held and get the catch-up+moving again; ask me only about the ones gbrain will not decide by itself."*+1. Read `status`. `cursor` is where the run stands (`index/total`, the`pinned_target` commit, `last_advance_at`); `committed_last_10m` is thesignal that data is moving (a live process with a flat cursor is notprogress). `holds` and `last_error` each carry the triple below.2. If `needs_human` is false and nothing committed in the last ten minutes,run `unblock --apply`: it performs the safe action for every hold that has- one, refuses the rest by name, and prints the sync to run.+ one, refuses the rest by name, and prints the sync to run. For a content+ hold (`invalid_fence`; `frontmatter_slug_conflict` once its lane kind+ ships) the safe action is `repair`: unblock runs the content-repair lane+ (`gbrain repair content`, the same kinds the maintenance run uses) on+ exactly those paths as one bounded apply under the `fences.repair` caps,+ each file bound to the bytes the plan read, and reports every path as+ `repaired`, `held`, `needs_human` or `skipped` with the reason code, the+ location-only receipt (mode, tier, classes, commit state) and the next+ step. `--no-llm` keeps the repairs to their free tiers; `--no-repair`+ refuses every repair-class hold instead, as releases before #6377 did.3. Run that sync. It re-screens the scheduled files, imports each one that nowpasses and holds again what still fails; the rest of the source is neverblocked. With `--retry-failed` a cursor an older release left blocked on a@@ -6894,9 +6911,13 @@ gbrain sync <next.argv...> # the sync unblock (or status)4. If `needs_human` is true, stop looping and page a person with the slug and`human_reason` from `status` (`next.user_message` is written for relay).-`unblock` is idempotent, writes no page, clears no hold and drops nothing:-refusing is the only way it leaves a file out, and each refusal names the file,-why, and its fix.+`unblock` is idempotent and drops nothing: the only pages it writes are the+hash-bound repairs it prints a receipt for, the only holds it clears are the+ones those repairs import, and refusing is the only way it leaves a file out.+Each refusal names the file, why, and its fix. A hold whose stored repair+state says a person decides (a manual fence reason, a gate rejection, a paid+wait on a setting only the user changes, a recommended page merge) is listed+`needs_human` and never retried until the file changes.## The triple@@ -6915,7 +6936,12 @@ Every hold and error has three fields, from one table- `needs_human`: a person has to choose or act before it clears;`human_reason` says what. A page held three times with the same code(`attempts`) is `needs_human` whatever its code says: it keeps moving under- the sync.+ the sync. A repair-class hold is `needs_human` when its stored repair state+ says so: a fence hold the lane marked `manual` (a manual-only reason, a gate+ rejection, a model answer the run does not retry) or `paid` (spend only the+ user raises), and a slug-conflict hold the lane decided a person must settle+ ([`merge_recommended`](write-refusals.md#merge_recommended),+ [`content_repair_needs_human`](write-refusals.md#content_repair_needs_human)).## Decision table@@ -6975,8 +7001,15 @@ it and kept going; the receipt lists the hold (`held`, `held_count`) and- `preparation_stalled`: the write owner, not the file, stalled;`gbrain sources writer status --source <id> --json` names the step.`unblock --apply` schedules the re-screen.-- The repair codes (`invalid_fence`, `invalid_frontmatter`, …) have their own- previews: [held files](write-refusals.md#held-files-and-content-refusals).+- `invalid_fence` and `frontmatter_slug_conflict`: the content-repair lane+ clears them. `unblock --apply` runs it on the held paths now; the maintenance+ run's `fence_repair` and `content_repair` phases run it by themselves;+ `gbrain repair content --source <id>` previews it. A hold the lane will not+ decide is `needs_human` with the paragraph in `human_reason`+ ([held files](repair.md#held-files)).+- The other repair codes (`invalid_frontmatter`, `rename_held`) stay+ consent-gated: unblock refuses them with the frontmatter repair preview to+ run ([held files](write-refusals.md#held-files-and-content-refusals)).- `revision_conflict`, `page_identity_changed`, `pinned_git_worktree_conflict`as a `last_error` come from a run on an older release; this release holdsthem. Rerun with `--retry-failed`: the stopped entry converts in place, thediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 4c868049fc..579176fffc 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,7 +13,7 @@ src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/commands/serve-http.ts 931 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)src/core/ai/gateway.ts 4430 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache countssrc/commands/sync.ts 514 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict)-src/core/cycle.ts 3283 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts)+src/core/cycle.ts 3293 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts)src/core/cycle/synthesize.ts 3227 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)src/core/cycle/extract-atoms.ts 1650 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms promptsrc/core/engine.ts 2737 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch memberdiff --git a/src/commands/repair-content.ts b/src/commands/repair-content.tsnew file mode 100644index 0000000000..a363edde52--- /dev/null+++ b/src/commands/repair-content.ts@@ -0,0 +1,53 @@+/**+ * `gbrain repair content [--source <id>] [--only <path>]... [--skip <path>]... [--no-llm] [--max-usd <n>] [--diff]+ * [--apply [--expect <h1>[,<h2>]]] [--json]`+ *+ * The content-repair lane (#6377) as one command: every kind in+ * `CONTENT_REPAIR_KINDS` (src/core/repair/content-lane.ts) over the same+ * source and file selection, each kind printing its own preview hash. `content`+ * is a lane, not a repair kind: it has no registry entry, no cursor of its own+ * and no help row under "Kinds"; it runs the registered kinds through the same+ * runner `gbrain repair <kind>` uses, so every refusal, receipt and cap is the+ * kind's own. Dry run unless `--apply`: the preview plans every kind before+ * anything is written and prints each kind's own hash; `--apply --expect+ * <h1>,<h2>` applies exactly the previewed sets, one hash per kind in lane+ * order; `--apply` alone applies each kind's current plan as `gbrain repair+ * <kind> --apply` does. `--max-usd` is the lane's allowance+ * for the run: what the first kind spends is gone for the next. Thin clients+ * refuse (cli.ts); the parse and the help text live in repair.ts so one flag+ * grammar serves every `gbrain repair` form.+ */+import type { BrainEngine } from '../core/engine.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { clearHealthMemo } from '../core/health-memo.ts';+import { resolveRepairScope } from '../core/repair/core.ts';+import { CONTENT_REPAIR_KINDS, contentLaneArgv, parseContentLaneExpect, runContentLane } from '../core/repair/content-lane.ts';+import { repairMaySpend, repairSpec } from '../core/repair/registry.ts';+import { renderRepairResult } from './repair.ts';++export interface RepairContentArgs { apply: boolean; json: boolean; diff: boolean; noLlm: boolean; noEmbed: boolean; source?: string; expect?: string; maxUsd?: number;+ only: string[]; skip: string[]; limit?: number }++export async function runRepairContentCommand(engine: BrainEngine, args: RepairContentArgs): Promise<void> {+ const kinds = [...CONTENT_REPAIR_KINDS];+ const preview = contentLaneArgv({ source: args.source, only: args.only, skip: args.skip, noLlm: args.noLlm, maxLlmUsd: args.maxUsd });+ const expect = args.expect === undefined ? undefined : parseContentLaneExpect(args.expect, kinds, [...preview, '--json']);+ const scope = await resolveRepairScope(engine, args.source);+ const lane = await runContentLane(engine, scope, { apply: args.apply, kinds, only: args.only, skip: args.skip, expect, noLlm: args.noLlm, maxLlmUsd: args.maxUsd,+ limit: args.limit, noEmbed: args.noEmbed, sourceFlag: args.source });+ if (args.apply) clearHealthMemo(engine);+ const paidKinds = lane.kinds.filter(kind => repairMaySpend(repairSpec(kind), args.noEmbed));+ if (args.json) {+ console.log(JSON.stringify({ lane: 'content', scope, mode: lane.mode, kinds: lane.kinds, results: lane.results.map(result => ({ ...result, paid: paidKinds.includes(result.kind) })),+ preview_hashes: lane.preview_hashes, cost: lane.cost, stopped: lane.stopped, paid_kinds: paidKinds, apply_command: lane.apply_command }, null, 2));+ } else {+ console.log(`Scope: brain ${scope.brain_id}; sources ${scope.source_ids.join(', ') || '(none)'}; lane content (${lane.kinds.join(', ')})`);+ for (const result of lane.results) console.log(renderRepairResult(result, { diff: args.diff }));+ const hashes = lane.kinds.map(kind => `${kind}=${lane.preview_hashes[kind] ?? '(none)'}`).join(', ');+ console.log(`Lane: paid model ${lane.mode === 'apply' ? `$${lane.cost.llm_usd.toFixed(4)} spent` : `~$${lane.cost.llm_usd.toFixed(4)}`}`+ + `${lane.cost.llm_allowance_remaining_usd === null ? '' : ` ($${lane.cost.llm_allowance_remaining_usd.toFixed(4)} left of this run's --max-usd)`}; preview hashes: ${hashes}`);+ for (const stop of lane.stopped) console.log(` ${stop.kind} STOPPED (${stop.reason}): ${stop.message}`);+ if (lane.mode === 'dry_run') console.log(` apply: ${lane.apply_command}`);+ }+ if (lane.stopped.length) setCliExitVerdict(1);+}diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 1495b96a7c..d4366344d6 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -11,7 +11,10 @@* preview-bound kinds accept `--expect <hash>` (their preview-bound apply);* only explicit-only kinds accept `--include-ambiguous`. `--max-usd <n>` is* accepted only for kinds that may call a paid chat model, and only lowers- * their cap for this run.+ * their cap for this run. `gbrain repair content` is the content-repair+ * lane (#6377, repair-content.ts): not a kind, but it takes the same+ * `--only`/`--skip`, `--no-llm`, `--max-usd`, `--expect` and `--apply` flags,+ * so it is parsed here and dispatched before the kind check.*/import type { BrainEngine } from '../core/engine.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';@@ -23,6 +26,20 @@ import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult }import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, LLM_REPAIR_REGISTRY, PREVIEW_BOUND_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMayEmbed, repairMaySpend,repairPreviewCommand, repairRunner, repairSpec } from '../core/repair/registry.ts';+import { CONTENT_REPAIR_KINDS } from '../core/repair/content-lane.ts';++/** The content-repair lane's command word (#6377): parsed like a kind, dispatched to repair-content.ts, never a RepairKind. */+export const CONTENT_LANE = 'content';+const REPAIR_CONTENT_HELP = ` gbrain repair content [--source <id>] [--only <path>]... [--skip <path>]... [--no-llm] [--max-usd <n>] [--diff]+ [--apply [--expect <hash>[,<hash>]]] [--json]`;+const REPAIR_CONTENT_SUMMARY = ` content The content-repair lane (#6377), not a kind: runs ${CONTENT_REPAIR_KINDS.join(', then ')} over the same+ --source/--only selection, so the holds managed sync records for a file's content (invalid_fence,+ frontmatter_slug_conflict) clear in one pass. The preview plans every kind before anything is written and+ prints each kind's own hash; --apply --expect <h1>[,<h2>] applies exactly those sets (one hash per kind,+ in that order); --apply alone applies each kind's current plan as gbrain repair <kind> --apply does.+ --max-usd is the lane's allowance for the run: what the first kind spends is gone for the next. The+ maintenance run's content_repair phase runs the same lane by itself; sync unblock --apply runs it for+ the paths it holds.`;function wrap(text: string, indent: number, width = 80): string {const lines: string[] = [];@@ -46,6 +63,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i[--apply --expect <preview-hash> --yes] [--json]gbrain repair fences [--source <id>] [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff][--no-llm] [--max-usd <n>] [--apply [--expect <preview-hash>]] [--limit <n>] [--json]+${REPAIR_CONTENT_HELP}Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.@@ -53,6 +71,9 @@ Kinds:${REPAIR_REGISTRY.map(spec => ` ${spec.kind.length < 13 ? spec.kind.padEnd(12) : `${spec.kind}\n${' '.repeat(14)}`} ${wrap(`${spec.explicit_only? `[explicit-only; preview: ${repairPreviewCommand(spec.kind)}] ` : ''}${spec.summary}`, 15)}`).join('\n')}+Lanes:+${REPAIR_CONTENT_SUMMARY}+Options:--apply Write the repair (no prompt). Without it, only preview.--source <id> Limit to one source (default: every active source).@@ -62,17 +83,17 @@ Options:Explicit-only kinds (${explicitKinds}) never run here; name each one.--expect <hash>Explicit-only and preview-bound kinds (${previewBoundKinds}): apply exactly the set the- preview printed under this hash.+ preview printed under this hash. content: one hash per lane kind, comma-separated, in lane order.--include-ambiguousExplicit-only kinds: widen the preview to ambiguous items (its hash covers them).--only <path>, --skip <path>- frontmatter, fences: select source-relative files (repeatable); the hash covers the selection.+ frontmatter, fences, content: select source-relative files (repeatable); the hash covers the selection.--slug <slug> fences: select a database page by slug (repeatable); the hash covers the selection.- --diff frontmatter, fences: print every per-file diff, not one sample per class or tier.- --no-llm Kinds that may call a paid model (${llmKinds}): use only the free tiers; model-tier- items stay held with llm_disabled.- --max-usd <n> Kinds that may call a paid model (${llmKinds}): spend at most n USD on the model in this- run. It only lowers the cap (the daily fences.repair cap still applies); never raises it.+ --diff frontmatter, fences, content: print every per-file diff, not one sample per class or tier.+ --no-llm Kinds that may call a paid model (${llmKinds}) and the content lane: use only the free tiers;+ model-tier items stay held with llm_disabled.+ --max-usd <n> Kinds that may call a paid model (${llmKinds}) and the content lane: spend at most n USD on the+ model in this run. It only lowers the cap (the daily fences.repair cap still applies); never raises it.--yes frontmatter, conversation-labels --apply: the user agreed to the previewed changes (destructiveconsent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).--json Machine-readable output with a stable shape (frontmatter: every per-file diff).@@ -81,14 +102,14 @@ Any other option is refused. --max-usd caps only a paid-model kind's model spendpaid embedding work, preview gbrain doctor --remediation-plan --json and, after the user agrees,run gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>.With no kind, previews every kind. Run it on the brain host.-Held files (two-pass frontmatter repair with real output): docs/guides/repair.md#held-files.+Held files (the content lane, then the two-pass frontmatter repair): docs/guides/repair.md#held-files.Malformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.`;const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm']);const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd']);/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {- '--only': ['frontmatter', 'fences'], '--skip': ['frontmatter', 'fences'], '--diff': ['frontmatter', 'fences'], '--yes': ['frontmatter', 'conversation-labels'],+ '--only': ['frontmatter', 'fences', CONTENT_LANE], '--skip': ['frontmatter', 'fences', CONTENT_LANE], '--diff': ['frontmatter', 'fences', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels'],'--slug': ['fences'],};const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md',@@ -161,7 +182,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {throw new OperationError('invalid_params', `${kindOnly} applies only to gbrain repair ${kinds.join(' or ')}.`,`Preview it by name: gbrain repair ${kinds[kinds.length - 1]}${parsed.source ? ` --source ${parsed.source}` : ''}`);}- const llmKind = LLM_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind);+ const llmKind = LLM_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind) || parsed.kind === CONTENT_LANE;if (maxUsdFlag) {if (!llmKind) throw maxUsdRefusal(maxUsdFlag, maxUsdText, parsed.kind);const cap = Number(maxUsdText);@@ -173,7 +194,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {}if (parsed.noLlm && !llmKind) throw new OperationError('invalid_params', `--no-llm applies only to a kind that may call a paid model (${llmKinds}).`,`Preview it by name: gbrain repair ${LLM_REPAIR_REGISTRY[0]?.kind ?? 'fences'}${parsed.source ? ` --source ${parsed.source}` : ''}`);- if (parsed.expect !== undefined && !PREVIEW_BOUND_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind)) {+ if (parsed.expect !== undefined && parsed.kind !== CONTENT_LANE && !PREVIEW_BOUND_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind)) {throw new OperationError('invalid_params', `--expect applies only to an explicit-only or preview-bound kind named on the command line (${previewBoundKinds}).`,`Preview one by name: ${repairPreviewCommand(PREVIEW_BOUND_REPAIR_REGISTRY[0]!.kind)}`);}@@ -184,7 +205,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {return parsed;}-function human(result: RepairResult, opts: { diff: boolean } = { diff: false }): string {+export function renderRepairResult(result: RepairResult, opts: { diff: boolean } = { diff: false }): string {const lines = [`${result.kind}: ${result.affected} item(s) ${result.mode === 'apply' ? 'pending before this run' : 'to repair'}`];for (const warning of result.warnings ?? []) lines.push(` WARNING: ${warning}`);if (result.sample.length) lines.push(` e.g. ${result.sample.join(', ')}`);@@ -223,8 +244,13 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proconst { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText } = parseRepairArgs(args);const limit = limitText === undefined ? undefined : Number(limitText);if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');+ if (kind === CONTENT_LANE) {+ if (all) throw invalid('Pass either content or --all, not both.', 'Drop --all to run the content lane, or drop content to run every automatic kind.', ['gbrain', 'repair', CONTENT_LANE, ...(source ? ['--source', source] : []), '--json']);+ const { runRepairContentCommand } = await import('./repair-content.ts');+ return runRepairContentCommand(engine, { apply, json, diff, noLlm, noEmbed, source, expect, maxUsd, only, skip, limit });+ }if (kind && !REPAIR_KINDS.includes(kind as RepairKind)) {- throw new OperationError('invalid_params', `Unknown repair kind '${kind}'.`, `Kinds: ${REPAIR_KINDS.join(', ')}.`);+ throw new OperationError('invalid_params', `Unknown repair kind '${kind}'.`, `Kinds: ${REPAIR_KINDS.join(', ')}; lanes: ${CONTENT_LANE}.`);}if (kind && all) throw invalid('Pass either a kind or --all, not both.', `Drop --all to repair only ${kind}, or drop ${kind} to run every automatic kind.`,['gbrain', 'repair', kind, ...(source ? ['--source', source] : []), '--json']);@@ -263,7 +289,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(explicitKindsNotRun.length ? { explicit_kinds: explicitKindsNotRun } : {}) }, null, 2));} else {console.log(`Scope: brain ${scope.brain_id}; sources ${scope.source_ids.join(', ') || '(none)'}`);- for (const result of results) console.log(human(result, { diff }));+ for (const result of results) console.log(renderRepairResult(result, { diff }));const embedKinds = results.filter(r => repairMayEmbed(repairSpec(r.kind), noEmbed)).map(r => r.kind);if (!apply && embedKinds.length) console.log(`Kinds that may queue paid embeddings: ${embedKinds.join(', ')} (pass --no-embed to skip; `+ 'page-write kinds are re-embedded by their publication either way; cap spend with gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash> from gbrain doctor --remediation-plan --json).');diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex 0e33a6aba2..9964b31b15 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -168,10 +168,12 @@ Subcommands:committed in the last 10 minutes, each hold and thelast error with class / safe_actions / needs_human,and the next action (for an operator agent's loop).- gbrain sync unblock --source <id> [--apply] [--json]+ gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]Performs the safe action for every hold (re-screens aheld file whose edit is now committed, retries a- stalled preparation) and refuses the rest by name.+ stalled preparation, repairs a content hold through+ the content-repair lane with a hash-bound apply and+ a receipt per file) and refuses the rest by name.Runbook: docs/guides/sync-unblock-runbook.mdSee also:diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex 539bf9d68c..84f737639d 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -3,15 +3,22 @@* for a managed catch-up (core in `src/core/persistence/sync-status.ts`,* decision table in `sync-fault-class.ts`, prose in* `docs/guides/sync-unblock-runbook.md`). Both speak the agent operator- * protocol: `--json` prints one envelope with `next` rendered as a fix.+ * protocol: `--json` prints one envelope with `next` rendered as a fix. Since+ * #6377 `unblock --apply` also runs the content-repair lane on the holds it+ * clears (`--no-llm`, `--no-repair`), and each repaired path prints its+ * location-only receipt.*/import type { BrainEngine } from '../../core/engine.ts';import { cliRenderContext, renderAction } from '../../core/agent-output.ts';import { opError } from '../../core/ops/contract.ts';import { readSyncStatus, unblockSync } from '../../core/persistence/sync-status.ts';import { HOLD_ATTEMPTS_NEEDS_HUMAN } from '../../core/persistence/sync-fault-class.ts';+import { CONTENT_REPAIR_HOLD_KINDS } from '../../core/repair/content-lane.ts';import { resolveSourceIdEngineFree } from '../../core/source-resolver.ts';+/** The hold codes the content-repair lane clears today, for the help text. */+const CONTENT_HOLD_CODES = Object.entries(CONTENT_REPAIR_HOLD_KINDS).filter(([, kind]) => kind).map(([code]) => code).join(', ');+export function printSyncStatusHelp(): void {console.log(`Usage: gbrain sync status --source <id> [--json]@@ -31,21 +38,33 @@ Decision table: docs/guides/sync-unblock-runbook.md}export function printSyncUnblockHelp(): void {- console.log(`Usage: gbrain sync unblock --source <id> [--apply] [--json]+ console.log(`Usage: gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]Performs the safe action for every held file of a managed source and refuses-the rest by name. Without --apply it previews. Idempotent; it never writes a-page, never clears a hold and never drops content: refusing is the only way-it leaves a file out, and each refusal names the file, why, and its fix.+the rest by name. Without --apply it previews. Idempotent; it writes only+hash-bound repairs (each with its receipt), never drops content and never+clears a hold except by repairing its file: refusing is the only way it+leaves a file out, and each refusal names the file, why, and its fix.worktree_dirty re-screened when its working-tree bytes are committedat HEAD now (still dirty: refused still_dirty)preparation_stalled re-screened (the writer, not the file, stalled)concurrent_write refused: a person reconciles the two versions- repair-class holds refused with the repair preview to run+ ${CONTENT_HOLD_CODES.padEnd(22)}repaired by the content-repair lane (gbrain repair content,+ each file bound to the bytes its plan read, under the+ fences.repair caps), then re-screened; per+ path: repaired | held | needs_human | skipped with the reason,+ the receipt and the next step. A hold whose stored state waits+ on a person, the user's spend decision or the owner host is+ listed, not retried.+ other repair holds refused with the repair preview to runheld ${HOLD_ATTEMPTS_NEEDS_HUMAN} times refused: the page keeps moving; needs a person+ --no-llm repairs keep to their free tiers (model-tier files stay held)+ --no-repair refuse every repair-class hold instead (the pre-#6377 behaviour)+Then run the sync \`next\` names (the cursor's own options).+Runbook: docs/guides/sync-unblock-runbook.md`);}@@ -78,12 +97,18 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promisexport async function runSyncUnblock(engine: BrainEngine, args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) return printSyncUnblockHelp();const sourceId = sourceOf(args);- const outcome = await unblockSync(engine, sourceId, { apply: args.includes('--apply') });+ const outcome = await unblockSync(engine, sourceId, { apply: args.includes('--apply'), noLlm: args.includes('--no-llm'), noRepair: args.includes('--no-repair') });const ctx = cliRenderContext();- const rendered = { ...outcome, refused: outcome.refused.map(entry => ({ ...entry, fix: renderAction(entry.fix, ctx) })), next: outcome.next ? renderAction(outcome.next, ctx) : null };+ const rendered = { ...outcome,+ applied: outcome.applied.map(entry => entry.action === 'repair' ? { ...entry, repair: { ...entry.repair, next: renderAction(entry.repair.next, ctx) } } : entry),+ refused: outcome.refused.map(entry => ({ ...entry, fix: renderAction(entry.fix, ctx) })), next: outcome.next ? renderAction(outcome.next, ctx) : null };if (args.includes('--json')) { console.log(JSON.stringify(rendered, null, 2)); return; }- console.log(`Source ${sourceId}: ${outcome.applied.length} held file(s) ${outcome.apply ? 'scheduled for a re-screen' : 'would be scheduled for a re-screen (preview; add --apply)'}, ${outcome.refused.length} refused.`);- for (const entry of outcome.applied) console.log(` ${entry.path}: ${entry.code} → ${entry.action}: ${entry.detail}`);+ const repaired = outcome.applied.filter(entry => entry.action === 'repair').length;+ console.log(`Source ${sourceId}: ${outcome.applied.length} held file(s) ${outcome.apply ? `${repaired ? 'repaired or ' : ''}scheduled for a re-screen` : `would be ${repaired ? 'repaired or ' : ''}scheduled for a re-screen (preview; add --apply)`}, ${outcome.refused.length} refused.`);+ for (const entry of outcome.applied) {+ console.log(` ${entry.path}: ${entry.code} → ${entry.action}: ${entry.detail}`);+ if (entry.action === 'repair' && entry.repair.receipt) console.log(` receipt: ${Object.entries(entry.repair.receipt).map(([k, v]) => `${k}=${v}`).join(', ')}`);+ }for (const entry of outcome.refused) console.log(` ${entry.path}: ${entry.code} refused (${entry.reason})${entry.needs_human ? ' NEEDS HUMAN' : ''}`);if (rendered.next) console.log(` Next: ${rendered.next.command ?? rendered.next.argv?.join(' ')}\n Why: ${rendered.next.why}`);else console.log(' Next: nothing held.');diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 12d33f36c2..d09f695e87 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -350,6 +350,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Budgeted delivery PR 1. `since` equals the branch's VERSION; the integrator sets it to the merge-slot stamp by hand (release:restamp does not rewrite this table).{ since: '0.60.124.0', text: 'A token budget passed under `auto` evidence delivery (`token_budget` on query, search and assemble_evidence, `budget_tokens` on recall with `return_unit: "auto"`) is now a hard cap on the delivered titles and evidence: the best hit comes first, and conversations or notes that do not fit are listed in `delivery.dropped_reasons` instead of being appended as extra chunks. A budget below 32 tokens is refused with `invalid_params`. Calls without a budget, and a bare query `token_budget` (legacy chunk budgeting), are unchanged. `gbrain config set search.auto_packing off` restores the uncapped behavior.' },{ since: '0.60.126.0', text: '`context_pack` cards now list the newest pages that mention each entity and are dated after the entity\'s own page (up to 8 per card, 2,000 characters per card and 6,000 per pack, each with its date, slug, title and preview), so a later mail or note that corrects the page reaches the agent on its first call. A remote caller never sees a private page or another source there, and the section packs last under `budget_tokens`. `gbrain config set mentions.newer_on_cards false` turns it off.' },+ // #6377 (GBRA-72). `since` is a placeholder equal to the branch's VERSION so a fresh install's baseline covers it; the integrator sets it+ // to the merge-slot stamp (master plus one PATCH) by hand, because release:restamp rewrites VERSION, CHANGELOG and TODOS, never this table.+ { since: '0.60.130.0', text: 'The maintenance run now repairs the content holds managed sync records, by itself and without consent: two facts or takes fences of one kind in one section are merged into one (exact duplicate rows dropped, colliding numbers renumbered, the validator proving every original row survived), an unclosed fence followed by text on a private page is closed after its last row, and a stray frontmatter `slug:` that names no page (or a page of a different type with no title in common) is removed; each repair is one committed file write carrying the trailer `gbrain-repair: <hold_code> <tier> <confidence>` and a receipt, so `git revert` of that commit undoes it. The `fence_repair` phase runs the fences, the new `content_repair` phase right after it runs the rest of the lane (`gbrain repair content --source <id>` previews both); `gbrain config set fences.repair.enabled false` pauses all of it.' },+ { since: '0.60.130.0', text: 'The repair model (`models.fence_repair`, or `models.content_repair` for slug conflicts) now also classifies the cases the deterministic rules mark ambiguous, under the same `fences.repair.max_usd_per_page` ($0.30) and `fences.repair.max_usd_per_day` ($1.00) caps and one shared daily ledger: whether the lines after an unclosed fence on a world-visible page are prose or table rows, and whether two pages a `slug:` line ties together are the same thing. The model chooses among coded answers and never writes text: a world-page close that would expose hidden lines waits for your hash-bound approval (`tail_exposure_approval`), a page merge is recommended, never executed (`merge_recommended` names the canonical page), and an undecided case is `needs_human`. `gbrain config set fences.repair.llm false` turns the model tier off for the whole lane; `--no-llm` keeps one run to the free tiers.' },+ { since: '0.60.130.0', text: '`gbrain sync unblock --source <id> --apply` now writes: for every held file the content-repair lane clears (`invalid_fence`, and `frontmatter_slug_conflict` once its kind ships) it runs the lane on exactly those paths as one bounded hash-bound apply under the `fences.repair` caps, prints a receipt per file and schedules the re-screen, and reports each path as `repaired`, `held`, `needs_human` or `skipped` with the reason and its next step; a hold whose stored state waits on a person, your spend decision or the owner host is listed, never retried. Before this release unblock refused every repair-class hold. `--no-llm` keeps the repairs to the free tiers; `--no-repair` restores the refuse-only behaviour. `gbrain sync status` now reports a fence hold the lane marked manual or paid, and a recommended merge, as `needs_human` with the paragraph in `human_reason`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 86093eca5a..ce52ea93f0 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -72,10 +72,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--auto', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--show-toplevel', '--skip-embed-check', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],+ 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--auto', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--show-toplevel', '--skip-embed-check', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],'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', '--admin-intent', '--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', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--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'],+ 'jobs': ['--abbrev-ref', '--access', '--add', '--admin-intent', '--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', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--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-llm', '--no-pull', '--no-renames', '--no-repair', '--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', '--grammar-diagnostics', '--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'],@@ -103,7 +103,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],+ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--scopes', '--source', '--timeout'],'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--only', '--probe', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],@@ -122,10 +122,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait', '--wait-drain', '--warn-only', '--yes'],- 'status': ['--abbrev-ref', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],+ 'status': ['--abbrev-ref', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex a4d4012d22..0ce094256f 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -68,6 +68,7 @@ export { anyAbortSignal } from './abort-signals.ts';export type CyclePhase =| 'lint' | 'backlinks' | 'sync' | 'synthesize' | 'extract' | 'extract_facts'| 'fence_repair' // #6188: repairs held and stored malformed facts/takes fences (global maintenance lane)+ | 'content_repair' // #6377: the rest of the content-repair lane (slug conflicts and later kinds), right after fence_repair| 'resolve_symbol_edges'| 'patterns' | 'recompute_emotional_weight' | 'consolidate'// v0.36.1.0 Hindsight calibration wave:@@ -125,6 +126,8 @@ export const ALL_PHASES: CyclePhase[] = ['sync',// #6188: right after sync, so a fence the sync just held is repaired before extract and extract_facts read the page.'fence_repair',+ // #6377: the other content-repair kinds (src/core/repair/content-lane.ts) right after it, same reason.+ 'content_repair','synthesize','extract',// v0.32.2 — reconcile DB facts index from the `## Facts` fence on@@ -324,6 +327,7 @@ const NEEDS_LOCK_PHASES: ReadonlySet<CyclePhase> = new Set(['backlinks','sync','fence_repair', // #6188: writes repaired fences through coordinated writes+ 'content_repair', // #6377: writes content repairs through the same coordinated file-repair path'synthesize','extract',// v0.32.2 — wipes + re-inserts facts per affected page.@@ -1856,6 +1860,18 @@ async function runPhaseOrphans(engine: BrainEngine, sourceId?: string): Promise<// ─── Main ──────────────────────────────────────────────────────────++/**+ * #6188 / #6377: the two repair-lane phases that run right after `sync`, in this order. `runCycle` dispatches them+ * through one loop; each phase module owns its gate, budget and report.+ */+const REPAIR_LANE_PHASES = ['fence_repair', 'content_repair'] as const;++async function runRepairLanePhase(phase: typeof REPAIR_LANE_PHASES[number], engine: BrainEngine | null,+ opts: { dryRun: boolean; signal?: AbortSignal; deadlineAtMs: number | null }): Promise<PhaseResult> {+ return phase === 'fence_repair' ? (await import('./cycle/fence-repair.ts')).runFenceRepairPhase(engine, opts) : (await import('./cycle/content-repair.ts')).runContentRepairPhase(engine, opts);+}+/*** Run the brain maintenance cycle.*@@ -2239,9 +2255,9 @@ export async function runCycle(await safeYield(opts.yieldBetweenPhases);}- if (phases.includes('fence_repair')) { // #6188: one bounded run of the `fences` repair kind (src/core/cycle/fence-repair.ts)- checkAborted(cycleSignal);- const { result, duration_ms } = await timePhase(async () => (await import('./cycle/fence-repair.ts')).runFenceRepairPhase(engine, { dryRun, signal: cycleSignal, deadlineAtMs: opts.deadlineAtMs ?? null }), 'fence_repair');+ for (const phase of REPAIR_LANE_PHASES) { // #6188 fence_repair, then #6377 content_repair: one bounded run each (src/core/cycle/{fence,content}-repair.ts)+ if (!phases.includes(phase)) continue; checkAborted(cycleSignal);+ const { result, duration_ms } = await timePhase(() => runRepairLanePhase(phase, engine, { dryRun, signal: cycleSignal, deadlineAtMs: opts.deadlineAtMs ?? null }), phase);phaseResults.push({ ...result, duration_ms }); await safeYield(opts.yieldBetweenPhases);}diff --git a/src/core/cycle/content-repair.ts b/src/core/cycle/content-repair.tsnew file mode 100644index 0000000000..7d25cefcc0--- /dev/null+++ b/src/core/cycle/content-repair.ts@@ -0,0 +1,139 @@+/**+ * `content_repair` cycle phase (#6377): one bounded pass of the content-repair+ * lane (src/core/repair/content-lane.ts) in the global maintenance lane,+ * right after `fence_repair`, so the content holds managed sync records+ * (`frontmatter_slug_conflict` today's candidate; `invalid_fence` is+ * `fence_repair`'s) clear within one maintenance cycle with no operator. The+ * phase runs every kind in `CONTENT_REPAIR_KINDS` except `fences`, which+ * `fence_repair` just ran, through the same shared trusted repair runner, so+ * each kind keeps its own census, owner checks, caps, ledger and gates, and a+ * new lane kind is picked up here with no change. With `CONTENT_REPAIR_KINDS`+ * holding only `fences` the phase runs nothing and says so (`no_kinds`).+ *+ * Gated on `fences.repair.enabled` (one switch for the whole lane, D3), with a+ * deadline of min(120 s, a third of the maintenance job's remaining time); an+ * apply on a real run, a preview on a dry run. The report is counts by kind,+ * outcome and reason, the lane's model spend and the oldest unresolved hold's+ * age. It never fails the cycle: a stop other than the time budget, or an+ * internal error, reports `warn` with the next step. Output is counts and+ * codes only, never a path, claim or cell value.+ */+import type { BrainEngine } from '../engine.ts';+import type { PhaseResult } from '../cycle.ts';+import type { Action } from '../agent-output.ts';+import { resolveRepairScope, type RepairKind, type RepairResult } from '../repair/core.ts';+import type { RepairKindSpec } from '../repair/registry.ts';+import { CONTENT_REPAIR_KINDS, contentLaneArgv, runContentLane, type ContentLaneResult } from '../repair/content-lane.ts';+import { FENCE_REPAIR_ENABLED_KEY, fenceRepairEnabled } from '../fence-repair/config.ts';+import { isUncontainedPhaseError } from './phase-containment.ts';++/** The longest one phase run spends on the lane; inside a maintenance job it is also at most a third of the job's remaining time. */+export const CONTENT_REPAIR_PHASE_BUDGET_MS = 120_000;++export interface ContentRepairPhaseOpts {+ dryRun: boolean;+ signal?: AbortSignal;+ /** The enclosing maintenance job's absolute deadline (epoch ms); null or unset for a direct `gbrain dream`. */+ deadlineAtMs?: number | null;+ /** The lane kinds to run (default: `CONTENT_REPAIR_KINDS` without `fences`); tests name a stub kind here. */+ kinds?: readonly RepairKind[];+ /** Replaces the registered repair kinds, as `repairRunner` takes it (tests pass stub specs). */+ registry?: readonly RepairKindSpec[];+ now?: () => number;+}++/** The kinds the phase runs by default: the lane minus the kind `fence_repair` already ran. */+export function contentRepairPhaseKinds(): RepairKind[] {+ return CONTENT_REPAIR_KINDS.filter(kind => kind !== 'fences');+}++const previewFix = (why: string): Action => ({ argv: contentLaneArgv({}), consent: [], actor: 'agent', why, requires_exclusive: false, docs: 'docs/guides/repair.md#held-files' });++/** Counts by reason over a kind's per-item outcomes (its `remaining` when the kind reports one). */+function heldByReason(result: RepairResult): Record<string, number> {+ if (result.remaining) return result.remaining;+ const counts: Record<string, number> = {};+ for (const item of result.outcome_items ?? []) if (item.outcome !== 'repaired' && item.reason) counts[item.reason] = (counts[item.reason] ?? 0) + 1;+ return counts;+}++export async function runContentRepairPhase(engine: BrainEngine | null, opts: ContentRepairPhaseOpts): Promise<PhaseResult> {+ const base = { phase: 'content_repair' as const, duration_ms: 0 };+ if (!engine) return { ...base, status: 'skipped', summary: 'no database connected', details: { reason: 'no_database' } };+ const kinds = [...(opts.kinds ?? contentRepairPhaseKinds())];+ const preview = contentLaneArgv({}).join(' ');+ if (!kinds.length) {+ return { ...base, status: 'skipped', details: { reason: 'no_kinds', kinds },+ summary: 'no content-repair kind beyond fence_repair is registered in this release, so the phase ran nothing; fence holds were handled by fence_repair.' };+ }+ if (!(await fenceRepairEnabled(engine))) {+ return { ...base, status: 'skipped', details: { reason: 'disabled', kinds },+ summary: `content repair is paused (${FENCE_REPAIR_ENABLED_KEY} false), so nothing was repaired. Turn it back on with `+ + `\`gbrain config set ${FENCE_REPAIR_ENABLED_KEY} true\`, or preview and apply by hand with \`${preview}\`.` };+ }+ const now = opts.now ?? Date.now;+ const start = now();+ const timeBudgetMs = opts.deadlineAtMs == null ? CONTENT_REPAIR_PHASE_BUDGET_MS+ : Math.min(CONTENT_REPAIR_PHASE_BUDGET_MS, Math.floor((opts.deadlineAtMs - start) / 3));+ if (timeBudgetMs <= 0) {+ return { ...base, status: 'skipped', summary: 'no maintenance-job time left for content repair; the next run continues', details: { reason: 'deadline', kinds } };+ }+ let lane: ContentLaneResult;+ try {+ lane = await runContentLane(engine, await resolveRepairScope(engine), { apply: !opts.dryRun, kinds, deadline: start + timeBudgetMs,+ logger: { info() {}, warn: console.warn, error: console.error }, ...(opts.registry ? { registry: opts.registry } : {}) });+ } catch (error) {+ if (isUncontainedPhaseError(error, opts.signal)) throw error;+ const rawCode = (error as { code?: unknown } | null)?.code;+ const code = typeof rawCode === 'string' ? rawCode : 'internal';+ return { ...base, status: 'warn', details: { reason: 'error', code, kinds, time_budget_ms: timeBudgetMs,+ fix: previewFix('The content repair stopped on an error; the preview shows each kind\'s plan and the error on the brain host.') },+ summary: `content repair stopped on an error (${code}) and the next maintenance run retries. Run \`${preview}\` on the brain host `+ + 'to see the plan and the error; ask the user if it keeps failing.' };+ }++ const byKind = Object.fromEntries(lane.results.map(result => {+ const held = heldByReason(result);+ const v = result.verification as { oldest_hold_at?: string | null } | undefined;+ return [result.kind, { mode: result.mode, candidates: result.affected, repaired: result.repaired ?? result.applied, outcomes: result.outcomes ?? {}, held_by_reason: held,+ llm_usd: result.cost.llm_usd ?? null, complete: result.complete, stopped_reason: result.stopped?.reason ?? null, oldest_hold_at: v?.oldest_hold_at ?? null }];+ })) as Record<string, { mode: string; candidates: number; repaired: number; outcomes: Record<string, number>; held_by_reason: Record<string, number>; llm_usd: number | null; complete: boolean;+ stopped_reason: string | null; oldest_hold_at: string | null }>;+ const kindsRun = Object.values(byKind);+ const candidates = kindsRun.reduce((sum, k) => sum + k.candidates, 0);+ const repaired = kindsRun.reduce((sum, k) => sum + k.repaired, 0);+ const heldTotals: Record<string, number> = {};+ for (const k of kindsRun) for (const [reason, n] of Object.entries(k.held_by_reason)) heldTotals[reason] = (heldTotals[reason] ?? 0) + n;+ const held = Object.values(heldTotals).reduce((sum, n) => sum + n, 0);+ const needsHuman = (heldTotals.needs_human ?? 0) + (heldTotals.merge_recommended ?? 0) + (heldTotals.content_repair_needs_human ?? 0);+ const oldest = kindsRun.map(k => k.oldest_hold_at).filter((at): at is string => !!at).sort()[0] ?? null;+ const oldestHoldAgeHours = oldest ? Math.max(0, Math.round((now() - Date.parse(oldest)) / 3_600_000)) : null;+ const hardStop = lane.stopped.find(stop => stop.reason !== 'time_budget');+ const timeStop = lane.stopped.find(stop => stop.reason === 'time_budget');+ const usd = `$${lane.cost.llm_usd.toFixed(4)}`;+ const parts = [+ lane.mode === 'dry_run' ? `dry run: ${candidates} content candidate(s) planned across ${lane.kinds.join(', ')}, nothing written`+ : candidates === 0 && held === 0 ? `no content holds to repair (${lane.kinds.join(', ')})`+ : `repaired ${repaired} of ${candidates} content candidate(s) across ${lane.kinds.join(', ')} (${usd} on the model)`,+ held ? `${held} still held (${Object.entries(heldTotals).filter(([, n]) => n).map(([reason, n]) => `${reason} ${n}`).join(', ')})` : '',+ oldestHoldAgeHours !== null ? `the oldest unresolved hold is ${oldestHoldAgeHours} h old` : '',+ ].filter(Boolean).join('; ');+ const notes = [+ timeStop ? `Stopped at the phase time budget (${Math.round(timeBudgetMs / 1000)} s) in ${timeStop.kind}; the next maintenance run resumes.` : '',+ hardStop ? `Stopped (${hardStop.kind}: ${hardStop.reason}): ${hardStop.message}` : '',+ needsHuman ? `${needsHuman} wait for a person: gbrain sync status --source <id> --json names each with its paragraph.` : '',+ ].filter(Boolean);+ const fix = hardStop ? hardStop.fix ?? previewFix('A lane kind stopped; the preview shows each kind\'s plan on the brain host.')+ : needsHuman ? previewFix('Some holds wait for a person; the preview names each with its exact next step.') : undefined;+ return {+ ...base,+ status: hardStop ? 'warn' : 'ok',+ summary: [`${parts}.`, ...notes].join(' '),+ details: {+ mode: lane.mode, kinds: lane.kinds, candidates, repaired, held_by_reason: heldTotals, by_kind: byKind,+ llm_usd: lane.cost.llm_usd, oldest_hold_at: oldest, oldest_hold_age_hours: oldestHoldAgeHours,+ complete: lane.results.every(result => result.complete), time_budget_ms: timeBudgetMs, stopped_reason: hardStop?.reason ?? timeStop?.reason ?? null,+ ...(lane.stopped.length ? { stopped: lane.stopped } : {}), ...(fix ? { fix } : {}),+ },+ };+}diff --git a/src/core/cycle/phase-scope.ts b/src/core/cycle/phase-scope.tsindex 3fa1ed231c..0037fac778 100644--- a/src/core/cycle/phase-scope.ts+++ b/src/core/cycle/phase-scope.ts@@ -17,6 +17,7 @@ export const PHASE_SCOPE: Record<CyclePhase, PhaseScope> = {backlinks: 'source',sync: 'source',fence_repair: 'global',+ content_repair: 'global',synthesize: 'mixed',extract: 'source',extract_facts: 'source',diff --git a/src/core/cycle/phase-table.ts b/src/core/cycle/phase-table.tsindex a599ec305b..51349eaa1a 100644--- a/src/core/cycle/phase-table.ts+++ b/src/core/cycle/phase-table.ts@@ -24,6 +24,7 @@ export const MANAGED_PHASE_TABLE: Readonly<Record<CyclePhase, ManagedPhaseEntry>backlinks: { class: 'no_coordinated_write', reason: 'Audit-only: counts missing back-links and never writes files.' },sync: { class: 'writes', reason: 'Managed sync admits each changed file through the coordinator.' },fence_repair: { class: 'writes', reason: 'Fence repairs publish through managed_file_repair (managed sources), a revision-bound put_page (database-only pages) or the legacy confined write, one coordinated write per repaired file or page.' },+ content_repair: { class: 'writes', reason: 'The other content-repair lane kinds publish through the same coordinated file-repair path as fence_repair, one write per repaired file; with no kind beyond fences registered the phase writes nothing.' },synthesize: { class: 'writes', reason: 'Dream synthesis publishes pages through the maintenance coordinator.' },extract: { class: 'writes', reason: 'Derived links and unrecorded timeline rows commit inside revision-bound coordinated transactions.' },extract_facts: { class: 'writes', reason: 'Fence facts are re-projected through coordinated maintenance writes.' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 23f91fd3bc..ef88755dd4 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -367,6 +367,7 @@ export const CODES = {reasons: ['candidate_in_flight', 'busy_set_unreadable'],suggestion: 'Nothing to do for the repair: the next run reads the file again. To finish the sync now: gbrain sync --source <id> --no-pull.' },sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull --retry-failed.' },+ tail_exposure_approval: { class: 'caller', summary: "A fence on a world-visible page has no end marker and prose follows its table; closing it after the last row is safe for the table but makes those lines visible to remote readers, so the content-repair lane previews the close and waits for a hash-bound approval instead of applying it unattended.", why: "Everything after an unpaired begin marker is hidden by the privacy boundary. The repair model read the tail as prose (not rows), so the only judgment left is whether those exact lines may become visible, and that is the user's: the preview prints them and the hash binds them. On a private page nothing new is disclosed and the lane closes the fence by itself.", actor: 'user', docs: 'docs/guides/write-refusals.md#tail_exposure_approval', suggestion: 'Show the user the preview\'s exposed lines (gbrain repair content --source <id> --only <path>, read-only), then run the printed gbrain repair content --source <id> --only <path> --apply --expect <hash> only after they agree; a changed tail invalidates the hash. By hand: add the end marker directly after the last table row and move the trailing text where it belongs, commit, then gbrain sync --source <id> --no-pull.' },take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },timeline_comment_markup: { class: 'caller', summary: "A stored timeline row carries HTML comment markup, so gbrain keeps it database-side and never writes it back into the page; clean it with gbrain repair timeline-comments.", docs: 'docs/guides/repair.md#timeline-comments' },@@ -378,6 +379,7 @@ export const CODES = {two_consumers_on_host: { class: 'host_only', summary: "Two resident gbrain processes on this host (`serve`, `sync`, `jobs`, `autopilot` or `mcp`) have each run a full persistence consumer for longer than 30 s, so both claim writes on the same roots.", why: "One full consumer per host is a preference, not a fenced role: a `serve` always starts full, every other resident kind defers to the first live full consumer it finds in `persistence_consumers`, and two processes that start within one renewal of each other, or a CLI that took its consumer before the `serve` started, both stay full until one exits. Every observed `preparing` wedge had two consumers alive on the host. Short-lived commands (`put`, `import`, `dream`, `cli`) and rows younger than 30 s are listed, never warned.", docs: 'docs/guides/troubleshooting.md#two-consumers-on-host', suggestion: 'Let the shorter-lived of the two finish (a sync CLI run ends on its own) or restart it so it defers; with persistence.single_consumer off, this is the configured behavior.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists every consumer alive on this host (pid, kind, mode, started_at, pool) so you can see which one to let finish.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'two_consumers_on_host', '--json'] } } },trusted_local_only: { class: 'host_only', summary: 'The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it.', legacy_error: 'permission_denied', suggestion: 'Ask the user to run the named gbrain command on the brain host.' },unavailable: { class: 'unavailable', summary: "A required dependency or capability cannot serve this request." },+ unclosed_ambiguous_tail: { class: 'caller', summary: "A fence has no end marker and text follows its table, and the repair model read that tail as table rows written without pipes or could not tell, so gbrain will not choose where the fence ends; nothing was written.", why: "Closing after the wrong row would hide rows behind the privacy boundary or expose text; a deterministic rule cannot place the end marker and the model declined to, so a person decides. The attempt memo keeps the same bytes from costing a second model call.", actor: 'user', docs: 'docs/guides/write-refusals.md#unclosed_ambiguous_tail', suggestion: 'Read the page (gbrain get --source <id> -- <slug>), add the end marker after the last real row of the named fence (moving any rows the tail holds into the table), commit, then gbrain sync --source <id> --no-pull. The preview (gbrain repair fences --source <id> --only <path>, read-only) names the fence, section and last row.', fix: { argv: ['gbrain', 'repair', 'fences', '--source', '{source_id}'], consent: [], actor: 'agent', why: 'Read-only: names each held fence with its section and last parsed row so the person knows where the end marker belongs; writes nothing and calls no model.', requires_exclusive: false, verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },unexpected_file_bytes: { class: 'server', summary: "A canonical skill file mode changed outside publication." },unexpected_staging_bytes: { class: 'server', summary: "Recovery staging has unexpected bytes or identity; the root and its recovery capacity remain reserved." },unknown: { class: 'server', summary: "An unclassified failure (legacy StructuredError fallback code)." },diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsindex 1bbfa82311..f508b14f2b 100644--- a/src/core/persistence/held-reads.ts+++ b/src/core/persistence/held-reads.ts@@ -21,8 +21,8 @@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, 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';+import { GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, contentRepairArgv, fenceAutoRepairFor, gitHoldDocs, gitHoldFix, holdRepairSteps, type GitHoldCode, type GitHoldReason, type GitHoldRecord, type HoldRepairRoute } from './sync-holds.ts';+import { fenceHoldLocation, fenceHoldRelay, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';type Exec = Pick<BrainEngine, 'executeRaw'>;@@ -128,14 +128,14 @@ export function coverageRoute(source: HeldCoverage): HoldRepairRoute {*/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 => `'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 fences = sources.filter(source => source.route && (source.route.fences > 0 || (source.route.slug_conflicts ?? 0) > 0)).map(source => `'${contentRepairArgv(source.source_id).join(' ')}'`);const concurrent = sources.filter(source => source.route?.concurrent).map(source => source.source_id);const stalled = sources.filter(source => source.route?.stalled).map(source => source.source_id);const dirty = sources.filter(source => source.route?.dirty).map(source => source.source_id);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 could not import. The brain host's maintenance run repairs most of these by itself when it is running; `+ ...(fences.length ? [`Some held files have a facts or takes table, or a slug line naming another page, that 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).`] : []),...(concurrent.length ? [`Some notes changed in their files while an agent saved a different version to the brain, so both were kept: on the brain host run ${concurrent.map(id => `'gbrain sources status ${id}'`).join(', ')} and reconcile each named note with 'gbrain sources reconcile <source> <slug> --preview'.`] : []),...(stalled.length ? [`Some files are held because the brain's write owner could not finish preparing them (the files themselves are fine): on the brain host run ${stalled.map(id => `'gbrain sources writer status --source ${id} --json'`).join(', ')} to see what the owner was stuck on, fix that or upgrade gbrain, then 'gbrain sources retry-held <source>' and the same sync.`] : []),@@ -148,7 +148,8 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; rout/** The route of one hold record. */export function recordRoute(record: Pick<GitHoldRecord, 'code'>): HoldRepairRoute {return record.code === 'invalid_fence' ? { fences: 1, others: 0 } : record.code === 'concurrent_write' ? { fences: 0, others: 0, concurrent: 1 }- : record.code === 'preparation_stalled' ? { fences: 0, others: 0, stalled: 1 } : record.code === 'worktree_dirty' ? { fences: 0, others: 0, dirty: 1 } : { fences: 0, others: 1 };+ : record.code === 'preparation_stalled' ? { fences: 0, others: 0, stalled: 1 } : record.code === 'worktree_dirty' ? { fences: 0, others: 0, dirty: 1 }+ : record.code === 'frontmatter_slug_conflict' ? { fences: 0, others: 0, slug_conflicts: 1 } : { fences: 0, others: 1 };}/**diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex e0d2c2b7ea..0a3c408387 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -21,9 +21,10 @@* frontmatter value. #6188 `invalid_fence` holds carry the fence, section,* 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 (`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).+ * the right repair (`holdRepairSteps`, D6): the content-repair lane+ * (`gbrain repair content`, #6377) for fence and slug-conflict 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';@@ -32,7 +33,7 @@ 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 } from '../fence-repair/refusal.ts';-import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';+import { fenceHoldFix, fenceHoldLocation, 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';import { VERSION } from '../../version.ts';@@ -348,13 +349,20 @@ export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, re}/**- * D6: which repairs a source's holds need. Fence holds route to the fence- * repair preview, #6194 concurrent-write holds to the reconcile preview and a- * re-screen, #6278 preparation-stalled holds to writer status and a re-screen- * (never a file repair), every other hold to the frontmatter repair preview;- * a source with several kinds names each.+ * D6: which repairs a source's holds need. Fence and slug-conflict holds route+ * to the content-repair lane's preview (#6377), #6194 concurrent-write holds+ * to the reconcile preview and a re-screen, #6278 preparation-stalled holds to+ * writer status and a re-screen (never a file repair), every other hold to the+ * frontmatter repair preview; a source with several kinds names each.*/-export interface HoldRepairRoute { fences: number; others: number; concurrent?: number; stalled?: number; dirty?: number }+export interface HoldRepairRoute { fences: number; others: number; concurrent?: number; stalled?: number; dirty?: number;+ /** #6377 `frontmatter_slug_conflict` holds, counted apart from `others` by callers that read codes (summary counts leave them in `others`). */+ slug_conflicts?: number }++/** `gbrain repair content --source <id> [--only <path>]`: the content-repair lane's read-only preview (#6377; no model call). */+export function contentRepairArgv(sourceId: string, path?: string): string[] {+ return ['gbrain', 'repair', 'content', '--source', sourceId, ...(path ? ['--only', path] : [])];+}/** #6278: the three commands that clear a source's `preparation_stalled` holds, in order (no file repair applies). */export function stalledHoldSteps(sourceId: string, syncArgv?: string[]): { status: string[]; retry: string[]; sync: string[] } {@@ -365,15 +373,17 @@ export function stalledHoldSteps(sourceId: string, syncArgv?: string[]): { statu/*** 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.+ * it, says whether the maintenance run repairs the content holds (fence and+ * slug-conflict) by itself; their preview is the content-repair lane's.*/export function holdRepairSteps(sourceId: string, route: HoldRepairRoute, auto?: FenceAutoRepair): { argv: string[]; commands: string[]; text: string } {- const fences = fencePreviewArgv(sourceId);+ const content = (route.fences ?? 0) + (route.slug_conflicts ?? 0);+ const fences = contentRepairArgv(sourceId);const frontmatter = ['gbrain', 'repair', 'frontmatter', '--source', sourceId];- 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>)'+ const automatic = !auto ? '' : auto.active ? 'the next maintenance run repairs the fence and slug-conflict holds it can by itself; '+ : `nothing repairs the fence and slug-conflict holds by itself (${auto.enabled ? 'no maintenance run is active' : 'fences.repair.enabled is false'}), so `;+ const fenceText = `${automatic}preview the content repairs with ${fences.join(' ')} `+ + '(read-only, no model call: it lists each held file with its planned repair or the exact edit, kind by kind, and prints the apply command with --expect <hash>[,<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)`;const concurrentText = `for each concurrent-write hold, preview the reconciliation with gbrain sources reconcile ${sourceId} <slug> --preview `@@ -384,20 +394,20 @@ export function holdRepairSteps(sourceId: string, route: HoldRepairRoute, auto?:const unblock = ['gbrain', 'sync', 'unblock', '--source', sourceId, '--apply'];const dirtyText = `the ${route.dirty ?? 0} worktree-dirty hold(s) are uncommitted edits in the checkout that sync would not overwrite: commit them (gbrain sources status ${sourceId} names each file), `+ `then run ${unblock.join(' ')}, which re-screens every held file that is now committed, and the same sync`;- if (route.stalled && !route.others && !route.fences && !route.concurrent && !route.dirty) {+ if (route.stalled && !route.others && !content && !route.concurrent && !route.dirty) {return { argv: stalled.status, commands: [stalled.status.join(' '), stalled.retry.join(' '), stalled.sync.join(' ')], text: stalledText };}- if (route.dirty && !route.others && !route.fences && !route.concurrent && !route.stalled) {+ if (route.dirty && !route.others && !content && !route.concurrent && !route.stalled) {return { argv: unblock, commands: [`gbrain sources status ${sourceId} --json`, unblock.join(' '), `gbrain sync --source ${sourceId} --no-pull`], text: dirtyText };}if (route.concurrent || route.stalled || route.dirty) {- const parts = [...(route.others ? [frontmatterText] : []), ...(route.fences ? [fenceText] : []), ...(route.concurrent ? [concurrentText] : []), ...(route.stalled ? [stalledText] : []), ...(route.dirty ? [dirtyText] : [])];- const commands = [...(route.others ? [frontmatter.join(' ')] : []), ...(route.fences ? [fences.join(' ')] : []),+ const parts = [...(route.others ? [frontmatterText] : []), ...(content ? [fenceText] : []), ...(route.concurrent ? [concurrentText] : []), ...(route.stalled ? [stalledText] : []), ...(route.dirty ? [dirtyText] : [])];+ const commands = [...(route.others ? [frontmatter.join(' ')] : []), ...(content ? [fences.join(' ')] : []),...(route.stalled ? [stalled.status.join(' ')] : []), `gbrain sources status ${sourceId} --json`, ...(route.dirty ? [unblock.join(' ')] : []), `gbrain sources retry-held ${sourceId}`, `gbrain sync --source ${sourceId} --no-pull`];- return { argv: route.others ? frontmatter : route.fences ? fences : route.concurrent ? ['gbrain', 'sources', 'status', sourceId, '--json'] : route.stalled ? stalled.status : unblock, commands, text: parts.join('; ') };+ return { argv: route.others ? frontmatter : content ? fences : route.concurrent ? ['gbrain', 'sources', 'status', sourceId, '--json'] : route.stalled ? stalled.status : unblock, commands, text: parts.join('; ') };}- 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}` };+ if (content && !route.others) return { argv: fences, commands: [fences.join(' ')], text: fenceText };+ if (content) return { argv: frontmatter, commands: [frontmatter.join(' '), fences.join(' ')], text: `${frontmatterText}; ${fenceText}` };return { argv: frontmatter, commands: [frontmatter.join(' ')], text: frontmatterText };}@@ -709,9 +719,11 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; iconst stalled = Math.max(Number(summary?.stalled ?? 0), runHolds.filter(hold => stalledWeight(hold)).length);const concurrent = Math.max(Number(summary?.concurrent ?? 0), runHolds.filter(hold => concurrentWeight(hold)).length);const dirty = Math.max(Number(summary?.dirty ?? 0), runHolds.filter(hold => dirtyWeight(hold)).length);+ // #6377: this run's slug-conflict holds route to the content lane; earlier runs' stay in `others` (the summary does not count them).+ const slugConflicts = runHolds.filter(hold => hold.code === 'frontmatter_slug_conflict').length;const auto = fences ? await readFenceAutoRepair(engine) : undefined;- const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences - stalled - concurrent - dirty), ...(stalled ? { stalled } : {}),- ...(concurrent ? { concurrent } : {}), ...(dirty ? { dirty } : {}) }, auto);+ const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences - stalled - concurrent - dirty - slugConflicts), ...(stalled ? { stalled } : {}),+ ...(concurrent ? { concurrent } : {}), ...(dirty ? { dirty } : {}), ...(slugConflicts ? { slug_conflicts: slugConflicts } : {}) }, auto);// #6278: the escalation text is routed by code: stalled holds point at the writer, not at a generator.const runStalled = runHolds.filter(hold => stalledWeight(hold)).length;const escalation = runStalled * 2 > runHolds.length@@ -723,7 +735,7 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; iuser_message: `Some files in source ${input.sourceId} could not be imported. Please run 'gbrain sources status ${input.sourceId}' on the brain host, then: ${steps.text}.` } };const fix: Action = { argv: steps.argv, consent: [], actor: 'agent', requires_exclusive: false, verify,why: `${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 || stalled || concurrent || dirty ? `then ${steps.text}.` : 'the repair preview proposes each fix and writes nothing.')+ + (fences || stalled || concurrent || dirty || slugConflicts ? `then ${steps.text}.` : 'the repair preview proposes each fix and writes nothing.')+ (escalated ? escalation : '') };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 } : {}),diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 9d0efe814d..d84435066d 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -12,16 +12,27 @@* `needs_human` triple from `sync-fault-class.ts`, and one `next` action.* `unblockSync` performs the safe action for every hold that has one (a* `worktree_dirty` hold whose file is now committed and a `preparation_stalled`- * hold are scheduled for a re-screen) and refuses the rest by name: refusing is- * the only way it leaves a page out, and it never drops content. Both are- * trusted-local readers (the CLI); paths are source-root relative.+ * hold are scheduled for a re-screen; since #6377 a repair-class hold whose+ * code the content-repair lane clears, `CONTENT_REPAIR_HOLD_KINDS`, takes a+ * bounded hash-bound apply of that kind under the fence-repair caps, then the+ * re-screen) and refuses the rest by name: refusing is the only way it leaves a+ * page out, and it never drops content. A hold whose stored repair state says+ * a person decides (a manual fence reason, a paid wait, a recommended merge) is+ * listed, never retried. `--no-repair` restores the refuse-only behaviour,+ * `--no-llm` keeps the repairs to their free tiers. Both are trusted-local+ * readers (the CLI); paths are source-root relative, and the per-path repair+ * outcomes carry codes, tiers and hashes only.*/import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';import { managedSyncResumeArgs } from '../sync-reconcile.ts';import { readManagedSyncFailures, type ManagedSyncFailure } from './sync-failures.ts';-import { gitHoldFix, readGitSourceHolds, requestGitHoldRetry, type GitHoldRecord } from './sync-holds.ts';+import { fenceAutoRepairFor, gitHoldFix, readGitSourceHolds, requestGitHoldRetry, type GitHoldRecord } from './sync-holds.ts';+import type { FenceAutoRepair } from '../fence-repair/hold-fix.ts';import { classifySyncFault, HOLD_ATTEMPTS_NEEDS_HUMAN, type SyncFaultVerdict } from './sync-fault-class.ts';+import { CONTENT_REPAIR_KINDS, contentHoldDisposition, runContentLane, type ContentHoldDisposition } from '../repair/content-lane.ts';+import { resolveRepairScope, type RepairKind, type RepairResult } from '../repair/core.ts';+import type { RepairKindSpec } from '../repair/registry.ts';import { headCommittedBytes } from './sync-page-fault.ts';import { drainEstimate } from './sync-drain.ts';import { resolveManagedSyncContext } from './sync-discovery.ts';@@ -76,11 +87,30 @@ async function cursorHeader(engine: BrainEngine, sourceId: string): Promise<Cursreturn rows[0]?.header ?? null;}-function holdStatus(record: GitHoldRecord): SyncStatusHold {+/**+ * #6377: the verdict of a repair-class hold follows its stored repair state. A fence hold whose state is `manual` (a+ * manual-only reason, a gate rejection, a model failure the run does not retry) or `paid` (spend only the user raises),+ * and a slug-conflict hold the lane decided a person must settle (`merge_recommended`, `content_repair_needs_human`),+ * is `needs_human`: the lane will not act on it again until the file changes. `detail` lets the fault table name the+ * paragraph for the lane's codes when it knows them; otherwise the hold's own code decides.+ */+function holdVerdict(record: GitHoldRecord, auto: FenceAutoRepair | undefined): SyncFaultVerdict {+ const attempts = record.meta.attempts ?? 1;+ const disposition = contentHoldDisposition(record, auto);+ if (disposition.action !== 'listed' || disposition.state === 'owner') return classifySyncFault({ code: record.code, attempts });+ const verdict = classifySyncFault({ code: record.code, attempts, detail: disposition.reason });+ if (verdict.needs_human) return verdict;+ const reason = disposition.state === 'paid'+ ? `Model repair of ${record.path} waits on a setting only the user changes (${disposition.reason}); the hold's fix names it.`+ : `gbrain will not repair ${record.path} by itself (${disposition.reason}); the hold's fix names the exact edit or decision.`;+ return { ...verdict, safe_actions: ['none'], needs_human: true, human_reason: reason };+}++function holdStatus(record: GitHoldRecord, auto?: FenceAutoRepair): SyncStatusHold {const attempts = record.meta.attempts ?? 1;- const verdict = classifySyncFault({ code: record.code, attempts });+ const verdict = holdVerdict(record, auto);return { code: record.code, slug: record.slug, path: record.path, attempts, held_since: record.held_at, ...verdict,- retry_after: verdict.safe_actions[0] === 'retry' || verdict.safe_actions[0] === 'retry_when_clean' ? null : 'after the named step', fix: gitHoldFix(record) };+ retry_after: verdict.safe_actions[0] === 'retry' || verdict.safe_actions[0] === 'retry_when_clean' ? null : 'after the named step', fix: gitHoldFix(record, auto) };}export async function readSyncStatus(engine: BrainEngine, sourceId: string): Promise<SyncStatus> {@@ -89,7 +119,10 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Proconst header = await cursorHeader(engine, sourceId);const [committed] = await engine.executeRaw<{ n: number | string }>(`SELECT count(*) AS n FROM persistence_requests WHERE source_id=$1 AND state='committed'AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete') AND completed_at > now() - interval '10 minutes'`, [sourceId]);- const holds = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.incarnation === source.incarnation).map(holdStatus);+ const records = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.incarnation === source.incarnation);+ const auto = await fenceAutoRepairFor(engine, records);+ const holds = records.map(record => holdStatus(record, auto));+ const repairable = records.filter(record => contentHoldDisposition(record, auto).action === 'repair').length;const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');const failure = failures[0];const lastError: SyncStatusError | null = failure ? { code: failure.code, message: failure.message, path: failure.path, phase: failure.phase, first_seen: failure.first_seen, attempts: failure.attempts,@@ -107,7 +140,9 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Prouser_message: `Sync of source ${sourceId} needs a decision: ${'slug' in human && human.slug ? `page ${human.slug} (${('path' in human ? human.path : undefined) ?? ''})` : `code ${human.code}`}: ${human.human_reason ?? 'see the hold'}` }: actionable.length? { argv: ['gbrain', 'sync', 'unblock', '--source', sourceId, '--apply', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,- why: `${actionable.length} held file(s) have a safe action: unblock schedules each one whose condition holds (a committed edit, a stalled preparation) for a re-screen and names the sync to run; it refuses the rest by name and drops nothing.` }+ why: `${actionable.length} held file(s) have a safe action: unblock schedules each one whose condition holds (a committed edit, a stalled preparation) for a re-screen`+ + `${repairable ? `, repairs the ${repairable} content hold(s) the content-repair lane clears (hash-bound repairs under the fences.repair caps, one receipt per file, then the re-screen)` : ''}`+ + ' and names the sync to run; it refuses the rest by name and drops nothing.' }: unfinished || lastError? { argv: ['gbrain', 'sync', ...resume, ...(lastError ? ['--retry-failed'] : [])], consent: [], actor: 'agent', requires_exclusive: false, verify,why: lastError ? `The last run recorded ${lastError.code} (${lastError.class}); this release holds or retries it, and --retry-failed converts the stopped entry in place without re-freezing the manifest.`@@ -119,34 +154,87 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Proresume_argv: resume, next };}+/** #6377: what the content-repair lane did to one held path during `unblock --apply`; codes, tiers and hashes only. */+export interface UnblockRepairOutcome {+ kind: RepairKind;+ /** `repaired` (the write committed, hold cleared or re-screened), `held` (the kind recorded why), `needs_human` (a person decides), `skipped` (not this run: owner, busy, moved, preview). */+ outcome: 'repaired' | 'held' | 'needs_human' | 'skipped';+ /** The kind's reason code for anything but `repaired`. */+ reason?: string;+ tier?: string;+ llm_usd?: number;+ /** The write's location-only receipt fields (mode, tier, classes, hashes, commit state); never content. */+ receipt?: Record<string, unknown>;+ /** The exact next step for this path. */+ next: Action;+}++export type UnblockApplied =+ | { path: string; slug: string | null; code: string; action: 'retry_when_clean' | 'retry'; detail: string }+ | { path: string; slug: string | null; code: string; action: 'repair'; detail: string; repair: UnblockRepairOutcome };+export interface UnblockOutcome {source_id: string;apply: boolean;/** Holds whose safe action ran (or, without --apply, would run). */- applied: Array<{ path: string; slug: string | null; code: string; action: 'retry_when_clean' | 'retry'; detail: string }>;+ applied: UnblockApplied[];/** Holds unblock leaves in place, each with why and the step that clears it. */refused: Array<{ path: string; slug: string | null; code: string; reason: string; needs_human: boolean; fix: Action }>;/** The sync to run after an apply (the cursor's stored options), or the first refusal's fix when nothing applied. */next: Action | null;}+export interface UnblockOptions {+ apply: boolean;+ /** Today's refuse-only behaviour for repair-class holds. */+ noRepair?: boolean;+ /** Repairs keep to their free tiers. */+ noLlm?: boolean;+ /** The lane's paid allowance for this unblock (undefined: the kinds' own caps). */+ maxLlmUsd?: number;+ /** Replaces the registered repair kinds (tests pass stub specs). */+ registry?: readonly RepairKindSpec[];+}++/** The longest one `unblock --apply` spends repairing; the kinds stop `time_budget` past it and the next unblock resumes. */+export const UNBLOCK_REPAIR_BUDGET_MS = 120_000;++const quiet = { info() {}, warn() {}, error() {} };++/** Location-only fields of a kind's outcome detail (its prose `message` and the legacy commit step are printed, not stored). */+function receiptOf(detail: Record<string, unknown> | undefined): Record<string, unknown> | undefined {+ if (!detail) return undefined;+ const { message: _message, commit_step: _step, why: _why, fix: _fix, ...rest } = detail;+ return Object.keys(rest).length ? rest : undefined;+}+/*** Performs the safe action for every hold that has one. `retry_when_clean` (`worktree_dirty`): the file is re-screened only* when its working-tree bytes are committed at HEAD now; still-dirty files are refused `still_dirty`. `retry`- * (`preparation_stalled`): scheduled for a re-screen. A hold whose attempts reached `HOLD_ATTEMPTS_NEEDS_HUMAN`, a- * `concurrent_write` hold and every repair-class hold are refused by name with their fix. Idempotent: scheduling twice is- * one re-screen, and nothing here writes a page or clears a hold.+ * (`preparation_stalled`): scheduled for a re-screen. `repair` (#6377; a hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to+ * a lane kind, unless `noRepair`): the kind runs on exactly those paths as one bounded apply under its caps (each item bound+ * to the bytes the kind's plan read), each path reports `repaired | held | needs_human | skipped` with the+ * kind's receipt or reason, and repaired paths are scheduled for the re-screen. A hold whose attempts reached+ * `HOLD_ATTEMPTS_NEEDS_HUMAN`, a `concurrent_write` hold, a repair-class hold whose stored state waits on a person, the+ * user's spend decision or the owner host, and a repair-class hold no lane kind clears yet are refused by name with their+ * fix. Idempotent: scheduling twice is one re-screen, a repaired file is `already_clean` on the next pass, and a preview+ * writes nothing.*/-export async function unblockSync(engine: BrainEngine, sourceId: string, opts: { apply: boolean }): Promise<UnblockOutcome> {+export async function unblockSync(engine: BrainEngine, sourceId: string, opts: UnblockOptions): Promise<UnblockOutcome> {const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);if (!source) throw Object.assign(new Error(`Source ${sourceId} does not exist.`), { code: 'not_found' });const holds = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.incarnation === source.incarnation);const header = await cursorHeader(engine, sourceId);const resume = managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });const context = holds.some(hold => hold.code === 'worktree_dirty') ? await resolveManagedSyncContext(engine, { sourceId, noPull: true }).catch(() => null) : null;+ const auto = await fenceAutoRepairFor(engine, holds);const applied: UnblockOutcome['applied'] = [], refused: UnblockOutcome['refused'] = [];+ const repairs = new Map<RepairKind, GitHoldRecord[]>();+ const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };+ const unblockApply: Action = { argv: ['gbrain', 'sync', 'unblock', '--source', sourceId, '--apply', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: 'Runs the lane kind on this path as a hash-bound apply under the fences.repair caps and schedules the re-screen.' };for (const hold of holds) {- const status = holdStatus(hold);+ const status = holdStatus(hold, auto);const refuse = (reason: string) => refused.push({ path: hold.path, slug: hold.slug, code: hold.code, reason, needs_human: status.needs_human, fix: status.fix });if (status.needs_human) { refuse(status.human_reason ?? 'needs a person'); continue; }if (hold.code === 'worktree_dirty') {@@ -159,16 +247,60 @@ export async function unblockSync(engine: BrainEngine, sourceId: string, opts: {applied.push({ path: hold.path, slug: hold.slug, code: hold.code, action: 'retry', detail: `attempt ${(hold.meta.attempts ?? 1) + 1} of ${HOLD_ATTEMPTS_NEEDS_HUMAN}; scheduled for a re-screen` });continue;}- refuse(`${status.safe_actions[0]}: not something unblock performs; run the fix it names`);+ const disposition: ContentHoldDisposition = opts.noRepair ? { action: 'unsupported' } : contentHoldDisposition(hold, auto);+ if (disposition.action === 'listed') { refuse(`${disposition.state}: ${disposition.reason}; the content-repair lane will not retry it until the file changes`); continue; }+ if (disposition.action === 'unsupported') { refuse(`${status.safe_actions[0]}: not something unblock performs; run the fix it names`); continue; }+ repairs.set(disposition.kind, [...(repairs.get(disposition.kind) ?? []), hold]);+ if (!opts.apply) {+ applied.push({ path: hold.path, slug: hold.slug, code: hold.code, action: 'repair', detail: `would run gbrain repair ${disposition.kind} on this path under the fences.repair caps; --apply repairs it and schedules the re-screen`,+ repair: { kind: disposition.kind, outcome: 'skipped', reason: 'preview', next: unblockApply } });+ }}- if (opts.apply && applied.length) await requestGitHoldRetry(engine, sourceId, source.incarnation, applied.map(entry => entry.path));- const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };+ const retry = applied.filter(entry => entry.action !== 'repair').map(entry => entry.path);+ if (opts.apply && repairs.size) {+ const kinds = CONTENT_REPAIR_KINDS.filter(kind => repairs.has(kind));+ const paths = [...repairs.values()].flat().map(hold => hold.path);+ const startedAt = Date.now();+ const lane = await runContentLane(engine, await resolveRepairScope(engine, sourceId), { apply: true, kinds, only: paths, noLlm: opts.noLlm, maxLlmUsd: opts.maxLlmUsd,+ deadline: Date.now() + UNBLOCK_REPAIR_BUDGET_MS, sourceFlag: sourceId, logger: quiet, ...(opts.registry ? { registry: opts.registry } : {}) });+ const after = new Map((((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? [])).map(hold => [hold.path, hold]));+ const syncNext: Action = { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify, why: 'Re-imports the repaired file and clears or re-screens its hold.' };+ for (const [kind, records] of repairs) {+ const result: RepairResult | undefined = lane.results.find(r => r.kind === kind);+ const stop = lane.stopped.find(s => s.kind === kind);+ for (const hold of records) {+ const item = result?.outcome_items?.find(o => o.detail?.path === hold.path || (hold.slug !== null && o.item === `${sourceId}:${hold.slug}`));+ const current = after.get(hold.path) ?? hold;+ const fix = gitHoldFix(current, auto);+ // A path the kind planned reports its own outcome; one it kept out of the plan recorded why on the hold (its state decides), or was never reached.+ const state = item?.outcome === 'repaired' ? null : contentHoldDisposition(current, auto);+ const recorded = current.meta.fence_repair && Date.parse(current.meta.fence_repair.at) >= startedAt ? current.meta.fence_repair.reason : undefined;+ const outcome: UnblockRepairOutcome['outcome'] = item?.outcome === 'repaired' ? 'repaired'+ : state?.action === 'listed' ? (state.state === 'needs_human' ? 'needs_human' : 'held')+ : item ? (item.outcome === 'held' ? 'held' : 'skipped') : recorded ? 'held' : 'skipped';+ const reason = outcome === 'repaired' ? undefined : state?.action === 'listed' ? state.reason : item ? item.reason : recorded ?? stop?.reason ?? 'not_planned';+ const detail = item?.detail as Record<string, unknown> | undefined;+ const message = typeof detail?.message === 'string' ? detail.message : undefined;+ const llmUsd = item?.llm_usd;+ if (outcome === 'repaired') retry.push(hold.path);+ applied.push({ path: hold.path, slug: hold.slug, code: hold.code, action: 'repair',+ detail: outcome === 'repaired' ? `repaired by gbrain repair ${kind}${typeof detail?.tier === 'string' ? ` (${detail.tier})` : ''}; scheduled for a re-screen`+ : `${outcome} (${reason})${message ? `: ${message}` : !item && stop ? `: ${stop.message}` : ''}`,+ repair: { kind, outcome, ...(reason ? { reason } : {}), ...(typeof detail?.tier === 'string' ? { tier: detail.tier } : {}), ...(llmUsd !== undefined ? { llm_usd: llmUsd } : {}),+ ...(receiptOf(detail) ? { receipt: receiptOf(detail) } : {}), next: outcome === 'repaired' ? syncNext : outcome === 'skipped' && (!item || stop) ? unblockApply : fix } });+ }+ }+ }+ if (opts.apply && retry.length) await requestGitHoldRetry(engine, sourceId, source.incarnation, retry);+ const repaired = applied.filter(entry => entry.action === 'repair' && entry.repair.outcome === 'repaired').length;const next: Action | null = applied.length? opts.apply- ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,- why: `${applied.length} held file(s) are scheduled for a re-screen; the sync imports each one that now passes and holds again what still fails, without blocking the rest.` }+ ? retry.length+ ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `${retry.length} held file(s) are scheduled for a re-screen${repaired ? ` (${repaired} repaired by the content-repair lane, each with its receipt above)` : ''}; the sync imports each one that now passes and holds again what still fails, without blocking the rest.` }+ : (applied.find((entry): entry is Extract<UnblockApplied, { action: 'repair' }> => entry.action === 'repair')?.repair.next ?? refused[0]?.fix ?? null): { argv: ['gbrain', 'sync', 'unblock', '--source', sourceId, '--apply', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,- why: `${applied.length} held file(s) would be scheduled for a re-screen; nothing was written. --apply schedules them and prints the sync to run.` }+ why: `${applied.length} held file(s) would be ${repairs.size ? 'repaired or ' : ''}scheduled for a re-screen; nothing was written. --apply ${repairs.size ? 'runs the hash-bound repairs under the fences.repair caps, ' : ''}schedules the re-screens and prints the sync to run.` }: refused[0]?.fix ?? null;return { source_id: sourceId, apply: opts.apply, applied, refused, next };}diff --git a/src/core/repair/content-lane.ts b/src/core/repair/content-lane.tsnew file mode 100644index 0000000000..6ef6093140--- /dev/null+++ b/src/core/repair/content-lane.ts@@ -0,0 +1,177 @@+/**+ * The content-repair lane (#6377): the repair kinds that clear managed-sync+ * content holds, run as one bounded pass under one paid-model allowance.+ *+ * `CONTENT_REPAIR_KINDS` is the lane in dependency order; `gbrain repair+ * content`, the `content_repair` maintenance phase (src/core/cycle/+ * content-repair.ts) and `gbrain sync unblock --apply` all read it, so a new+ * kind plugs in with one entry here. Today it holds `fences`; the GBRA-72+ * integration appends `slug-conflicts` (Lane B, src/core/repair/+ * slug-conflicts.ts). `CONTENT_REPAIR_HOLD_KINDS` maps a hold code to the kind+ * that clears it (`null`: no kind yet, the surfaces keep today's refusal text).+ *+ * `runContentLane` has no rule logic of its own: it runs each kind through+ * the shared trusted `repairRunner`, so every kind keeps its own census, owner+ * checks, caps, ledger, memo and gates. What the lane adds is the contract+ * between kinds: the run's paid allowance (`maxLlmUsd`) flows from one kind to+ * the next minus what the earlier kinds spent (read from each result's+ * `cost.llm_usd`; the daily ledger is shared by every kind, `FENCE_REPAIR_LEDGER`),+ * and one absolute deadline bounds the whole pass. A preview builds every+ * component plan before any mutation and returns each kind's own preview+ * hash; `--apply --expect <h1>[,<h2>]` applies exactly those sets, one hash+ * per kind in lane order, so the operator's approval binds both concrete plans+ * (Codex #10). There is no combined hash. A bare apply (the cycle, `sync+ * unblock`, `--apply` alone) applies each kind's current plan the way+ * `gbrain repair <kind> --apply` does: the kind plans and applies in one run,+ * each item bound to the bytes its plan read (`changed_since_read`), and+ * records on every hold it leaves why (a preview records nothing).+ *+ * `contentHoldDisposition` is the one place that reads a hold's stored repair+ * state (a fence hold's `fenceHoldStatus`, a slug-conflict hold's+ * `meta.content_repair.action`) to say whether unattended surfaces may run the+ * kind on it or must list it for a person. Output is counts, codes, hashes+ * and paths only: never a claim, a cell or a frontmatter value.+ */+import type { BrainEngine } from '../engine.ts';+import type { OperationContext } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { shellQuote } from '../agent-output.ts';+import { fenceHoldStatus, type FenceAutoRepair } from '../fence-repair/hold-fix.ts';+import type { GitHoldRecord } from '../persistence/sync-holds.ts';+import type { RepairKind, RepairResult, RepairScope } from './core.ts';+import { repairRunner, type RepairKindSpec } from './registry.ts';++/** The lane, in run order. GBRA-72 integration appends 'slug-conflicts' (Lane B). */+export const CONTENT_REPAIR_KINDS: readonly RepairKind[] = ['fences'];++/**+ * Which lane kind clears a hold code. `null` keeps today's behaviour for the+ * code (unblock refuses it with the fix it names); Lane B sets+ * `frontmatter_slug_conflict` to 'slug-conflicts'.+ */+export const CONTENT_REPAIR_HOLD_KINDS: Readonly<Partial<Record<GitHoldRecord['code'], RepairKind | null>>> = {+ invalid_fence: 'fences',+ frontmatter_slug_conflict: null,+};++/** A hold's stored repair decision, when the lane recorded one (Lane B writes it; read loosely so either lane lands first). */+function storedContentAction(meta: GitHoldRecord['meta']): string | undefined {+ const action = (meta as { content_repair?: { action?: unknown } }).content_repair?.action;+ return typeof action === 'string' ? action : undefined;+}++export type ContentHoldDisposition =+ /** An unattended run may run `kind` on this hold now. */+ | { action: 'repair'; kind: RepairKind }+ /** The hold waits on a person (`needs_human`), the user's spend decision (`paid`) or the owner host (`owner`); list it, never retry it. */+ | { action: 'listed'; kind: RepairKind; state: 'needs_human' | 'paid' | 'owner'; reason: string }+ /** No lane kind clears this code yet. */+ | { action: 'unsupported' };++/**+ * What an unattended surface (`sync unblock --apply`, the cycle) may do with+ * one hold. `auto` is what the caller read about the maintenance run+ * (`fenceAutoRepairFor`); it decides a fence hold's state exactly as the+ * hold's own fix does.+ */+export function contentHoldDisposition(record: Pick<GitHoldRecord, 'code' | 'meta'>, auto?: FenceAutoRepair): ContentHoldDisposition {+ const kind = CONTENT_REPAIR_HOLD_KINDS[record.code];+ if (!kind) return { action: 'unsupported' };+ if (record.code === 'invalid_fence') {+ const status = fenceHoldStatus(record.meta, auto);+ if (status.state === 'manual') return { action: 'listed', kind, state: 'needs_human', reason: status.reason };+ if (status.state === 'paid' || status.state === 'owner') return { action: 'listed', kind, state: status.state, reason: status.reason };+ return { action: 'repair', kind };+ }+ const stored = storedContentAction(record.meta);+ if (stored === 'merge_into') return { action: 'listed', kind, state: 'needs_human', reason: 'merge_recommended' };+ if (stored === 'needs_human') return { action: 'listed', kind, state: 'needs_human', reason: 'content_repair_needs_human' };+ return { action: 'repair', kind };+}++export interface ContentLaneOptions {+ apply: boolean;+ /** The kinds to run, in order (default: the whole lane). */+ kinds?: readonly RepairKind[];+ /** Source-relative file selection, handed to every kind (its hash covers it). */+ only?: string[];+ skip?: string[];+ /** One preview hash per kind in `kinds` order; the apply binds each kind to exactly that set. */+ expect?: readonly string[];+ /** Free tiers only, for every kind. */+ noLlm?: boolean;+ /** The run's paid-model allowance in USD for the whole lane; what one kind spends is gone for the next. */+ maxLlmUsd?: number;+ /** Absolute deadline (epoch ms) for the whole lane; a kind stopped `time_budget` ends the pass. */+ deadline?: number;+ limit?: number;+ noEmbed?: boolean;+ /** `--source <id>` as the operator wrote it, for the printed commands. */+ sourceFlag?: string;+ /** Replaces the registered kinds (tests pass stub specs). */+ registry?: readonly RepairKindSpec[];+ logger?: OperationContext['logger'];+}++export interface ContentLaneResult {+ mode: 'dry_run' | 'apply';+ scope: RepairScope;+ /** The kinds the lane ran, in order; one `results` entry each. */+ kinds: RepairKind[];+ results: RepairResult[];+ /** Each kind's own preview hash on a dry run, the hash each apply was bound to with `expect` (null: the kind printed none, or a bare apply). */+ preview_hashes: Partial<Record<RepairKind, string | null>>;+ /** Paid-model spend across the lane: the estimate on a dry run, the actual spend on an apply; the allowance left under `maxLlmUsd` (null: no run cap). */+ cost: { llm_usd: number; llm_allowance_remaining_usd: number | null };+ /** Every kind that stopped, with its reason (`time_budget` ends the lane; the rest let the next kind run). */+ stopped: Array<{ kind: RepairKind } & NonNullable<RepairResult['stopped']>>;+ /** The command that applies exactly these plans (dry run), or reruns the lane (apply). */+ apply_command: string;+}++/** `gbrain repair content [--source <id>] [--only <p>]... [--skip <p>]... [--no-llm] [--max-usd <n>] [--apply [--expect <h1>,<h2>]]`. */+export function contentLaneArgv(opts: { source?: string; only?: readonly string[]; skip?: readonly string[]; noLlm?: boolean; maxLlmUsd?: number; apply?: boolean; expect?: readonly string[] }): string[] {+ return ['gbrain', 'repair', 'content', ...(opts.source ? ['--source', opts.source] : []), ...(opts.only ?? []).flatMap(path => ['--only', path]),+ ...(opts.skip ?? []).flatMap(path => ['--skip', path]), ...(opts.noLlm ? ['--no-llm'] : []), ...(opts.maxLlmUsd !== undefined ? ['--max-usd', String(opts.maxLlmUsd)] : []),+ ...(opts.apply ? ['--apply'] : []), ...(opts.expect?.length ? ['--expect', opts.expect.join(',')] : [])];+}++/**+ * `--expect <h1>[,<h2>]` → one hash per kind, in order. Refuses a count that+ * does not match the kinds the lane runs: the operator previewed a different+ * lane, so no hash can be matched to a kind.+ */+export function parseContentLaneExpect(text: string, kinds: readonly RepairKind[], previewArgv: string[]): string[] {+ const hashes = text.split(',').map(hash => hash.trim()).filter(Boolean);+ if (hashes.length === kinds.length) return hashes;+ throw opError('invalid_params', `--expect takes one preview hash per kind of the content lane, comma-separated in lane order (${kinds.join(', ')}); got ${hashes.length} hash(es) for ${kinds.length} kind(s), so nothing ran.`,+ `Preview the lane again and pass the hashes it prints: ${shellQuote(previewArgv)} prints each kind's own hash and the exact apply command.`,+ { fix: readFix('Previews every lane kind; it writes nothing and calls no model.', { argv: previewArgv }) });+}++export async function runContentLane(engine: BrainEngine, scope: RepairScope, opts: ContentLaneOptions): Promise<ContentLaneResult> {+ const kinds = [...(opts.kinds ?? CONTENT_REPAIR_KINDS)];+ const previewArgv = contentLaneArgv({ source: opts.sourceFlag, only: opts.only, skip: opts.skip, noLlm: opts.noLlm, maxLlmUsd: opts.maxLlmUsd });+ if (opts.expect && opts.expect.length !== kinds.length) parseContentLaneExpect(opts.expect.join(','), kinds, previewArgv);+ const runner = await repairRunner(engine, { apply: opts.apply, noEmbed: opts.noEmbed, ...(opts.logger ? { logger: opts.logger } : {}), ...(opts.registry ? { registry: opts.registry } : {}) });+ const hashes: ContentLaneResult['preview_hashes'] = {};+ const stopped: ContentLaneResult['stopped'] = [];+ const results: RepairResult[] = [];+ let spent = 0;+ const allowance = () => opts.maxLlmUsd === undefined ? undefined : Math.max(0, opts.maxLlmUsd - spent);+ for (const [index, kind] of kinds.entries()) {+ const expect = opts.expect?.[index];+ const result = await runner.run(kind, scope, { explicit: true, limit: opts.limit, sourceFlag: opts.sourceFlag, only: opts.only, skip: opts.skip, noLlm: opts.noLlm,+ maxLlmUsd: allowance(), deadline: opts.deadline, ...(expect ? { expect } : {}) });+ hashes[kind] = expect ?? result.preview_hash ?? null;+ spent += result.cost.llm_usd ?? 0;+ results.push(result);+ if (result.stopped) stopped.push({ kind, ...result.stopped });+ if (result.stopped?.reason === 'time_budget') break;+ }+ const expect = kinds.map(kind => hashes[kind] ?? null);+ return { mode: opts.apply ? 'apply' : 'dry_run', scope, kinds, results, preview_hashes: hashes, cost: { llm_usd: spent, llm_allowance_remaining_usd: allowance() ?? null }, stopped,+ apply_command: shellQuote(contentLaneArgv({ source: opts.sourceFlag, only: opts.only, skip: opts.skip, noLlm: opts.noLlm, maxLlmUsd: opts.maxLlmUsd, apply: true,+ expect: expect.every((hash): hash is string => hash !== null) ? expect : undefined })) };+}diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 1f40620f94..849814de71 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -144,9 +144,11 @@ export interface RepairResult {scan?: { fresh_at: string | null; partial: boolean };/** Preview-bound kinds' dry run: every item the preview hash covers. */listing?: RepairListing[];+ /** Preview-bound kinds' dry run: the hash `--apply --expect` binds to (the one `apply_command` carries). */+ preview_hash?: string;/** Per-outcome counts and the first items, for kinds that name outcomes. */outcomes?: Record<string, number>;- outcome_items?: Array<{ item: string; outcome: string; reason?: string; detail?: Record<string, unknown> }>;+ outcome_items?: Array<{ item: string; outcome: string; reason?: string; detail?: Record<string, unknown>; llm_usd?: number }>;/** Kind-specific preview detail (see RepairPlan.details). */details?: Record<string, unknown>;}@@ -286,6 +288,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s};if (!opts.apply) {if (plan.listing) result.listing = plan.listing;+ if (plan.preview_hash) result.preview_hash = plan.preview_hash;if (plan.details) result.details = plan.details;result.complete = pending.length === plan.items.length;return finish();@@ -328,7 +331,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sresult.outcomes = { ...result.outcomes, [applied.outcome]: (result.outcomes?.[applied.outcome] ?? 0) + 1 };if ((result.outcome_items ??= []).length < (handler.outcomeItemsLimit ?? SAMPLE * 2)) {result.outcome_items.push({ item: `${item.source_id}:${item.slug}`, outcome: applied.outcome, ...(applied.reason ? { reason: applied.reason } : {}),- ...(applied.detail ? { detail: applied.detail } : {}) });+ ...(applied.detail ? { detail: applied.detail } : {}), ...(applied.llm_usd ? { llm_usd: applied.llm_usd } : {}) });}}if (typeof applied === 'object' ? applied.applied : applied) result.applied++;diff --git a/test/cycle-content-repair.test.ts b/test/cycle-content-repair.test.tsnew file mode 100644index 0000000000..7ea24c14a0--- /dev/null+++ b/test/cycle-content-repair.test.ts@@ -0,0 +1,269 @@+/**+ * #6377 `content_repair` maintenance phase (src/core/cycle/content-repair.ts)+ * and the content lane it runs (src/core/repair/content-lane.ts).+ *+ * Protects: the global maintenance lane runs the rest of the content-repair+ * lane by itself, bounded and honest. With `CONTENT_REPAIR_KINDS` holding only+ * `fences` the phase runs nothing and says so (`no_kinds`); a kind handed to+ * it runs through the shared repair runner with the lane's deadline+ * (min(120 s, a third of the job's remaining time)); `fences.repair.enabled`+ * false pauses it without calling the kind; the report carries counts by+ * outcome and reason, the lane's spend and the oldest hold's age; a non-time+ * stop or an internal error reports `warn` with the next step and no error+ * text; the phase is brain-global, right after `fence_repair`, and never in a+ * per-source payload. The lane itself: every component plan is built before+ * the first mutation and each kind applies against its own hash; the paid+ * allowance flows minus the earlier kind's spend; `--expect` needs one hash+ * per kind.+ * Fails when: the enabled gate is dropped, the budget formula changes, the+ * phase hides a kind's stop, an error fails the cycle or leaks its message,+ * the lane applies before planning, or the allowance stops flowing.+ * Why new: the fence_repair test covers one kind's wrapper; nothing covered a+ * lane of kinds sharing one allowance, nor the plan-first apply.+ * Seams: the repair runner's `registry` stub-spec seam, passed through the+ * lane and the phase; `kinds` names the stub kind the phase should run.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { ALL_PHASES, GLOBAL_PHASES, MAINTENANCE_PHASES, PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, SOURCE_PHASES, normalizeQueuedSourcePhases } from '../src/core/cycle.ts';+import { CONNECTOR_SOURCE_PHASES } from '../src/core/cycle/phase-scope.ts';+import { MANAGED_PHASE_TABLE } from '../src/core/cycle/phase-table.ts';+import { CONTENT_REPAIR_PHASE_BUDGET_MS, contentRepairPhaseKinds, runContentRepairPhase } from '../src/core/cycle/content-repair.ts';+import { CONTENT_REPAIR_HOLD_KINDS, CONTENT_REPAIR_KINDS, contentHoldDisposition, parseContentLaneExpect, runContentLane } from '../src/core/repair/content-lane.ts';+import { afterCursor, resolveRepairScope, type RepairCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairKind, type RepairPlanOptions } from '../src/core/repair/core.ts';+import type { RepairKindSpec } from '../src/core/repair/registry.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { RECOVERY_VERSION } from '../src/core/markdown.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); });++interface Stub {+ spec: RepairKindSpec;+ plans: Array<{ apply: boolean; after: RepairCursor | null; opts?: RepairPlanOptions }>;+ applied: Array<{ id: number; deadline?: number; allowance?: number; expect?: string }>;+}++/** A stub lane kind over `count` items: preview-bound (its hash binds the selection), spends on the model, honors the resume cursor. */+function stubKind(kind: RepairKind, count: number, behavior: {+ onApply?: (item: RepairItem) => Partial<RepairItemOutcome> | void;+ plan?: () => never;+ llmUsdPerItem?: number;+ verification?: Record<string, unknown>;+} = {}): Stub {+ const items: RepairItem[] = Array.from({ length: count }, (_, id) => ({ cursor: { phase: 0, id }, source_id: 'default', slug: `people/alice-example-${id}`, chars: 10, action: 'repair',+ ...(behavior.llmUsdPerItem ? { llm_usd: behavior.llmUsdPerItem } : {}) }));+ const stub: Stub = { plans: [], applied: [], spec: undefined as never };+ let repaired = 0;+ const handler: RepairHandler = {+ kind, publication: 'projection', embeds: false,+ async plan(_engine, _scope, after, opts) {+ stub.plans.push({ apply: opts?.apply === true, after, opts });+ behavior.plan?.();+ return { items: items.filter(item => afterCursor(item.cursor, after)), residuals: {}, preview_hash: `${kind}-hash-${count}`,+ llm: { usd: items.length * (behavior.llmUsdPerItem ?? 0), cap_remaining_usd: 1 }, scan: { fresh_at: null, partial: false } };+ },+ async apply(_ctx, item, opts) {+ stub.applied.push({ id: item.cursor.id, deadline: opts?.deadline, allowance: opts?.llmAllowanceUsd, expect: opts?.expect });+ const outcome: RepairItemOutcome = { applied: true, outcome: 'repaired', detail: { tier: 'deterministic', path: `${item.slug}.md` }, ...(behavior.llmUsdPerItem ? { llm_usd: behavior.llmUsdPerItem } : {}), ...behavior.onApply?.(item) };+ if (outcome.applied) repaired++;+ return outcome;+ },+ ...(behavior.verification ? { async report() { return { repaired, verification: behavior.verification }; } } : {}),+ };+ stub.spec = { kind, handler, summary: 'stub', embeds: 'none', checks: [], preview_bound: true, spends: 'llm' };+ return stub;+}++describe('the content lane', () => {+ test('today it holds fences; the hold table maps invalid_fence to it and leaves frontmatter_slug_conflict for Lane B', () => {+ expect(CONTENT_REPAIR_KINDS).toEqual(['fences']);+ expect(CONTENT_REPAIR_HOLD_KINDS.invalid_fence).toBe('fences');+ expect(CONTENT_REPAIR_HOLD_KINDS.frontmatter_slug_conflict).toBeNull();+ expect(contentRepairPhaseKinds()).toEqual([]);+ const meta = { recovery_version: RECOVERY_VERSION };+ expect(contentHoldDisposition({ code: 'frontmatter_slug_conflict', meta })).toEqual({ action: 'unsupported' });+ expect(contentHoldDisposition({ code: 'invalid_frontmatter', meta })).toEqual({ action: 'unsupported' });+ expect(contentHoldDisposition({ code: 'invalid_fence', meta: { ...meta, reason: 'holder_unresolved' } })).toEqual({ action: 'repair', kind: 'fences' });+ expect(contentHoldDisposition({ code: 'invalid_fence', meta: { ...meta, reason: 'repeated_marker' } })).toEqual({ action: 'listed', kind: 'fences', state: 'needs_human', reason: 'repeated_marker' });+ expect(contentHoldDisposition({ code: 'invalid_fence', meta: { ...meta, reason: 'no_header', fence_repair: { reason: 'budget_exhausted', tier: 'llm', at: 't', next_attempt_after: 'u' } } }))+ .toEqual({ action: 'listed', kind: 'fences', state: 'paid', reason: 'budget_exhausted' });+ expect(contentHoldDisposition({ code: 'invalid_fence', meta: { ...meta, reason: 'no_header', fence_repair: { reason: 'host_mismatch', tier: 'llm', at: 't', next_attempt_after: null } } }))+ .toEqual({ action: 'listed', kind: 'fences', state: 'owner', reason: 'host_mismatch' });+ });++ test('a dry run plans every kind, prints each kind\'s own hash and writes nothing; the apply command carries one hash per kind', async () => {+ const a = stubKind('fences', 2, { llmUsdPerItem: 0.1 }), b = stubKind('connector-fences', 1, { llmUsdPerItem: 0.1 });+ const scope = await resolveRepairScope(engine);+ const lane = await runContentLane(engine, scope, { apply: false, kinds: ['fences', 'connector-fences'], registry: [a.spec, b.spec], maxLlmUsd: 0.5, sourceFlag: 'default' });+ expect(lane.mode).toBe('dry_run');+ expect(lane.kinds).toEqual(['fences', 'connector-fences']);+ expect(lane.preview_hashes).toEqual({ fences: 'fences-hash-2', 'connector-fences': 'connector-fences-hash-1' });+ expect(lane.results.map(r => [r.kind, r.mode, r.affected, r.preview_hash])).toEqual([['fences', 'dry_run', 2, 'fences-hash-2'], ['connector-fences', 'dry_run', 1, 'connector-fences-hash-1']]);+ expect(lane.cost.llm_usd).toBeCloseTo(0.3); expect(lane.cost.llm_allowance_remaining_usd).toBeCloseTo(0.2);+ expect(lane.apply_command).toBe('gbrain repair content --source default --max-usd 0.5 --apply --expect fences-hash-2,connector-fences-hash-1');+ expect(a.applied).toHaveLength(0); expect(b.applied).toHaveLength(0);+ // The second kind's plan was built with the allowance left after the first kind's estimate.+ expect(b.plans[0]?.opts?.maxLlmUsd).toBeCloseTo(0.3);+ });++ test('a bare apply runs each kind\'s current plan in order (its own plan, its own apply, as gbrain repair <kind> --apply); the allowance flows minus the earlier spend', async () => {+ const a = stubKind('fences', 2, { llmUsdPerItem: 0.1 });+ const b = stubKind('connector-fences', 2, { llmUsdPerItem: 0.1 });+ const lane = await runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: ['fences', 'connector-fences'], registry: [a.spec, b.spec], maxLlmUsd: 0.35 });+ expect(lane.mode).toBe('apply');+ expect(a.plans.map(p => p.apply)).toEqual([true]);+ expect(b.plans.map(p => p.apply)).toEqual([true]);+ expect(a.applied.map(x => x.expect)).toEqual([undefined, undefined]);+ expect(a.applied[0]!.allowance).toBeCloseTo(0.35); expect(a.applied[1]!.allowance).toBeCloseTo(0.25);+ // fences spent 0.20; connector-fences gets 0.15, enough for one item, then stops before the second (budget_exhausted).+ expect(b.plans[0]?.opts?.maxLlmUsd).toBeCloseTo(0.15);+ expect(b.applied).toHaveLength(1);+ expect(b.applied[0]!.allowance).toBeCloseTo(0.15);+ expect(lane.preview_hashes).toEqual({ fences: null, 'connector-fences': null });+ expect(lane.stopped.map(s => [s.kind, s.reason])).toEqual([['connector-fences', 'budget_exhausted']]);+ expect(lane.cost.llm_usd).toBeCloseTo(0.3);+ expect(lane.cost.llm_allowance_remaining_usd).toBeCloseTo(0.05);+ });++ test('--expect binds each kind to the operator\'s hash in lane order, and a count that does not match the lane refuses before anything runs', async () => {+ const a = stubKind('fences', 1), b = stubKind('connector-fences', 1);+ const lane = await runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: ['fences', 'connector-fences'], registry: [a.spec, b.spec], expect: ['h1', 'h2'] });+ expect(a.plans.map(p => p.apply)).toEqual([true]);+ expect(a.applied[0]?.expect).toBe('h1'); expect(b.applied[0]?.expect).toBe('h2');+ expect(lane.preview_hashes).toEqual({ fences: 'h1', 'connector-fences': 'h2' });+ const c = stubKind('fences', 1);+ await expect(runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: ['fences', 'connector-fences'], registry: [c.spec, b.spec], expect: ['h1'] }))+ .rejects.toMatchObject({ code: 'invalid_params' });+ expect(c.plans).toHaveLength(0);+ expect(() => parseContentLaneExpect('h1', ['fences', 'connector-fences'], ['gbrain', 'repair', 'content'])).toThrow(OperationError);+ expect(parseContentLaneExpect('h1, h2', ['fences', 'connector-fences'], ['gbrain', 'repair', 'content'])).toEqual(['h1', 'h2']);+ });++ test('a time_budget stop in one kind ends the lane; the deadline reaches every kind', async () => {+ const t = Date.now();+ const a = stubKind('fences', 2, { onApply: item => ({ stop: item.cursor.id === 0 ? { reason: 'time_budget', message: 'out of time' } : undefined }) });+ const b = stubKind('connector-fences', 1);+ const lane = await runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: ['fences', 'connector-fences'], registry: [a.spec, b.spec], deadline: t + 1000 });+ expect(a.applied).toHaveLength(1);+ expect(a.applied[0]?.deadline).toBe(t + 1000);+ expect(b.applied).toHaveLength(0);+ expect(lane.results.map(r => r.kind)).toEqual(['fences']);+ expect(lane.stopped.map(s => s.reason)).toEqual(['time_budget']);+ });+});++describe('content_repair phase gates and budget', () => {+ test('with no lane kind beyond fences the phase runs nothing and says so', async () => {+ const result = await runContentRepairPhase(engine, { dryRun: false });+ expect(result).toMatchObject({ status: 'skipped', details: { reason: 'no_kinds', kinds: [] } });+ expect(result.summary).toContain('ran nothing');+ });++ test('fences.repair.enabled false skips the phase and never calls the kind', async () => {+ const stub = stubKind('connector-fences', 2);+ await engine.setConfig('fences.repair.enabled', 'false');+ const paused = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [stub.spec] });+ expect(paused).toMatchObject({ status: 'skipped', details: { reason: 'disabled', kinds: ['connector-fences'] } });+ expect(paused.summary).toContain('gbrain config set fences.repair.enabled true');+ expect(paused.summary).toContain('gbrain repair content');+ expect(stub.plans).toHaveLength(0);+ await engine.setConfig('fences.repair.enabled', 'true');+ const resumed = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [stub.spec] });+ expect(resumed.status).toBe('ok');+ expect(stub.applied.map(a => a.id)).toEqual([0, 1]);+ });++ test('the deadline is min(120 s, a third of the remaining job deadline), 120 s without a job deadline', async () => {+ const t = Date.now();+ const cases: Array<[number | null, number]> = [[t + 180_000, 60_000], [t + 3_600_000, CONTENT_REPAIR_PHASE_BUDGET_MS], [null, CONTENT_REPAIR_PHASE_BUDGET_MS]];+ for (const [deadlineAtMs, budget] of cases) {+ const stub = stubKind('connector-fences', 1);+ const result = await runContentRepairPhase(engine, { dryRun: false, deadlineAtMs, kinds: ['connector-fences'], registry: [stub.spec], now: () => t });+ expect(result.details.time_budget_ms).toBe(budget);+ expect(stub.plans[0]?.opts?.deadline).toBe(t + budget);+ expect(stub.applied[0]?.deadline).toBe(t + budget);+ }+ const stub = stubKind('connector-fences', 1);+ const late = await runContentRepairPhase(engine, { dryRun: false, deadlineAtMs: t, kinds: ['connector-fences'], registry: [stub.spec], now: () => t });+ expect(late).toMatchObject({ status: 'skipped', details: { reason: 'deadline' } });+ expect(stub.plans).toHaveLength(0);+ });++ test('a dry run previews the kind and writes nothing', async () => {+ const stub = stubKind('connector-fences', 2);+ const result = await runContentRepairPhase(engine, { dryRun: true, kinds: ['connector-fences'], registry: [stub.spec] });+ expect(result.details).toMatchObject({ mode: 'dry_run', candidates: 2, repaired: 0 });+ expect(result.summary).toContain('dry run: 2 content candidate(s) planned across connector-fences, nothing written');+ expect(stub.applied).toHaveLength(0);+ });+});++describe('content_repair phase report', () => {+ test('counts by kind, outcome and reason, the lane spend and the oldest hold age; needs_human holds point at sync status', async () => {+ const t = Date.now();+ const stub = stubKind('connector-fences', 3, {+ onApply: item => item.cursor.id === 0 ? { llm_usd: 0.02, detail: { tier: 'llm' } }+ : item.cursor.id === 1 ? { applied: false, outcome: 'held', reason: 'merge_recommended' } : { applied: false, outcome: 'skipped', reason: 'sync_in_progress' },+ verification: { oldest_hold_at: new Date(t - 30 * 3_600_000).toISOString() },+ });+ const result = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [stub.spec], now: () => t });+ expect(result.status).toBe('ok');+ expect(result.details).toMatchObject({ mode: 'apply', kinds: ['connector-fences'], candidates: 3, repaired: 1, llm_usd: 0.02, oldest_hold_age_hours: 30, stopped_reason: null,+ held_by_reason: { merge_recommended: 1, sync_in_progress: 1 } });+ expect((result.details.by_kind as Record<string, { outcomes: Record<string, number> }>)['connector-fences']!.outcomes).toEqual({ repaired: 1, held: 1, skipped: 1 });+ expect(result.summary).toContain('repaired 1 of 3 content candidate(s) across connector-fences ($0.0200 on the model)');+ expect(result.summary).toContain('2 still held (merge_recommended 1, sync_in_progress 1)');+ expect(result.summary).toContain('the oldest unresolved hold is 30 h old');+ expect(result.summary).toContain('1 wait for a person: gbrain sync status');+ expect((result.details.fix as { argv?: string[] }).argv).toEqual(['gbrain', 'repair', 'content']);+ });++ test('a stop other than the time budget reports warn with the kind fix; a time-budget stop stays ok', async () => {+ const fix = { argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<n>'], consent: ['paid' as const], actor: 'user' as const, why: 'cap', requires_exclusive: false };+ const stub = stubKind('connector-fences', 3, { onApply: () => ({ stop: { reason: 'budget_exhausted', message: 'The daily content repair cap is spent.', fix } }) });+ const result = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [stub.spec] });+ expect(result.status).toBe('warn');+ expect(result.details).toMatchObject({ stopped_reason: 'budget_exhausted', fix });+ expect(result.summary).toContain('Stopped (connector-fences: budget_exhausted): The daily content repair cap is spent.');+ const timed = stubKind('connector-fences', 2, { onApply: () => ({ stop: { reason: 'time_budget', message: 'out of time' } }) });+ const ok = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [timed.spec] });+ expect(ok.status).toBe('ok');+ expect(ok.details.stopped_reason).toBe('time_budget');+ expect(ok.summary).toContain('the next maintenance run resumes');+ });++ test('an internal error is contained as warn without its message; an aborted cycle still propagates', async () => {+ const failing = stubKind('connector-fences', 1, { plan: () => { throw new OperationError('database_error' as never, 'boom SENTINEL-CELL-VALUE'); } });+ const result = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [failing.spec] });+ expect(result).toMatchObject({ status: 'warn', details: { reason: 'error', code: 'database_error' } });+ expect(JSON.stringify(result)).not.toContain('SENTINEL-CELL-VALUE');+ expect(result.summary).toContain('gbrain repair content');+ const controller = new AbortController();+ controller.abort();+ await expect(runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [failing.spec], signal: controller.signal })).rejects.toThrow('SENTINEL-CELL-VALUE');+ });+});++describe('content_repair scheduling lanes', () => {+ test('brain-global, right after fence_repair, classified writes, never a source or freshness phase', () => {+ expect(PHASE_SCOPE.content_repair).toBe('global');+ expect(ALL_PHASES.indexOf('content_repair')).toBe(ALL_PHASES.indexOf('fence_repair') + 1);+ expect(GLOBAL_PHASES).toContain('content_repair');+ expect(MAINTENANCE_PHASES).toContain('content_repair');+ expect(SOURCE_PHASES).not.toContain('content_repair');+ expect(SOURCE_FRESHNESS_PHASES).not.toContain('content_repair');+ expect(CONNECTOR_SOURCE_PHASES).not.toContain('content_repair');+ expect(MANAGED_PHASE_TABLE.content_repair.class).toBe('writes');+ expect(normalizeQueuedSourcePhases(['sync', 'content_repair'], 'repo-a')).toEqual({ phases: ['sync'], rejected: ['content_repair'] });+ });+});diff --git a/test/fence-hold-surfaces.test.ts b/test/fence-hold-surfaces.test.tsindex b8f1db2a2c..07a9ee3083 100644--- a/test/fence-hold-surfaces.test.ts+++ b/test/fence-hold-surfaces.test.ts@@ -58,6 +58,8 @@ const cli = { transport: 'cli' as const, isCallable: () => false, preapproved: (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] : [])];+// #6377: the source-level route names the content-repair lane; one hold's own fix stays that file's fence preview.+const lane = ['gbrain', 'repair', 'content', '--source', 'notes-example'];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', () => {@@ -168,16 +170,20 @@ describe('structured location (D16)', () => {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(preview());- expect(fences.commands).toEqual(['gbrain repair fences --source notes-example']);+ expect(fences.argv).toEqual(lane);+ expect(fences.commands).toEqual(['gbrain repair content --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.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(mixed.commands).toEqual(['gbrain repair frontmatter --source notes-example', 'gbrain repair content --source notes-example']);+ // #6377: slug-conflict holds take the same lane route as fence holds.+ const slugs = holdRepairSteps('notes-example', { fences: 0, others: 0, slug_conflicts: 1 });+ expect(slugs.argv).toEqual(lane);+ expect(slugs.text).not.toContain('frontmatter');+ expect(holdRepairSteps('notes-example', { fences: 1, others: 0 }, ACTIVE).text).toContain('the next maintenance run repairs the fence and slug-conflict holds it can by itself');+ expect(holdRepairSteps('notes-example', { fences: 1, others: 0 }, INACTIVE).text).toContain('nothing repairs the fence and slug-conflict 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');});@@ -185,21 +191,23 @@ describe('source-level routing on every surface (D6)', () => {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!.argv).toEqual(lane);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).toMatchObject({ actor: 'host_admin', argv: lane });+ expect(remote.fix!.user_message).toContain("'gbrain repair content --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'");+ expect(mixed.user_message).toContain("'gbrain repair content --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");- expect(frontmatter.user_message).not.toContain('repair fences');+ expect(frontmatter.user_message).not.toContain('repair content');expect(recordRoute(fenceHold())).toEqual({ fences: 1, others: 0 });+ expect(recordRoute({ code: 'frontmatter_slug_conflict' })).toEqual({ fences: 0, others: 0, slug_conflicts: 1 });+ expect(hostOperatorFix([{ source_id: 'notes-example', route: recordRoute({ code: 'frontmatter_slug_conflict' }) }], 'Held.').user_message).toContain("'gbrain repair content --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)', () => {diff --git a/test/fence-refusal.test.ts b/test/fence-refusal.test.tsindex 2821a322e4..c48c0c8701 100644--- a/test/fence-refusal.test.ts+++ b/test/fence-refusal.test.ts@@ -138,7 +138,7 @@ describe('every PR1 reason routes to the fence repair, never to frontmatter repameta: { 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']);+ expect(steps.argv).toEqual(['gbrain', 'repair', 'content', '--source', 'default']); // #6377: the source-level step is the content laneconst texts = [error.message, error.suggestion, JSON.stringify(error.fix), receipt?.suggestion, hold.message, JSON.stringify(fix),writeFailureDiagnostic('invalid_params', error.message).suggestion, steps.text];for (const text of texts) expect(text ?? '').not.toContain('repair frontmatter');diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex ab3c0459d5..3ae7b03a79 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -5963,7 +5963,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"tail_exposure_approval\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unclosed_ambiguous_tail\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/held-files-walkthrough.test.ts b/test/held-files-walkthrough.test.tsindex 059c45cde8..0b707038f6 100644--- a/test/held-files-walkthrough.test.ts+++ b/test/held-files-walkthrough.test.ts@@ -179,7 +179,7 @@ test('#6278: a source holding frontmatter, fence and preparation-stalled files rconst coverage = (await readHeldCoverage(engine, { sourceId: id }))[0]!;expect(coverageRoute(coverage)).toEqual({ fences: 1, others: 1, stalled: 1 });const steps = holdRepairSteps(id, coverageRoute(coverage));- expect(steps.commands).toEqual([`gbrain repair frontmatter --source ${id}`, `gbrain repair fences --source ${id}`, `gbrain sources writer status --source ${id} --json`,+ expect(steps.commands).toEqual([`gbrain repair frontmatter --source ${id}`, `gbrain repair content --source ${id}`, `gbrain sources writer status --source ${id} --json`,`gbrain sources status ${id} --json`, `gbrain sources retry-held ${id}`, `gbrain sync --source ${id} --no-pull`]);expect(steps.text).toContain('preparation-stalled hold(s) are not file problems and need no repair');expect(result.holds_fix!.why).toContain('the 1 preparation-stalled hold(s) are not file problems and need no repair');@@ -194,7 +194,7 @@ test('#6278: a source holding frontmatter, fence and preparation-stalled files rexpect(check.status).toBe('warn');expect(check.details).toMatchObject({ held: 3, sources: [{ source_id: id, fences: 1, stalled: 1, held: 3 }] });expect(check.message).toContain(`gbrain sources writer status --source ${id} --json`);- expect(check.message).toContain('gbrain repair fences');+ expect(check.message).toContain('gbrain repair content'); // #6377: fence holds route to the content laneexpect(check.message).toContain('gbrain repair frontmatter');// retry-held schedules all three and keeps the run's options on the follow-up sync.const retry = await retryHeld(engine, id);diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.tsindex a2f4b7970a..26e4daeb13 100644--- a/test/managed-phase-matrix.test.ts+++ b/test/managed-phase-matrix.test.ts@@ -145,6 +145,15 @@ const MATRIX: Record<CyclePhase, Entry> = {expect(result.details).toMatchObject({ mode: 'apply', repaired: 0, stopped_reason: null, llm_usd: 0 });},},+ content_repair: {+ // #6377: the lane minus `fences`; with no other content-repair kind registered in this release the phase runs nothing+ // and says so, so it must finish skipped with `no_kinds` and never refuse or stop.+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'people/alice-example', page('person', 'Alice', 'A person with no holds.')),+ assert: async ({ result }) => {+ expect(result.status).toBe('skipped');+ expect(result.details).toMatchObject({ reason: 'no_kinds', kinds: [] });+ },+ },synthesize: {seed: async ({ engine, sourceId, root }) => {await put(engine, sourceId, 'people/example', page('note', 'Example', 'Example evidence.'));diff --git a/test/persistence-sync-fence-holds.test.ts b/test/persistence-sync-fence-holds.test.tsindex 368906dc15..111c8bbee7 100644--- a/test/persistence-sync-fence-holds.test.ts+++ b/test/persistence-sync-fence-holds.test.ts@@ -118,7 +118,7 @@ test('a malformed fence among clean files: the sync finishes, holds that file wiexpect(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]);+ expect(result.holds_fix!.argv).toEqual(['gbrain', 'repair', 'content', '--source', s.id]); // #6377: the source-level step is the content lanefor (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 9');@@ -130,14 +130,14 @@ test('a malformed fence among clean files: the sync finishes, holds that file wiconst 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);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.+ // Doctor routes a fence-only source to the content lane's preview (#6377), never to frontmatter repair.const doctor = await gitHeldFilesCheck(engine, [s.id]);- 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).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'repair', 'content', '--source', s.id] }, details: { fences: 1, auto_repair: { active: false } } });+ expect(doctor.message).toContain(`gbrain repair content --source ${s.id}`);expect(doctor.message).not.toContain('repair frontmatter');- // retry-held names the fence repair preview for what still refuses.+ // retry-held names the content lane's 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).toContain(`gbrain repair content --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');diff --git a/test/phase-scope-coverage.test.ts b/test/phase-scope-coverage.test.tsindex 38b3a33e3a..6018f6df5d 100644--- a/test/phase-scope-coverage.test.ts+++ b/test/phase-scope-coverage.test.ts@@ -41,7 +41,7 @@ describe('PHASE_SCOPE coverage', () => {expect(invalid).toEqual([]);});- test('all 27 phases covered (regression on accidental omission)', () => {+ test('all 28 phases covered (regression on accidental omission)', () => {// Pin the count so a future PR that adds a phase to ALL_PHASES// without updating PHASE_SCOPE notices here too. The v0.39.1.0// master merge brought in the 17th phase (`schema-suggest`); v0.41@@ -51,9 +51,9 @@ describe('PHASE_SCOPE coverage', () => {// #2653 adds 'drift' for 23; #5876 adds 'chronicle' for 24; GBRA-40 Lane D// adds 'facts_drain' for 25.// Temporal typed edges adds 'edge_contradictions' for 26.- // #6188 adds 'fence_repair' for 27.- expect(ALL_PHASES.length).toBe(27);- expect(Object.keys(PHASE_SCOPE).length).toBe(27);+ // #6188 adds 'fence_repair' for 27; #6377 adds 'content_repair' for 28.+ expect(ALL_PHASES.length).toBe(28);+ expect(Object.keys(PHASE_SCOPE).length).toBe(28);});test('embed remains global (the headline brain-wide phase)', () => {diff --git a/test/repair-content.test.ts b/test/repair-content.test.tsnew file mode 100644index 0000000000..f6085debc6--- /dev/null+++ b/test/repair-content.test.ts@@ -0,0 +1,131 @@+/**+ * #6377 `gbrain repair content` (src/commands/repair-content.ts), the+ * content-repair lane as one command.+ *+ * Protects: `content` is parsed like a kind but is a lane, never a RepairKind+ * (its flags are the lane's: --only/--skip, --no-llm, --max-usd, --expect with+ * one hash per kind, --apply, --json; --slug, --yes and --all refuse); the+ * preview runs every lane kind read-only over the same selection and prints+ * each kind's own hash plus the exact apply command; `--apply --expect <hash>`+ * applies exactly that set through the real `fences` kind on a managed source+ * (the held file is repaired, committed through the Git effect and its hold+ * cleared); a hash count that does not match the lane refuses before any kind+ * runs; the exit verdict follows a kind's stop. Sentinel text never reaches an+ * output line. The two-kind contract (allowance flow, per-kind hashes, the+ * time-budget stop) is pinned in test/cycle-content-repair.test.ts with stub+ * kinds, since the CLI runs the registered lane.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readGitHold } from '../src/core/persistence/sync-holds.ts';+import { CONTENT_LANE, parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import type { RepairResult } from '../src/core/repair/core.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-content-'));+let engine: BrainEngine;+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_FENCE_REPAIR_SCAN_MS: '60000', OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };+const HOLDER = 'Alice Example', MCLAIM = 'Sentinelmanualrc77 opens an office';+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+const T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';+const md = (title: string, body: string) => `---\ntitle: ${title}\n---\nA synthetic page.\n\n${body}`;+const holder = () => `${T}\n${TH}\n| 1 | Synthetic take | take | ${HOLDER} | 0.7 | 2026-01 | chat |\n${TE}\n`;+const manual = () => `${FB}\n${FH}\n| 1 | ${MCLAIM} | fact | 0.9 | sideways | high | 2026-01-01 | | chat | ctx |\n${FBE}\n`;+/** Claim text never reaches an output; the preview's per-file diff shows the holder cell to the operator by design (D14), so the holder is checked on the apply result only. */+const expectNoSecrets = (text: string, secrets: string[] = ['Sentinelmanualrc77', HOLDER]) => { for (const secret of secrets) expect(text).not.toContain(secret); };++async function fixture(files: Record<string, string>) {+ const id = `rc-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ for (const [path, body] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), body); }+ commit(root, 'fixture');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };+}++async function cli(args: string[]): Promise<string> {+ const out: string[] = [];+ const log = console.log;+ console.log = (...parts: unknown[]) => { out.push(parts.join(' ')); };+ try { await runRepairCommand(engine, args); } finally { console.log = log; }+ return out.join('\n');+}++interface LaneJson { lane: string; mode: string; kinds: string[]; results: RepairResult[]; preview_hashes: Record<string, string | null>; cost: { llm_usd: number; llm_allowance_remaining_usd: number | null }; stopped: unknown[]; apply_command: string }++beforeAll(async () => { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; }, 60_000);+beforeEach(() => { _resetCliExitVerdictForTests(); });+afterAll(async () => { await withEnv(env, async () => { await disposePersistenceConsumer(engine); }); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++test('content parses like a kind but is a lane: its flags are accepted, the kind-only ones refuse', () => {+ expect(CONTENT_LANE).toBe('content');+ const parsed = parseRepairArgs(['content', '--source', 'notes', '--only', 'a.md', '--skip', 'b.md', '--no-llm', '--max-usd', '0.5', '--apply', '--expect', 'h1,h2', '--json', '--diff']);+ expect(parsed).toMatchObject({ kind: 'content', source: 'notes', only: ['a.md'], skip: ['b.md'], noLlm: true, maxUsd: 0.5, apply: true, expect: 'h1,h2', json: true, diff: true });+ expect(() => parseRepairArgs(['content', '--slug', 'people/a'])).toThrow(/--slug applies only to gbrain repair fences/);+ expect(() => parseRepairArgs(['content', '--yes'])).toThrow(/--yes/);+ expect(() => parseRepairArgs(['content', '--include-ambiguous'])).toThrow(/--include-ambiguous applies only/);+ expect(() => parseRepairArgs(['content', 'fences'])).toThrow(/at most one kind/);+});++test('preview runs the lane read-only and prints each kind\'s hash; --apply --expect <hash> repairs the held file through the fences kind and clears its hold; a wrong hash count refuses', async () => withEnv(env, async () => {+ const f = await fixture({ 'people/alice-example.md': md('Alice Example', 'A synthetic person.\n'), 'notes/a.md': md('A', 'Plain.\n') });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ writeFileSync(join(f.root, 'people/holder.md'), md('Holder', holder()));+ writeFileSync(join(f.root, 'people/manual.md'), md('Manual', manual()));+ commit(f.root, 'two malformed fences');+ expect((await performManagedSync(engine, f.opts)).held?.map(hold => hold.path).sort()).toEqual(['people/holder.md', 'people/manual.md']);+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.id]);++ await expect(cli(['content', '--all'])).rejects.toMatchObject({ code: 'invalid_params' });+ await expect(cli(['content', '--source', f.id, '--apply', '--expect', 'h1,h2'])).rejects.toMatchObject({ code: 'invalid_params' });+ expect(await readGitHold(engine, f.id, source.incarnation, 'people/holder.md')).not.toBeNull();++ const preview = JSON.parse(await cli(['content', '--source', f.id, '--json'])) as LaneJson;+ expect(preview).toMatchObject({ lane: 'content', mode: 'dry_run', kinds: ['fences'], stopped: [] });+ const hash = preview.preview_hashes.fences!;+ expect(hash).toMatch(/^[0-9a-f]{16,}$/);+ const fences = preview.results[0]!;+ expect(fences.kind).toBe('fences');+ expect(fences.preview_hash).toBe(hash);+ expect(fences.listing!.map(entry => [entry.item, entry.class]).sort()).toEqual([[`${f.id}:people/holder.md`, 'resolver'], [`${f.id}:people/manual.md`, 'enum_unmapped']]);+ expect(preview.apply_command).toBe(`gbrain repair content --source ${f.id} --apply --expect ${hash}`);+ expect(fences.apply_command).toBe(`gbrain repair fences --source ${f.id} --apply --expect ${hash}`);+ expect(currentExitCode()).toBe(0);++ const human = await cli(['content', '--source', f.id]);+ expect(human).toContain(`lane content (fences)`);+ expect(human).toContain(`preview hashes: fences=${hash}`);+ expect(human).toContain(`apply: gbrain repair content --source ${f.id} --apply --expect ${hash}`);+ expectNoSecrets(human, ['Sentinelmanualrc77']);++ const applied = JSON.parse(await cli(['content', '--source', f.id, '--apply', '--expect', hash, '--json'])) as LaneJson;+ expect(applied).toMatchObject({ mode: 'apply', kinds: ['fences'], preview_hashes: { fences: hash }, stopped: [] });+ expect(applied.results[0]).toMatchObject({ mode: 'apply', applied: 1, outcomes: { repaired: 1 } });+ expect(applied.results[0]!.outcome_items![0]).toMatchObject({ outcome: 'repaired', detail: { tier: 'resolver', path: 'people/holder.md', hold_cleared: true } });+ expect(await readGitHold(engine, f.id, source.incarnation, 'people/holder.md')).toBeNull();+ expect(await readGitHold(engine, f.id, source.incarnation, 'people/manual.md')).not.toBeNull();+ expect(readFileSync(join(f.root, 'people/holder.md'), 'utf8')).toContain('people/alice-example');+ expectNoSecrets(JSON.stringify(applied));++ // The hash is spent: the same apply is preview_changed; a bare apply finds nothing left to repair but the manual hold.+ await expect(cli(['content', '--source', f.id, '--apply', '--expect', hash, '--json'])).rejects.toMatchObject({ code: 'preview_changed' });+ const again = JSON.parse(await cli(['content', '--source', f.id, '--apply', '--json'])) as LaneJson;+ expect(again.results[0]).toMatchObject({ mode: 'apply', applied: 0, residuals: { enum_unmapped: 1 } });+}), 180_000);diff --git a/test/sync-status-unblock.test.ts b/test/sync-status-unblock.test.tsindex f61484e281..04eb6348c2 100644--- a/test/sync-status-unblock.test.ts+++ b/test/sync-status-unblock.test.ts@@ -4,6 +4,15 @@* `gbrain sync unblock --apply` performs the safe action for each hold that has* one and refuses the rest by name. The classifier table and the runbook are* pinned to each other in `test/sync-runbook-table.test.ts`. Synthetic content.+ *+ * #6377 (T4): `unblock --apply` repairs an `invalid_fence` hold through the+ * `fences` kind of the content-repair lane on exactly that path, reports the+ * structured per-path outcome with its location-only receipt, schedules the+ * re-screen and prints the sync; a hold whose stored state needs a person (a+ * manual fence reason) is listed and never retried, and `sync status` says so;+ * `--no-llm` keeps the model-tier file held; `--no-repair` refuses every+ * repair-class hold as before. Sentinel claim text must never reach a hold,+ * an outcome, a receipt or a printed line.*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';@@ -18,7 +27,8 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { readSyncStatus, unblockSync } from '../src/core/persistence/sync-status.ts';import { classifySyncFault, HOLD_ATTEMPTS_NEEDS_HUMAN, SYNC_FAULT_TABLE } from '../src/core/persistence/sync-fault-class.ts';-import { readGitHoldRetryPaths, readGitHold } from '../src/core/persistence/sync-holds.ts';+import { readGitHoldRetryPaths, readGitHold, readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import { runSyncUnblock } from '../src/commands/sync/operator.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { withEnv } from './helpers/with-env.ts';@@ -144,3 +154,108 @@ test('status reports an older release\'s recorded failure as a retryable page faexpect(converted).toMatchObject({ status: 'synced', held: [{ path: 'b.md', code: 'worktree_dirty' }] });expect((await readSyncStatus(engine, f.id)).last_error).toBeNull();}), 120_000);++// #6377: fence fixtures (as test/repair-fences.test.ts builds them). Sentinel strings must never leave a file.+const CLAIM = 'Sentinelclaimub77 ships quarterly', HOLDER = 'Alice Example', MCLAIM = 'Sentinelmanualub77 opens an office';+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+const T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';+const md = (title: string, body: string) => `---\ntitle: ${title}\n---\nA synthetic page.\n\n${body}`;+/** Tier 2: a display-name holder, resolved against people/alice-example. */+const holder = () => `${T}\n${TH}\n| 1 | Synthetic take | take | ${HOLDER} | 0.7 | 2026-01 | chat |\n${TE}\n`;+/** Manual: a visibility word with no mapping. */+const manual = () => `${FB}\n${FH}\n| 1 | ${MCLAIM} | fact | 0.9 | sideways | high | 2026-01-01 | | chat | ctx |\n${FBE}\n`;+/** Tier 3: rows but no header. */+const noHeader = () => `${FB}\n| 1 | ${CLAIM} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |\n${FBE}\n`;+const expectNoSecrets = (value: unknown) => { const text = typeof value === 'string' ? value : JSON.stringify(value); for (const secret of ['Sentinelclaimub77', 'Sentinelmanualub77', HOLDER]) expect(text).not.toContain(secret); };++async function printed(run: () => Promise<void>): Promise<string> {+ const out: string[] = [];+ const log = console.log;+ console.log = (...parts: unknown[]) => { out.push(parts.join(' ')); };+ try { await run(); } finally { console.log = log; }+ return out.join('\n');+}++test('#6377: unblock --apply repairs an invalid_fence hold through the fences kind, lists structured outcomes, schedules the re-screen and prints the sync; a manual hold is listed, not retried; --no-llm and --no-repair', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_FENCE_REPAIR_SCAN_MS: '60000', OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined }, async () => {+ const f = await fixture({ 'a.md': note('Alpha one.') });+ mkdirSync(join(f.root, 'people'));+ writeFileSync(join(f.root, 'people/alice-example.md'), md('Alice Example', 'A synthetic person.\n'));+ commit(f.root, 'a person page');+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ writeFileSync(join(f.root, 'people/holder.md'), md('Holder', holder()));+ writeFileSync(join(f.root, 'people/manual.md'), md('Manual', manual()));+ writeFileSync(join(f.root, 'people/model.md'), md('Model', noHeader()));+ commit(f.root, 'three malformed fences');+ const synced = await performManagedSync(engine, f.opts);+ expect(synced.held?.map(hold => [hold.path, hold.code, hold.reason]).sort()).toEqual([['people/holder.md', 'invalid_fence', 'holder_unresolved'], ['people/manual.md', 'invalid_fence', 'enum_unmapped'], ['people/model.md', 'invalid_fence', 'no_header']]);+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.id]);++ // status: the manual hold needs a person and says why; the other two are actionable, and next is the unblock apply naming the repairs.+ const status = await readSyncStatus(engine, f.id);+ const byPath = new Map(status.holds.map(hold => [hold.path, hold]));+ expect(byPath.get('people/manual.md')).toMatchObject({ code: 'invalid_fence', class: 'page', safe_actions: ['none'], needs_human: true });+ expect(byPath.get('people/manual.md')!.human_reason).toContain('enum_unmapped');+ expect(byPath.get('people/holder.md')).toMatchObject({ safe_actions: ['repair'], needs_human: false });+ expect(byPath.get('people/model.md')).toMatchObject({ safe_actions: ['repair'], needs_human: false });+ expect(status.needs_human).toBe(true);+ expectNoSecrets(status);++ // --no-repair: every repair-class hold is refused by name, as before #6377.+ const refuseOnly = await unblockSync(engine, f.id, { apply: true, noRepair: true });+ expect(refuseOnly.applied).toEqual([]);+ expect(refuseOnly.refused.map(entry => [entry.path, entry.needs_human]).sort()).toEqual([['people/holder.md', false], ['people/manual.md', true], ['people/model.md', false]]);+ expect(refuseOnly.refused.find(entry => entry.path === 'people/holder.md')!.reason).toContain('not something unblock performs');+ expect(await readGitHoldRetryPaths(engine, f.id, source.incarnation)).toEqual([]);++ // Preview: the two actionable holds would be repaired, the manual one is listed with its state; nothing is written.+ const preview = await unblockSync(engine, f.id, { apply: false });+ expect(preview.applied.map(entry => [entry.path, entry.action, entry.action === 'repair' ? entry.repair.outcome : null]).sort()).toEqual([['people/holder.md', 'repair', 'skipped'], ['people/model.md', 'repair', 'skipped']]);+ expect(preview.refused.map(entry => [entry.path, entry.needs_human])).toEqual([['people/manual.md', true]]);+ expect(preview.refused[0]!.reason).toContain('enum_unmapped');+ expect(preview.next).toMatchObject({ argv: ['gbrain', 'sync', 'unblock', '--source', f.id, '--apply', '--json'] });+ expect(preview.next!.why).toContain('hash-bound repairs');+ expect(await readGitHold(engine, f.id, source.incarnation, 'people/holder.md')).not.toBeNull();++ // --no-llm apply: the resolver repairs the holder file (receipt, re-screen scheduled, the sync printed); the model-tier file stays held llm_disabled; the manual one is listed, not retried.+ const applied = await unblockSync(engine, f.id, { apply: true, noLlm: true });+ const repaired = applied.applied.find(entry => entry.path === 'people/holder.md');+ expect(repaired).toMatchObject({ code: 'invalid_fence', action: 'repair', repair: { kind: 'fences', outcome: 'repaired', tier: 'resolver', receipt: { mode: 'managed', path: 'people/holder.md', tier: 'resolver', classes: 'holder_verified', hold_cleared: true, committed: 'queued' } } });+ expect(repaired!.action === 'repair' && repaired!.repair.next).toMatchObject({ argv: ['gbrain', 'sync', '--source', f.id, '--no-pull', '--no-embed', '--no-extract'] });+ const model = applied.applied.find(entry => entry.path === 'people/model.md');+ // The model-tier file was kept out of the plan (--no-llm); the kind recorded llm_disabled on its hold, and its next step is the hold's own paid fix.+ expect(model).toMatchObject({ action: 'repair', repair: { kind: 'fences', outcome: 'held', reason: 'llm_disabled', next: { argv: ['gbrain', 'config', 'set', 'fences.repair.llm', 'true'], consent: ['paid'] } } });+ expect(applied.refused.map(entry => entry.path)).toEqual(['people/manual.md']);+ expect(applied.next).toMatchObject({ argv: ['gbrain', 'sync', '--source', f.id, '--no-pull', '--no-embed', '--no-extract'] });+ expect(applied.next!.why).toContain('1 repaired by the content-repair lane');+ expect(await readGitHoldRetryPaths(engine, f.id, source.incarnation)).toEqual(['people/holder.md']);+ expect(readFileSync(join(f.root, 'people/holder.md'), 'utf8')).toContain('people/alice-example');+ expectNoSecrets(applied);+ const holdsAfter = (await readGitSourceHolds(engine, { sourceIds: [f.id] }))[0]!.holds;+ expect(holdsAfter.find(hold => hold.path === 'people/model.md')?.meta.fence_repair?.reason).toBe('llm_disabled');+ expect(holdsAfter.find(hold => hold.path === 'people/manual.md')?.meta.fence_repair).toBeUndefined();+ expectNoSecrets(holdsAfter);++ // The printed sync imports the repaired file; the hold set is the manual one and the model-tier one.+ const after = await performManagedSync(engine, f.opts);+ expect(after.status).toBe('synced');+ expect(await readGitHold(engine, f.id, source.incarnation, 'people/holder.md')).toBeNull();+ expect((await readSyncStatus(engine, f.id)).holds.map(hold => hold.path).sort()).toEqual(['people/manual.md', 'people/model.md']);++ // Idempotent: the second apply finds the model-tier hold in its recorded paid state (llm_disabled) and lists it beside the manual one; nothing is retried.+ const text = await printed(() => runSyncUnblock(engine, ['--source', f.id, '--apply', '--no-llm']));+ expect(text).toContain('0 held file(s) scheduled for a re-screen, 2 refused');+ expect(text).toContain('people/manual.md: invalid_fence refused');+ expect(text).toContain('people/model.md: invalid_fence refused');+ expect(text).toContain('llm_disabled');+ expect(text).toContain('NEEDS HUMAN');+ expectNoSecrets(text);+ expect(await readGitHoldRetryPaths(engine, f.id, source.incarnation)).toEqual([]);+ // --json renders each refusal's fix with its next verb (the paid setting asks the user).+ const json = JSON.parse(await printed(() => runSyncUnblock(engine, ['--source', f.id, '--no-llm', '--json']))) as { applied: unknown[]; refused: Array<{ path: string; fix: { next: string } }> };+ expect(json.applied).toEqual([]);+ expect(json.refused.find(entry => entry.path === 'people/model.md')?.fix.next).toBe('ask_user');+ expect(json.refused.find(entry => entry.path === 'people/manual.md')?.fix.next).toBe('run');+ expectNoSecrets(json);+}), 180_000);